blob: dd46dfb3d4e8073aeac84294c551e38681337456 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000068 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000069 };
Chris Lattner8123a952008-04-10 02:22:51 +000070
Chris Lattner9e979552008-04-12 23:52:44 +000071 /// VisitExpr - Visit all of the children of this expression.
72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000074 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000075 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000076 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000077 }
78
Chris Lattner9e979552008-04-12 23:52:44 +000079 /// VisitDeclRefExpr - Visit a reference to a declaration, to
80 /// determine whether this declaration can be used in the default
81 /// argument expression.
82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000084 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85 // C++ [dcl.fct.default]p9
86 // Default arguments are evaluated each time the function is
87 // called. The order of evaluation of function arguments is
88 // unspecified. Consequently, parameters of a function shall not
89 // be used in default argument expressions, even if they are not
90 // evaluated. Parameters of a function declared before a default
91 // argument expression are in scope and can hide namespace and
92 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000093 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000096 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000097 // C++ [dcl.fct.default]p7
98 // Local variables shall not be used in default argument
99 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000100 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000101 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000103 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105
Douglas Gregor3996f232008-11-04 13:41:56 +0000106 return false;
107 }
Chris Lattner9e979552008-04-12 23:52:44 +0000108
Douglas Gregor796da182008-11-04 14:32:21 +0000109 /// VisitCXXThisExpr - Visit a C++ "this" expression.
110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111 // C++ [dcl.fct.default]p8:
112 // The keyword this shall not be used in a default argument of a
113 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000114 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 diag::err_param_default_argument_references_this)
116 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000117 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000118
John McCall045d2522013-04-09 01:56:28 +0000119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120 bool Invalid = false;
121 for (PseudoObjectExpr::semantics_iterator
122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123 Expr *E = *i;
124
125 // Look through bindings.
126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127 E = OVE->getSourceExpr();
128 assert(E && "pseudo-object binding without source expression?");
129 }
130
131 Invalid |= Visit(E);
132 }
133 return Invalid;
134 }
135
Douglas Gregorf0459f82012-02-10 23:30:22 +0000136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137 // C++11 [expr.lambda.prim]p13:
138 // A lambda-expression appearing in a default argument shall not
139 // implicitly or explicitly capture any entity.
140 if (Lambda->capture_begin() == Lambda->capture_end())
141 return false;
142
143 return S->Diag(Lambda->getLocStart(),
144 diag::err_lambda_capture_default_arg);
145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146}
147
Richard Smith0b0ca472013-04-10 06:11:48 +0000148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000151 // If we have an MSAny spec already, don't bother.
152 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000153 return;
154
155 const FunctionProtoType *Proto
156 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158 if (!Proto)
159 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000160
161 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000164 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000165 ClearExceptions();
166 ComputedEST = EST;
167 return;
168 }
169
Richard Smith7a614d82011-06-11 17:19:42 +0000170 // FIXME: If the call to this decl is using any of its default arguments, we
171 // need to search them for potentially-throwing calls.
172
Sean Hunt001cad92011-05-10 00:49:42 +0000173 // If this function has a basic noexcept, it doesn't affect the outcome.
174 if (EST == EST_BasicNoexcept)
175 return;
176
177 // If we have a throw-all spec at this point, ignore the function.
178 if (ComputedEST == EST_None)
179 return;
180
181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
183 if (EST == EST_DynamicNone) {
184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
187 }
188
189 // Check out noexcept specs.
190 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
198
199 // noexcept(false) -> no spec on the new function
200 if (NR == FunctionProtoType::NR_Throw) {
201 ClearExceptions();
202 ComputedEST = EST_None;
203 }
204 // noexcept(true) won't change anything either.
205 return;
206 }
207
208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214 EEnd = Proto->exception_end();
215 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000217 Exceptions.push_back(*E);
218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson5e300d12009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000359}
360
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
398 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000403 }
404 }
405}
406
David Majnemerf6a144f2013-06-25 23:09:30 +0000407static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
408 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
409 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
410 if (!PVD->hasDefaultArg())
411 return false;
412 if (!PVD->hasInheritedDefaultArg())
413 return true;
414 }
415 return false;
416}
417
Craig Topper1a6eac82012-09-21 04:33:26 +0000418/// MergeCXXFunctionDecl - Merge two declarations of the same C++
419/// function, once we already know that they have the same
420/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
421/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000422bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
423 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000424 bool Invalid = false;
425
Chris Lattner3d1cee32008-04-08 05:04:30 +0000426 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000427 // For non-template functions, default arguments can be added in
428 // later declarations of a function in the same
429 // scope. Declarations in different scopes have completely
430 // distinct sets of default arguments. That is, declarations in
431 // inner scopes do not acquire default arguments from
432 // declarations in outer scopes, and vice versa. In a given
433 // function declaration, all parameters subsequent to a
434 // parameter with a default argument shall have default
435 // arguments supplied in this or previous declarations. A
436 // default argument shall not be redefined by a later
437 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000438 //
439 // C++ [dcl.fct.default]p6:
440 // Except for member functions of class templates, the default arguments
441 // in a member function definition that appears outside of the class
442 // definition are added to the set of default arguments provided by the
443 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000444 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
445 ParmVarDecl *OldParam = Old->getParamDecl(p);
446 ParmVarDecl *NewParam = New->getParamDecl(p);
447
James Molloy9cda03f2012-03-13 08:55:35 +0000448 bool OldParamHasDfl = OldParam->hasDefaultArg();
449 bool NewParamHasDfl = NewParam->hasDefaultArg();
450
451 NamedDecl *ND = Old;
452 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
453 // Ignore default parameters of old decl if they are not in
454 // the same scope.
455 OldParamHasDfl = false;
456
457 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000458
Francois Pichet8d051e02011-04-10 03:03:52 +0000459 unsigned DiagDefaultParamID =
460 diag::err_param_default_argument_redefinition;
461
462 // MSVC accepts that default parameters be redefined for member functions
463 // of template class. The new default parameter's value is ignored.
464 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000465 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000466 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
467 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000468 // Merge the old default argument into the new parameter.
469 NewParam->setHasInheritedDefaultArg();
470 if (OldParam->hasUninstantiatedDefaultArg())
471 NewParam->setUninstantiatedDefaultArg(
472 OldParam->getUninstantiatedDefaultArg());
473 else
474 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000475 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000476 Invalid = false;
477 }
478 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000479
Francois Pichet8cf90492011-04-10 04:58:30 +0000480 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
481 // hint here. Alternatively, we could walk the type-source information
482 // for NewParam to find the last source location in the type... but it
483 // isn't worth the effort right now. This is the kind of test case that
484 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000485 // int f(int);
486 // void g(int (*fp)(int) = f);
487 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000488 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000489 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000490
491 // Look for the function declaration where the default argument was
492 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000493 for (FunctionDecl *Older = Old->getPreviousDecl();
494 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000495 if (!Older->getParamDecl(p)->hasDefaultArg())
496 break;
497
498 OldParam = Older->getParamDecl(p);
499 }
500
501 Diag(OldParam->getLocation(), diag::note_previous_definition)
502 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000503 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000504 // Merge the old default argument into the new parameter.
505 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000506 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000507 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000508 if (OldParam->hasUninstantiatedDefaultArg())
509 NewParam->setUninstantiatedDefaultArg(
510 OldParam->getUninstantiatedDefaultArg());
511 else
John McCall3d6c1782010-05-04 01:53:42 +0000512 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000513 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000514 if (New->getDescribedFunctionTemplate()) {
515 // Paragraph 4, quoted above, only applies to non-template functions.
516 Diag(NewParam->getLocation(),
517 diag::err_param_default_argument_template_redecl)
518 << NewParam->getDefaultArgRange();
519 Diag(Old->getLocation(), diag::note_template_prev_declaration)
520 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000521 } else if (New->getTemplateSpecializationKind()
522 != TSK_ImplicitInstantiation &&
523 New->getTemplateSpecializationKind() != TSK_Undeclared) {
524 // C++ [temp.expr.spec]p21:
525 // Default function arguments shall not be specified in a declaration
526 // or a definition for one of the following explicit specializations:
527 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000528 // - the explicit specialization of a member function template;
529 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000530 // template where the class template specialization to which the
531 // member function specialization belongs is implicitly
532 // instantiated.
533 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
534 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
535 << New->getDeclName()
536 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000537 } else if (New->getDeclContext()->isDependentContext()) {
538 // C++ [dcl.fct.default]p6 (DR217):
539 // Default arguments for a member function of a class template shall
540 // be specified on the initial declaration of the member function
541 // within the class template.
542 //
543 // Reading the tea leaves a bit in DR217 and its reference to DR205
544 // leads me to the conclusion that one cannot add default function
545 // arguments for an out-of-line definition of a member function of a
546 // dependent type.
547 int WhichKind = 2;
548 if (CXXRecordDecl *Record
549 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
550 if (Record->getDescribedClassTemplate())
551 WhichKind = 0;
552 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
553 WhichKind = 1;
554 else
555 WhichKind = 2;
556 }
557
558 Diag(NewParam->getLocation(),
559 diag::err_param_default_argument_member_template_redecl)
560 << WhichKind
561 << NewParam->getDefaultArgRange();
562 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000563 }
564 }
565
Richard Smithb8abff62012-11-28 03:45:24 +0000566 // DR1344: If a default argument is added outside a class definition and that
567 // default argument makes the function a special member function, the program
568 // is ill-formed. This can only happen for constructors.
569 if (isa<CXXConstructorDecl>(New) &&
570 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
571 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
572 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
573 if (NewSM != OldSM) {
574 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
575 assert(NewParam->hasDefaultArg());
576 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
577 << NewParam->getDefaultArgRange() << NewSM;
578 Diag(Old->getLocation(), diag::note_previous_declaration);
579 }
580 }
581
Richard Smithff234882012-02-20 23:28:05 +0000582 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000583 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000584 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000585 if (New->isConstexpr() != Old->isConstexpr()) {
586 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
587 << New << New->isConstexpr();
588 Diag(Old->getLocation(), diag::note_previous_declaration);
589 Invalid = true;
590 }
591
David Majnemerf6a144f2013-06-25 23:09:30 +0000592 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000593 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000594 // the only declaration of the function or function template in the
595 // translation unit.
596 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
597 functionDeclHasDefaultArgument(Old)) {
598 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
599 Diag(Old->getLocation(), diag::note_previous_declaration);
600 Invalid = true;
601 }
602
Douglas Gregore13ad832010-02-12 07:32:17 +0000603 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000604 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000605
Douglas Gregorcda9c672009-02-16 17:45:42 +0000606 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000607}
608
Sebastian Redl60618fa2011-03-12 11:50:43 +0000609/// \brief Merge the exception specifications of two variable declarations.
610///
611/// This is called when there's a redeclaration of a VarDecl. The function
612/// checks if the redeclaration might have an exception specification and
613/// validates compatibility and merges the specs if necessary.
614void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
615 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000616 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000617 return;
618
619 assert(Context.hasSameType(New->getType(), Old->getType()) &&
620 "Should only be called if types are otherwise the same.");
621
622 QualType NewType = New->getType();
623 QualType OldType = Old->getType();
624
625 // We're only interested in pointers and references to functions, as well
626 // as pointers to member functions.
627 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
628 NewType = R->getPointeeType();
629 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
630 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
631 NewType = P->getPointeeType();
632 OldType = OldType->getAs<PointerType>()->getPointeeType();
633 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
634 NewType = M->getPointeeType();
635 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
636 }
637
638 if (!NewType->isFunctionProtoType())
639 return;
640
641 // There's lots of special cases for functions. For function pointers, system
642 // libraries are hopefully not as broken so that we don't need these
643 // workarounds.
644 if (CheckEquivalentExceptionSpec(
645 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
646 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
647 New->setInvalidDecl();
648 }
649}
650
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651/// CheckCXXDefaultArguments - Verify that the default arguments for a
652/// function declaration are well-formed according to C++
653/// [dcl.fct.default].
654void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
655 unsigned NumParams = FD->getNumParams();
656 unsigned p;
657
658 // Find first parameter with a default argument
659 for (p = 0; p < NumParams; ++p) {
660 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000661 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000662 break;
663 }
664
665 // C++ [dcl.fct.default]p4:
666 // In a given function declaration, all parameters
667 // subsequent to a parameter with a default argument shall
668 // have default arguments supplied in this or previous
669 // declarations. A default argument shall not be redefined
670 // by a later declaration (not even to the same value).
671 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000672 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000674 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000675 if (Param->isInvalidDecl())
676 /* We already complained about this parameter. */;
677 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000678 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000679 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000680 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000681 else
Mike Stump1eb44332009-09-09 15:08:12 +0000682 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000683 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Chris Lattner3d1cee32008-04-08 05:04:30 +0000685 LastMissingDefaultArg = p;
686 }
687 }
688
689 if (LastMissingDefaultArg > 0) {
690 // Some default arguments were missing. Clear out all of the
691 // default arguments up to (and including) the last missing
692 // default argument, so that we leave the function parameters
693 // in a semantically valid state.
694 for (p = 0; p <= LastMissingDefaultArg; ++p) {
695 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000696 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000697 Param->setDefaultArg(0);
698 }
699 }
700 }
701}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000702
Richard Smith9f569cc2011-10-01 02:31:28 +0000703// CheckConstexprParameterTypes - Check whether a function's parameter types
704// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000705// diagnostic and return false.
706static bool CheckConstexprParameterTypes(Sema &SemaRef,
707 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000708 unsigned ArgIndex = 0;
709 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
710 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
711 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
712 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
713 SourceLocation ParamLoc = PD->getLocation();
714 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000715 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000716 diag::err_constexpr_non_literal_param,
717 ArgIndex+1, PD->getSourceRange(),
718 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000719 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000720 }
Joao Matos17d35c32012-08-31 22:18:20 +0000721 return true;
722}
723
724/// \brief Get diagnostic %select index for tag kind for
725/// record diagnostic message.
726/// WARNING: Indexes apply to particular diagnostics only!
727///
728/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000729static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000730 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000731 case TTK_Struct: return 0;
732 case TTK_Interface: return 1;
733 case TTK_Class: return 2;
734 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000735 }
Joao Matos17d35c32012-08-31 22:18:20 +0000736}
737
738// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
739// the requirements of a constexpr function definition or a constexpr
740// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000741// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000742//
Richard Smith86c3ae42012-02-13 03:54:03 +0000743// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
744bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000745 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
746 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000747 // C++11 [dcl.constexpr]p4:
748 // The definition of a constexpr constructor shall satisfy the following
749 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000750 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000751 const CXXRecordDecl *RD = MD->getParent();
752 if (RD->getNumVBases()) {
753 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
754 << isa<CXXConstructorDecl>(NewFD)
755 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
756 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
757 E = RD->vbases_end(); I != E; ++I)
758 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000759 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000760 return false;
761 }
Richard Smith35340502012-01-13 04:54:00 +0000762 }
763
764 if (!isa<CXXConstructorDecl>(NewFD)) {
765 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000766 // The definition of a constexpr function shall satisfy the following
767 // constraints:
768 // - it shall not be virtual;
769 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
770 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000772
Richard Smith86c3ae42012-02-13 03:54:03 +0000773 // If it's not obvious why this function is virtual, find an overridden
774 // function which uses the 'virtual' keyword.
775 const CXXMethodDecl *WrittenVirtual = Method;
776 while (!WrittenVirtual->isVirtualAsWritten())
777 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
778 if (WrittenVirtual != Method)
779 Diag(WrittenVirtual->getLocation(),
780 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000781 return false;
782 }
783
784 // - its return type shall be a literal type;
785 QualType RT = NewFD->getResultType();
786 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000787 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000788 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000789 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000790 }
791
Richard Smith35340502012-01-13 04:54:00 +0000792 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000793 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000794 return false;
795
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 return true;
797}
798
799/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000800/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000801///
Richard Smitha10b9782013-04-22 15:31:51 +0000802/// \return true if the body is OK (maybe only as an extension), false if we
803/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000804static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000805 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
806 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000807 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
808 // contain only
809 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
810 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
811 switch ((*DclIt)->getKind()) {
812 case Decl::StaticAssert:
813 case Decl::Using:
814 case Decl::UsingShadow:
815 case Decl::UsingDirective:
816 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000817 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000818 // - static_assert-declarations
819 // - using-declarations,
820 // - using-directives,
821 continue;
822
823 case Decl::Typedef:
824 case Decl::TypeAlias: {
825 // - typedef declarations and alias-declarations that do not define
826 // classes or enumerations,
827 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
828 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
829 // Don't allow variably-modified types in constexpr functions.
830 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
831 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
832 << TL.getSourceRange() << TL.getType()
833 << isa<CXXConstructorDecl>(Dcl);
834 return false;
835 }
836 continue;
837 }
838
839 case Decl::Enum:
840 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000841 // C++1y allows types to be defined, not just declared.
842 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
843 SemaRef.Diag(DS->getLocStart(),
844 SemaRef.getLangOpts().CPlusPlus1y
845 ? diag::warn_cxx11_compat_constexpr_type_definition
846 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000847 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000848 continue;
849
Richard Smitha10b9782013-04-22 15:31:51 +0000850 case Decl::EnumConstant:
851 case Decl::IndirectField:
852 case Decl::ParmVar:
853 // These can only appear with other declarations which are banned in
854 // C++11 and permitted in C++1y, so ignore them.
855 continue;
856
857 case Decl::Var: {
858 // C++1y [dcl.constexpr]p3 allows anything except:
859 // a definition of a variable of non-literal type or of static or
860 // thread storage duration or for which no initialization is performed.
861 VarDecl *VD = cast<VarDecl>(*DclIt);
862 if (VD->isThisDeclarationADefinition()) {
863 if (VD->isStaticLocal()) {
864 SemaRef.Diag(VD->getLocation(),
865 diag::err_constexpr_local_var_static)
866 << isa<CXXConstructorDecl>(Dcl)
867 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
868 return false;
869 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000870 if (!VD->getType()->isDependentType() &&
871 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000872 VD->getLocation(), VD->getType(),
873 diag::err_constexpr_local_var_non_literal_type,
874 isa<CXXConstructorDecl>(Dcl)))
875 return false;
876 if (!VD->hasInit()) {
877 SemaRef.Diag(VD->getLocation(),
878 diag::err_constexpr_local_var_no_init)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882 }
883 SemaRef.Diag(VD->getLocation(),
884 SemaRef.getLangOpts().CPlusPlus1y
885 ? diag::warn_cxx11_compat_constexpr_local_var
886 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000887 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000888 continue;
889 }
890
891 case Decl::NamespaceAlias:
892 case Decl::Function:
893 // These are disallowed in C++11 and permitted in C++1y. Allow them
894 // everywhere as an extension.
895 if (!Cxx1yLoc.isValid())
896 Cxx1yLoc = DS->getLocStart();
897 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000898
899 default:
900 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
901 << isa<CXXConstructorDecl>(Dcl);
902 return false;
903 }
904 }
905
906 return true;
907}
908
909/// Check that the given field is initialized within a constexpr constructor.
910///
911/// \param Dcl The constexpr constructor being checked.
912/// \param Field The field being checked. This may be a member of an anonymous
913/// struct or union nested within the class being checked.
914/// \param Inits All declarations, including anonymous struct/union members and
915/// indirect members, for which any initialization was provided.
916/// \param Diagnosed Set to true if an error is produced.
917static void CheckConstexprCtorInitializer(Sema &SemaRef,
918 const FunctionDecl *Dcl,
919 FieldDecl *Field,
920 llvm::SmallSet<Decl*, 16> &Inits,
921 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000922 if (Field->isInvalidDecl())
923 return;
924
Douglas Gregord61db332011-10-10 17:22:13 +0000925 if (Field->isUnnamedBitfield())
926 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000927
928 if (Field->isAnonymousStructOrUnion() &&
929 Field->getType()->getAsCXXRecordDecl()->isEmpty())
930 return;
931
Richard Smith9f569cc2011-10-01 02:31:28 +0000932 if (!Inits.count(Field)) {
933 if (!Diagnosed) {
934 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
935 Diagnosed = true;
936 }
937 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
938 } else if (Field->isAnonymousStructOrUnion()) {
939 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
940 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
941 I != E; ++I)
942 // If an anonymous union contains an anonymous struct of which any member
943 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000944 if (!RD->isUnion() || Inits.count(*I))
945 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000946 }
947}
948
Richard Smitha10b9782013-04-22 15:31:51 +0000949/// Check the provided statement is allowed in a constexpr function
950/// definition.
951static bool
952CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
953 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
954 SourceLocation &Cxx1yLoc) {
955 // - its function-body shall be [...] a compound-statement that contains only
956 switch (S->getStmtClass()) {
957 case Stmt::NullStmtClass:
958 // - null statements,
959 return true;
960
961 case Stmt::DeclStmtClass:
962 // - static_assert-declarations
963 // - using-declarations,
964 // - using-directives,
965 // - typedef declarations and alias-declarations that do not define
966 // classes or enumerations,
967 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
968 return false;
969 return true;
970
971 case Stmt::ReturnStmtClass:
972 // - and exactly one return statement;
973 if (isa<CXXConstructorDecl>(Dcl)) {
974 // C++1y allows return statements in constexpr constructors.
975 if (!Cxx1yLoc.isValid())
976 Cxx1yLoc = S->getLocStart();
977 return true;
978 }
979
980 ReturnStmts.push_back(S->getLocStart());
981 return true;
982
983 case Stmt::CompoundStmtClass: {
984 // C++1y allows compound-statements.
985 if (!Cxx1yLoc.isValid())
986 Cxx1yLoc = S->getLocStart();
987
988 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
989 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
990 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
991 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
992 Cxx1yLoc))
993 return false;
994 }
995 return true;
996 }
997
998 case Stmt::AttributedStmtClass:
999 if (!Cxx1yLoc.isValid())
1000 Cxx1yLoc = S->getLocStart();
1001 return true;
1002
1003 case Stmt::IfStmtClass: {
1004 // C++1y allows if-statements.
1005 if (!Cxx1yLoc.isValid())
1006 Cxx1yLoc = S->getLocStart();
1007
1008 IfStmt *If = cast<IfStmt>(S);
1009 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1010 Cxx1yLoc))
1011 return false;
1012 if (If->getElse() &&
1013 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1014 Cxx1yLoc))
1015 return false;
1016 return true;
1017 }
1018
1019 case Stmt::WhileStmtClass:
1020 case Stmt::DoStmtClass:
1021 case Stmt::ForStmtClass:
1022 case Stmt::CXXForRangeStmtClass:
1023 case Stmt::ContinueStmtClass:
1024 // C++1y allows all of these. We don't allow them as extensions in C++11,
1025 // because they don't make sense without variable mutation.
1026 if (!SemaRef.getLangOpts().CPlusPlus1y)
1027 break;
1028 if (!Cxx1yLoc.isValid())
1029 Cxx1yLoc = S->getLocStart();
1030 for (Stmt::child_range Children = S->children(); Children; ++Children)
1031 if (*Children &&
1032 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1033 Cxx1yLoc))
1034 return false;
1035 return true;
1036
1037 case Stmt::SwitchStmtClass:
1038 case Stmt::CaseStmtClass:
1039 case Stmt::DefaultStmtClass:
1040 case Stmt::BreakStmtClass:
1041 // C++1y allows switch-statements, and since they don't need variable
1042 // mutation, we can reasonably allow them in C++11 as an extension.
1043 if (!Cxx1yLoc.isValid())
1044 Cxx1yLoc = S->getLocStart();
1045 for (Stmt::child_range Children = S->children(); Children; ++Children)
1046 if (*Children &&
1047 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1048 Cxx1yLoc))
1049 return false;
1050 return true;
1051
1052 default:
1053 if (!isa<Expr>(S))
1054 break;
1055
1056 // C++1y allows expression-statements.
1057 if (!Cxx1yLoc.isValid())
1058 Cxx1yLoc = S->getLocStart();
1059 return true;
1060 }
1061
1062 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1063 << isa<CXXConstructorDecl>(Dcl);
1064 return false;
1065}
1066
Richard Smith9f569cc2011-10-01 02:31:28 +00001067/// Check the body for the given constexpr function declaration only contains
1068/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1069///
1070/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001071bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001072 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001073 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001074 // The definition of a constexpr function shall satisfy the following
1075 // constraints: [...]
1076 // - its function-body shall be = delete, = default, or a
1077 // compound-statement
1078 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001079 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001080 // In the definition of a constexpr constructor, [...]
1081 // - its function-body shall not be a function-try-block;
1082 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1083 << isa<CXXConstructorDecl>(Dcl);
1084 return false;
1085 }
1086
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001087 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001088
1089 // - its function-body shall be [...] a compound-statement that contains only
1090 // [... list of cases ...]
1091 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1092 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001093 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1094 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001095 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1096 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001097 }
1098
Richard Smitha10b9782013-04-22 15:31:51 +00001099 if (Cxx1yLoc.isValid())
1100 Diag(Cxx1yLoc,
1101 getLangOpts().CPlusPlus1y
1102 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1103 : diag::ext_constexpr_body_invalid_stmt)
1104 << isa<CXXConstructorDecl>(Dcl);
1105
Richard Smith9f569cc2011-10-01 02:31:28 +00001106 if (const CXXConstructorDecl *Constructor
1107 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1108 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001109 // DR1359:
1110 // - every non-variant non-static data member and base class sub-object
1111 // shall be initialized;
1112 // - if the class is a non-empty union, or for each non-empty anonymous
1113 // union member of a non-union class, exactly one non-static data member
1114 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001115 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001116 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001117 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1118 return false;
1119 }
Richard Smith6e433752011-10-10 16:38:04 +00001120 } else if (!Constructor->isDependentContext() &&
1121 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001122 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1123
1124 // Skip detailed checking if we have enough initializers, and we would
1125 // allow at most one initializer per member.
1126 bool AnyAnonStructUnionMembers = false;
1127 unsigned Fields = 0;
1128 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1129 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001130 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001131 AnyAnonStructUnionMembers = true;
1132 break;
1133 }
1134 }
1135 if (AnyAnonStructUnionMembers ||
1136 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1137 // Check initialization of non-static data members. Base classes are
1138 // always initialized so do not need to be checked. Dependent bases
1139 // might not have initializers in the member initializer list.
1140 llvm::SmallSet<Decl*, 16> Inits;
1141 for (CXXConstructorDecl::init_const_iterator
1142 I = Constructor->init_begin(), E = Constructor->init_end();
1143 I != E; ++I) {
1144 if (FieldDecl *FD = (*I)->getMember())
1145 Inits.insert(FD);
1146 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1147 Inits.insert(ID->chain_begin(), ID->chain_end());
1148 }
1149
1150 bool Diagnosed = false;
1151 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1152 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001153 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001154 if (Diagnosed)
1155 return false;
1156 }
1157 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001158 } else {
1159 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001160 // C++1y doesn't require constexpr functions to contain a 'return'
1161 // statement. We still do, unless the return type is void, because
1162 // otherwise if there's no return statement, the function cannot
1163 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001164 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001165 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001166 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1167 : diag::err_constexpr_body_no_return);
1168 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001169 }
1170 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001171 Diag(ReturnStmts.back(),
1172 getLangOpts().CPlusPlus1y
1173 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1174 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001175 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1176 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001177 }
1178 }
1179
Richard Smith5ba73e12012-02-04 00:33:54 +00001180 // C++11 [dcl.constexpr]p5:
1181 // if no function argument values exist such that the function invocation
1182 // substitution would produce a constant expression, the program is
1183 // ill-formed; no diagnostic required.
1184 // C++11 [dcl.constexpr]p3:
1185 // - every constructor call and implicit conversion used in initializing the
1186 // return value shall be one of those allowed in a constant expression.
1187 // C++11 [dcl.constexpr]p4:
1188 // - every constructor involved in initializing non-static data members and
1189 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001190 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001191 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001192 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001193 << isa<CXXConstructorDecl>(Dcl);
1194 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1195 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001196 // Don't return false here: we allow this for compatibility in
1197 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001198 }
1199
Richard Smith9f569cc2011-10-01 02:31:28 +00001200 return true;
1201}
1202
Douglas Gregorb48fe382008-10-31 09:07:45 +00001203/// isCurrentClassName - Determine whether the identifier II is the
1204/// name of the class type currently being defined. In the case of
1205/// nested classes, this will only return true if II is the name of
1206/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001207bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1208 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001209 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001210
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001211 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001212 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001213 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001214 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1215 } else
1216 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1217
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001218 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001219 return &II == CurDecl->getIdentifier();
1220 else
1221 return false;
1222}
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 {
2294 public:
2295 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2296 : ClassDecl(ClassDecl) {}
2297
2298 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2299 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2300 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2301 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2302 else
2303 return isa<TypeDecl>(ND);
2304 }
2305 return false;
2306 }
2307
2308 private:
2309 CXXRecordDecl *ClassDecl;
2310};
2311
2312}
2313
Sebastian Redl6df65482011-09-24 17:48:25 +00002314/// \brief Handle a C++ member initializer.
2315MemInitResult
2316Sema::BuildMemInitializer(Decl *ConstructorD,
2317 Scope *S,
2318 CXXScopeSpec &SS,
2319 IdentifierInfo *MemberOrBase,
2320 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002321 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002322 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002323 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002324 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002325 if (!ConstructorD)
2326 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002328 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002329
2330 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002331 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002332 if (!Constructor) {
2333 // The user wrote a constructor initializer on a function that is
2334 // not a C++ constructor. Ignore the error for now, because we may
2335 // have more member initializers coming; we'll diagnose it just
2336 // once in ActOnMemInitializers.
2337 return true;
2338 }
2339
2340 CXXRecordDecl *ClassDecl = Constructor->getParent();
2341
2342 // C++ [class.base.init]p2:
2343 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002344 // constructor's class and, if not found in that scope, are looked
2345 // up in the scope containing the constructor's definition.
2346 // [Note: if the constructor's class contains a member with the
2347 // same name as a direct or virtual base class of the class, a
2348 // mem-initializer-id naming the member or base class and composed
2349 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002350 // mem-initializer-id for the hidden base class may be specified
2351 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002352 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002353 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002354 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002355 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002356 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002357 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002358 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2359 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002360 if (EllipsisLoc.isValid())
2361 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002362 << MemberOrBase
2363 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002364
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002365 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002366 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002367 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002368 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002369 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002370 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002371 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002372
2373 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002374 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002375 } else if (DS.getTypeSpecType() == TST_decltype) {
2376 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002377 } else {
2378 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2379 LookupParsedName(R, S, &SS);
2380
2381 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2382 if (!TyD) {
2383 if (R.isAmbiguous()) return true;
2384
John McCallfd225442010-04-09 19:01:14 +00002385 // We don't want access-control diagnostics here.
2386 R.suppressDiagnostics();
2387
Douglas Gregor7a886e12010-01-19 06:46:48 +00002388 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2389 bool NotUnknownSpecialization = false;
2390 DeclContext *DC = computeDeclContext(SS, false);
2391 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2392 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2393
2394 if (!NotUnknownSpecialization) {
2395 // When the scope specifier can refer to a member of an unknown
2396 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002397 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2398 SS.getWithLocInContext(Context),
2399 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002400 if (BaseType.isNull())
2401 return true;
2402
Douglas Gregor7a886e12010-01-19 06:46:48 +00002403 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002404 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002405 }
2406 }
2407
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002408 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002409 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002410 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002411 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002412 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002413 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002414 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2415 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002416 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002417 // We have found a non-static data member with a similar
2418 // name to what was typed; complain and initialize that
2419 // member.
2420 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2421 << MemberOrBase << true << CorrectedQuotedStr
2422 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2423 Diag(Member->getLocation(), diag::note_previous_decl)
2424 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002425
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002426 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002427 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002428 const CXXBaseSpecifier *DirectBaseSpec;
2429 const CXXBaseSpecifier *VirtualBaseSpec;
2430 if (FindBaseInitializer(*this, ClassDecl,
2431 Context.getTypeDeclType(Type),
2432 DirectBaseSpec, VirtualBaseSpec)) {
2433 // We have found a direct or virtual base class with a
2434 // similar name to what was typed; complain and initialize
2435 // that base class.
2436 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002437 << MemberOrBase << false << CorrectedQuotedStr
2438 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002439
2440 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2441 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002442 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002443 diag::note_base_class_specified_here)
2444 << BaseSpec->getType()
2445 << BaseSpec->getSourceRange();
2446
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002447 TyD = Type;
2448 }
2449 }
2450 }
2451
Douglas Gregor7a886e12010-01-19 06:46:48 +00002452 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002453 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002454 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002455 return true;
2456 }
John McCall2b194412009-12-21 10:41:20 +00002457 }
2458
Douglas Gregor7a886e12010-01-19 06:46:48 +00002459 if (BaseType.isNull()) {
2460 BaseType = Context.getTypeDeclType(TyD);
2461 if (SS.isSet()) {
2462 NestedNameSpecifier *Qualifier =
2463 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002464
Douglas Gregor7a886e12010-01-19 06:46:48 +00002465 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002466 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002467 }
John McCall2b194412009-12-21 10:41:20 +00002468 }
2469 }
Mike Stump1eb44332009-09-09 15:08:12 +00002470
John McCalla93c9342009-12-07 02:54:59 +00002471 if (!TInfo)
2472 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002473
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002474 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002475}
2476
Chandler Carruth81c64772011-09-03 01:14:15 +00002477/// Checks a member initializer expression for cases where reference (or
2478/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002479static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2480 Expr *Init,
2481 SourceLocation IdLoc) {
2482 QualType MemberTy = Member->getType();
2483
2484 // We only handle pointers and references currently.
2485 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2486 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2487 return;
2488
2489 const bool IsPointer = MemberTy->isPointerType();
2490 if (IsPointer) {
2491 if (const UnaryOperator *Op
2492 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2493 // The only case we're worried about with pointers requires taking the
2494 // address.
2495 if (Op->getOpcode() != UO_AddrOf)
2496 return;
2497
2498 Init = Op->getSubExpr();
2499 } else {
2500 // We only handle address-of expression initializers for pointers.
2501 return;
2502 }
2503 }
2504
Richard Smitha4bb99c2013-06-12 21:51:50 +00002505 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002506 // We only warn when referring to a non-reference parameter declaration.
2507 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2508 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002509 return;
2510
2511 S.Diag(Init->getExprLoc(),
2512 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2513 : diag::warn_bind_ref_member_to_parameter)
2514 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002515 } else {
2516 // Other initializers are fine.
2517 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002518 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002519
2520 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2521 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002522}
2523
John McCallf312b1e2010-08-26 23:41:50 +00002524MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002525Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002526 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002527 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2528 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2529 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002530 "Member must be a FieldDecl or IndirectFieldDecl");
2531
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002532 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002533 return true;
2534
Douglas Gregor464b2f02010-11-05 22:21:31 +00002535 if (Member->isInvalidDecl())
2536 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002537
John McCallb4190042009-11-04 23:02:40 +00002538 // Diagnose value-uses of fields to initialize themselves, e.g.
2539 // foo(foo)
2540 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002541 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002542 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002543 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002544 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002545 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002546 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002547 } else {
2548 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002549 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002550 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002551
Richard Trieude5e75c2012-06-14 23:11:34 +00002552 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2553 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002554 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002555 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002556 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002557 // initializing the i'th field, throw a warning if any of the >= i'th
2558 // fields are used, as they are not yet initialized.
2559 // Right now we are only handling the case where the i'th field uses
2560 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002561 // Also need to take into account that some fields may be initialized by
2562 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002563 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002564
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002565 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002566
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002567 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002568 // Can't check initialization for a member of dependent type or when
2569 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002570 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002571 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002572 bool InitList = false;
2573 if (isa<InitListExpr>(Init)) {
2574 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002575 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002576 }
2577
Chandler Carruth894aed92010-12-06 09:23:57 +00002578 // Initialize the member.
2579 InitializedEntity MemberEntity =
2580 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2581 : InitializedEntity::InitializeMember(IndirectMember, 0);
2582 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002583 InitList ? InitializationKind::CreateDirectList(IdLoc)
2584 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2585 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002586
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002587 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2588 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002589 if (MemberInit.isInvalid())
2590 return true;
2591
Richard Smith8a07cd32013-06-12 20:42:33 +00002592 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2593
Richard Smith41956372013-01-14 22:39:08 +00002594 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002595 // The initialization of each base and member constitutes a
2596 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002597 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002598 if (MemberInit.isInvalid())
2599 return true;
2600
Richard Smithc83c2302012-12-19 01:39:02 +00002601 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002602 }
2603
Chandler Carruth894aed92010-12-06 09:23:57 +00002604 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002605 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2606 InitRange.getBegin(), Init,
2607 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002608 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002609 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2610 InitRange.getBegin(), Init,
2611 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002612 }
Eli Friedman59c04372009-07-29 19:44:27 +00002613}
2614
John McCallf312b1e2010-08-26 23:41:50 +00002615MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002616Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002617 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002618 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002619 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002620 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002621 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002622 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002623
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002624 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002625 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002626 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2627 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002628 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002629 }
2630
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002631 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002632 // Initialize the object.
2633 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2634 QualType(ClassDecl->getTypeForDecl(), 0));
2635 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002636 InitList ? InitializationKind::CreateDirectList(NameLoc)
2637 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2638 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002639 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002640 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002641 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002642 if (DelegationInit.isInvalid())
2643 return true;
2644
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002645 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2646 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002647
Richard Smith41956372013-01-14 22:39:08 +00002648 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002649 // The initialization of each base and member constitutes a
2650 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002651 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2652 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002653 if (DelegationInit.isInvalid())
2654 return true;
2655
Eli Friedmand21016f2012-05-19 23:35:23 +00002656 // If we are in a dependent context, template instantiation will
2657 // perform this type-checking again. Just save the arguments that we
2658 // received in a ParenListExpr.
2659 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2660 // of the information that we have about the base
2661 // initializer. However, deconstructing the ASTs is a dicey process,
2662 // and this approach is far more likely to get the corner cases right.
2663 if (CurContext->isDependentContext())
2664 DelegationInit = Owned(Init);
2665
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002666 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002667 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002668 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002669}
2670
2671MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002672Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002673 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002674 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002675 SourceLocation BaseLoc
2676 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002677
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002678 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2679 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2680 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2681
2682 // C++ [class.base.init]p2:
2683 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002684 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002685 // of that class, the mem-initializer is ill-formed. A
2686 // mem-initializer-list can initialize a base class using any
2687 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002688 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002689
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002690 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002691 if (EllipsisLoc.isValid()) {
2692 // This is a pack expansion.
2693 if (!BaseType->containsUnexpandedParameterPack()) {
2694 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002695 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002696
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002697 EllipsisLoc = SourceLocation();
2698 }
2699 } else {
2700 // Check for any unexpanded parameter packs.
2701 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2702 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002703
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002704 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002705 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002706 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002707
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002708 // Check for direct and virtual base classes.
2709 const CXXBaseSpecifier *DirectBaseSpec = 0;
2710 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2711 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002712 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2713 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002714 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002715
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002716 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2717 VirtualBaseSpec);
2718
2719 // C++ [base.class.init]p2:
2720 // Unless the mem-initializer-id names a nonstatic data member of the
2721 // constructor's class or a direct or virtual base of that class, the
2722 // mem-initializer is ill-formed.
2723 if (!DirectBaseSpec && !VirtualBaseSpec) {
2724 // If the class has any dependent bases, then it's possible that
2725 // one of those types will resolve to the same type as
2726 // BaseType. Therefore, just treat this as a dependent base
2727 // class initialization. FIXME: Should we try to check the
2728 // initialization anyway? It seems odd.
2729 if (ClassDecl->hasAnyDependentBases())
2730 Dependent = true;
2731 else
2732 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2733 << BaseType << Context.getTypeDeclType(ClassDecl)
2734 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2735 }
2736 }
2737
2738 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002739 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Sebastian Redl6df65482011-09-24 17:48:25 +00002741 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2742 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002743 InitRange.getBegin(), Init,
2744 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002745 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002746
2747 // C++ [base.class.init]p2:
2748 // If a mem-initializer-id is ambiguous because it designates both
2749 // a direct non-virtual base class and an inherited virtual base
2750 // class, the mem-initializer is ill-formed.
2751 if (DirectBaseSpec && VirtualBaseSpec)
2752 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002753 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002754
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002755 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002756 if (!BaseSpec)
2757 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2758
2759 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002760 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002761 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002762 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002763 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002764 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002765 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002766
2767 InitializedEntity BaseEntity =
2768 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2769 InitializationKind Kind =
2770 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2771 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2772 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002773 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2774 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002775 if (BaseInit.isInvalid())
2776 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002777
Richard Smith41956372013-01-14 22:39:08 +00002778 // C++11 [class.base.init]p7:
2779 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002780 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002781 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002782 if (BaseInit.isInvalid())
2783 return true;
2784
2785 // If we are in a dependent context, template instantiation will
2786 // perform this type-checking again. Just save the arguments that we
2787 // received in a ParenListExpr.
2788 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2789 // of the information that we have about the base
2790 // initializer. However, deconstructing the ASTs is a dicey process,
2791 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002792 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002793 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002794
Sean Huntcbb67482011-01-08 20:30:50 +00002795 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002796 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002797 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002798 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002799 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002800}
2801
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002802// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002803static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2804 if (T.isNull()) T = E->getType();
2805 QualType TargetType = SemaRef.BuildReferenceType(
2806 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002807 SourceLocation ExprLoc = E->getLocStart();
2808 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2809 TargetType, ExprLoc);
2810
2811 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2812 SourceRange(ExprLoc, ExprLoc),
2813 E->getSourceRange()).take();
2814}
2815
Anders Carlssone5ef7402010-04-23 03:10:23 +00002816/// ImplicitInitializerKind - How an implicit base or member initializer should
2817/// initialize its base or member.
2818enum ImplicitInitializerKind {
2819 IIK_Default,
2820 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002821 IIK_Move,
2822 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002823};
2824
Anders Carlssondefefd22010-04-23 02:00:02 +00002825static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002826BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002827 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002828 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002829 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002830 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002831 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002832 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2833 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002834
John McCall60d7b3a2010-08-24 06:29:42 +00002835 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002836
2837 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002838 case IIK_Inherit: {
2839 const CXXRecordDecl *Inherited =
2840 Constructor->getInheritedConstructor()->getParent();
2841 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2842 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2843 // C++11 [class.inhctor]p8:
2844 // Each expression in the expression-list is of the form
2845 // static_cast<T&&>(p), where p is the name of the corresponding
2846 // constructor parameter and T is the declared type of p.
2847 SmallVector<Expr*, 16> Args;
2848 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2849 ParmVarDecl *PD = Constructor->getParamDecl(I);
2850 ExprResult ArgExpr =
2851 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2852 VK_LValue, SourceLocation());
2853 if (ArgExpr.isInvalid())
2854 return true;
2855 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2856 }
2857
2858 InitializationKind InitKind = InitializationKind::CreateDirect(
2859 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002860 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002861 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2862 break;
2863 }
2864 }
2865 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002866 case IIK_Default: {
2867 InitializationKind InitKind
2868 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002869 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2870 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002871 break;
2872 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002873
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002874 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002875 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002876 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002877 ParmVarDecl *Param = Constructor->getParamDecl(0);
2878 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002879
Anders Carlssone5ef7402010-04-23 03:10:23 +00002880 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002881 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002882 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002883 Constructor->getLocation(), ParamType,
2884 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002885
Eli Friedman5f2987c2012-02-02 03:46:19 +00002886 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2887
Anders Carlssonc7957502010-04-24 22:02:54 +00002888 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002889 QualType ArgTy =
2890 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2891 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002892
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002893 if (Moving) {
2894 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2895 }
2896
John McCallf871d0c2010-08-07 06:22:56 +00002897 CXXCastPath BasePath;
2898 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002899 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2900 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002901 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002902 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002903
Anders Carlssone5ef7402010-04-23 03:10:23 +00002904 InitializationKind InitKind
2905 = InitializationKind::CreateDirect(Constructor->getLocation(),
2906 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002907 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2908 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002909 break;
2910 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002911 }
John McCall9ae2f072010-08-23 23:25:46 +00002912
Douglas Gregor53c374f2010-12-07 00:41:46 +00002913 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002914 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002915 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002916
Anders Carlssondefefd22010-04-23 02:00:02 +00002917 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002918 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002919 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2920 SourceLocation()),
2921 BaseSpec->isVirtual(),
2922 SourceLocation(),
2923 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002924 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002925 SourceLocation());
2926
Anders Carlssondefefd22010-04-23 02:00:02 +00002927 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002928}
2929
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002930static bool RefersToRValueRef(Expr *MemRef) {
2931 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2932 return Referenced->getType()->isRValueReferenceType();
2933}
2934
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002935static bool
2936BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002937 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002938 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002939 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002940 if (Field->isInvalidDecl())
2941 return true;
2942
Chandler Carruthf186b542010-06-29 23:50:44 +00002943 SourceLocation Loc = Constructor->getLocation();
2944
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002945 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2946 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002947 ParmVarDecl *Param = Constructor->getParamDecl(0);
2948 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002949
2950 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002951 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2952 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002953
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002954 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002955 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002956 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002957 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002958
Eli Friedman5f2987c2012-02-02 03:46:19 +00002959 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2960
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002961 if (Moving) {
2962 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2963 }
2964
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002965 // Build a reference to this field within the parameter.
2966 CXXScopeSpec SS;
2967 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2968 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002969 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2970 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002971 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002972 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002973 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002974 ParamType, Loc,
2975 /*IsArrow=*/false,
2976 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002977 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002978 /*FirstQualifierInScope=*/0,
2979 MemberLookup,
2980 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002981 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002982 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002983
2984 // C++11 [class.copy]p15:
2985 // - if a member m has rvalue reference type T&&, it is direct-initialized
2986 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002987 if (RefersToRValueRef(CtorArg.get())) {
2988 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002989 }
2990
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002991 // When the field we are copying is an array, create index variables for
2992 // each dimension of the array. We use these index variables to subscript
2993 // the source array, and other clients (e.g., CodeGen) will perform the
2994 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002995 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002996 QualType BaseType = Field->getType();
2997 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002998 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002999 while (const ConstantArrayType *Array
3000 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003001 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003002 // Create the iteration variable for this array index.
3003 IdentifierInfo *IterationVarName = 0;
3004 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003005 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003006 llvm::raw_svector_ostream OS(Str);
3007 OS << "__i" << IndexVariables.size();
3008 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3009 }
3010 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003011 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003012 IterationVarName, SizeType,
3013 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003014 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003015 IndexVariables.push_back(IterationVar);
3016
3017 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003018 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003019 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003020 assert(!IterationVarRef.isInvalid() &&
3021 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003022 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3023 assert(!IterationVarRef.isInvalid() &&
3024 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003025
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003026 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003027 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003028 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003029 Loc);
3030 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003031 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003032
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003033 BaseType = Array->getElementType();
3034 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003035
3036 // The array subscript expression is an lvalue, which is wrong for moving.
3037 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003038 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003039
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003040 // Construct the entity that we will be initializing. For an array, this
3041 // will be first element in the array, which may require several levels
3042 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003043 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003044 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003045 if (Indirect)
3046 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3047 else
3048 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003049 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3050 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3051 0,
3052 Entities.back()));
3053
3054 // Direct-initialize to use the copy constructor.
3055 InitializationKind InitKind =
3056 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3057
Sebastian Redl74e611a2011-09-04 18:14:28 +00003058 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003059 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003060
John McCall60d7b3a2010-08-24 06:29:42 +00003061 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003062 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003063 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003064 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003065 if (MemberInit.isInvalid())
3066 return true;
3067
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003068 if (Indirect) {
3069 assert(IndexVariables.size() == 0 &&
3070 "Indirect field improperly initialized");
3071 CXXMemberInit
3072 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3073 Loc, Loc,
3074 MemberInit.takeAs<Expr>(),
3075 Loc);
3076 } else
3077 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3078 Loc, MemberInit.takeAs<Expr>(),
3079 Loc,
3080 IndexVariables.data(),
3081 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003082 return false;
3083 }
3084
Richard Smith07b0fdc2013-03-18 21:12:30 +00003085 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3086 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003087
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003088 QualType FieldBaseElementType =
3089 SemaRef.Context.getBaseElementType(Field->getType());
3090
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003091 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003092 InitializedEntity InitEntity
3093 = Indirect? InitializedEntity::InitializeMember(Indirect)
3094 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003095 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003096 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003097
3098 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3099 ExprResult MemberInit =
3100 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003101
Douglas Gregor53c374f2010-12-07 00:41:46 +00003102 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003103 if (MemberInit.isInvalid())
3104 return true;
3105
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003106 if (Indirect)
3107 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3108 Indirect, Loc,
3109 Loc,
3110 MemberInit.get(),
3111 Loc);
3112 else
3113 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3114 Field, Loc, Loc,
3115 MemberInit.get(),
3116 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003117 return false;
3118 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003119
Sean Hunt1f2f3842011-05-17 00:19:05 +00003120 if (!Field->getParent()->isUnion()) {
3121 if (FieldBaseElementType->isReferenceType()) {
3122 SemaRef.Diag(Constructor->getLocation(),
3123 diag::err_uninitialized_member_in_ctor)
3124 << (int)Constructor->isImplicit()
3125 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3126 << 0 << Field->getDeclName();
3127 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3128 return true;
3129 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003130
Sean Hunt1f2f3842011-05-17 00:19:05 +00003131 if (FieldBaseElementType.isConstQualified()) {
3132 SemaRef.Diag(Constructor->getLocation(),
3133 diag::err_uninitialized_member_in_ctor)
3134 << (int)Constructor->isImplicit()
3135 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3136 << 1 << Field->getDeclName();
3137 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3138 return true;
3139 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003140 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003141
David Blaikie4e4d0842012-03-11 07:00:24 +00003142 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003143 FieldBaseElementType->isObjCRetainableType() &&
3144 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3145 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003146 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003147 // Default-initialize Objective-C pointers to NULL.
3148 CXXMemberInit
3149 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3150 Loc, Loc,
3151 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3152 Loc);
3153 return false;
3154 }
3155
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003156 // Nothing to initialize.
3157 CXXMemberInit = 0;
3158 return false;
3159}
John McCallf1860e52010-05-20 23:23:51 +00003160
3161namespace {
3162struct BaseAndFieldInfo {
3163 Sema &S;
3164 CXXConstructorDecl *Ctor;
3165 bool AnyErrorsInInits;
3166 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003167 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003168 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003169
3170 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3171 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003172 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3173 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003174 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003175 else if (Generated && Ctor->isMoveConstructor())
3176 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003177 else if (Ctor->getInheritedConstructor())
3178 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003179 else
3180 IIK = IIK_Default;
3181 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003182
3183 bool isImplicitCopyOrMove() const {
3184 switch (IIK) {
3185 case IIK_Copy:
3186 case IIK_Move:
3187 return true;
3188
3189 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003190 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003191 return false;
3192 }
David Blaikie30263482012-01-20 21:50:17 +00003193
3194 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003195 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003196
3197 bool addFieldInitializer(CXXCtorInitializer *Init) {
3198 AllToInit.push_back(Init);
3199
3200 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003201 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003202 S.UnusedPrivateFields.remove(Init->getAnyMember());
3203
3204 return false;
3205 }
John McCallf1860e52010-05-20 23:23:51 +00003206};
3207}
3208
Richard Smitha4950662011-09-19 13:34:43 +00003209/// \brief Determine whether the given indirect field declaration is somewhere
3210/// within an anonymous union.
3211static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3212 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3213 CEnd = F->chain_end();
3214 C != CEnd; ++C)
3215 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3216 if (Record->isUnion())
3217 return true;
3218
3219 return false;
3220}
3221
Douglas Gregorddb21472011-11-02 23:04:16 +00003222/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3223/// array type.
3224static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3225 if (T->isIncompleteArrayType())
3226 return true;
3227
3228 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3229 if (!ArrayT->getSize())
3230 return true;
3231
3232 T = ArrayT->getElementType();
3233 }
3234
3235 return false;
3236}
3237
Richard Smith7a614d82011-06-11 17:19:42 +00003238static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003239 FieldDecl *Field,
3240 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003241 if (Field->isInvalidDecl())
3242 return false;
John McCallf1860e52010-05-20 23:23:51 +00003243
Chandler Carruthe861c602010-06-30 02:59:29 +00003244 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003245 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3246 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003247
Richard Smith0b8220a2012-08-07 21:30:42 +00003248 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003249 // has a brace-or-equal-initializer, the entity is initialized as specified
3250 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003251 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003252 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3253 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003254 CXXCtorInitializer *Init;
3255 if (Indirect)
3256 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3257 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003258 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003259 SourceLocation());
3260 else
3261 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3262 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003263 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003264 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003265 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003266 }
3267
Richard Smithc115f632011-09-18 11:14:50 +00003268 // Don't build an implicit initializer for union members if none was
3269 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003270 if (Field->getParent()->isUnion() ||
3271 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003272 return false;
3273
Douglas Gregorddb21472011-11-02 23:04:16 +00003274 // Don't initialize incomplete or zero-length arrays.
3275 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3276 return false;
3277
John McCallf1860e52010-05-20 23:23:51 +00003278 // Don't try to build an implicit initializer if there were semantic
3279 // errors in any of the initializers (and therefore we might be
3280 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003281 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003282 return false;
3283
Sean Huntcbb67482011-01-08 20:30:50 +00003284 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003285 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3286 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003287 return true;
John McCallf1860e52010-05-20 23:23:51 +00003288
Richard Smith0b8220a2012-08-07 21:30:42 +00003289 if (!Init)
3290 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003291
Richard Smith0b8220a2012-08-07 21:30:42 +00003292 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003293}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003294
3295bool
3296Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3297 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003298 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003299 Constructor->setNumCtorInitializers(1);
3300 CXXCtorInitializer **initializer =
3301 new (Context) CXXCtorInitializer*[1];
3302 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3303 Constructor->setCtorInitializers(initializer);
3304
Sean Huntb76af9c2011-05-03 23:05:34 +00003305 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003306 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003307 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3308 }
3309
Sean Huntc1598702011-05-05 00:05:47 +00003310 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003311
Sean Hunt059ce0d2011-05-01 07:04:31 +00003312 return false;
3313}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003314
David Blaikie93c86172013-01-17 05:26:25 +00003315bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3316 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003317 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003318 // Just store the initializers as written, they will be checked during
3319 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003320 if (!Initializers.empty()) {
3321 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003322 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003323 new (Context) CXXCtorInitializer*[Initializers.size()];
3324 memcpy(baseOrMemberInitializers, Initializers.data(),
3325 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003326 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003327 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003328
3329 // Let template instantiation know whether we had errors.
3330 if (AnyErrors)
3331 Constructor->setInvalidDecl();
3332
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003333 return false;
3334 }
3335
John McCallf1860e52010-05-20 23:23:51 +00003336 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003337
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003338 // We need to build the initializer AST according to order of construction
3339 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003340 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003341 if (!ClassDecl)
3342 return true;
3343
Eli Friedman80c30da2009-11-09 19:20:36 +00003344 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003345
David Blaikie93c86172013-01-17 05:26:25 +00003346 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003347 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003348
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003349 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003350 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003351 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003352 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003353 }
3354
Anders Carlsson711f34a2010-04-21 19:52:01 +00003355 // Keep track of the direct virtual bases.
3356 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3357 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3358 E = ClassDecl->bases_end(); I != E; ++I) {
3359 if (I->isVirtual())
3360 DirectVBases.insert(I);
3361 }
3362
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003363 // Push virtual bases before others.
3364 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3365 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3366
Sean Huntcbb67482011-01-08 20:30:50 +00003367 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003368 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003369 // [class.base.init]p7, per DR257:
3370 // A mem-initializer where the mem-initializer-id names a virtual base
3371 // class is ignored during execution of a constructor of any class that
3372 // is not the most derived class.
3373 if (ClassDecl->isAbstract()) {
3374 // FIXME: Provide a fixit to remove the base specifier. This requires
3375 // tracking the location of the associated comma for a base specifier.
3376 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3377 << VBase->getType() << ClassDecl;
3378 DiagnoseAbstractType(ClassDecl);
3379 }
3380
John McCallf1860e52010-05-20 23:23:51 +00003381 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003382 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3383 // [class.base.init]p8, per DR257:
3384 // If a given [...] base class is not named by a mem-initializer-id
3385 // [...] and the entity is not a virtual base class of an abstract
3386 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003387 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003388 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003389 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003390 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003391 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003392 HadError = true;
3393 continue;
3394 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003395
John McCallf1860e52010-05-20 23:23:51 +00003396 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003397 }
3398 }
Mike Stump1eb44332009-09-09 15:08:12 +00003399
John McCallf1860e52010-05-20 23:23:51 +00003400 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003401 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3402 E = ClassDecl->bases_end(); Base != E; ++Base) {
3403 // Virtuals are in the virtual base list and already constructed.
3404 if (Base->isVirtual())
3405 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003406
Sean Huntcbb67482011-01-08 20:30:50 +00003407 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003408 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3409 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003410 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003411 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003412 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003413 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003414 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003415 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003416 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003417 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003418
John McCallf1860e52010-05-20 23:23:51 +00003419 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003420 }
3421 }
Mike Stump1eb44332009-09-09 15:08:12 +00003422
John McCallf1860e52010-05-20 23:23:51 +00003423 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003424 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3425 MemEnd = ClassDecl->decls_end();
3426 Mem != MemEnd; ++Mem) {
3427 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003428 // C++ [class.bit]p2:
3429 // A declaration for a bit-field that omits the identifier declares an
3430 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3431 // initialized.
3432 if (F->isUnnamedBitfield())
3433 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003434
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003435 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003436 // handle anonymous struct/union fields based on their individual
3437 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003438 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003439 continue;
3440
3441 if (CollectFieldInitializer(*this, Info, F))
3442 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003443 continue;
3444 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003445
3446 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003447 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003448 continue;
3449
3450 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3451 if (F->getType()->isIncompleteArrayType()) {
3452 assert(ClassDecl->hasFlexibleArrayMember() &&
3453 "Incomplete array type is not valid");
3454 continue;
3455 }
3456
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003457 // Initialize each field of an anonymous struct individually.
3458 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3459 HadError = true;
3460
3461 continue;
3462 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003463 }
Mike Stump1eb44332009-09-09 15:08:12 +00003464
David Blaikie93c86172013-01-17 05:26:25 +00003465 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003466 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003467 Constructor->setNumCtorInitializers(NumInitializers);
3468 CXXCtorInitializer **baseOrMemberInitializers =
3469 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003470 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003471 NumInitializers * sizeof(CXXCtorInitializer*));
3472 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003473
John McCallef027fe2010-03-16 21:39:52 +00003474 // Constructors implicitly reference the base and member
3475 // destructors.
3476 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3477 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003478 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003479
3480 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003481}
3482
David Blaikieee000bb2013-01-17 08:49:22 +00003483static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003484 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003485 const RecordDecl *RD = RT->getDecl();
3486 if (RD->isAnonymousStructOrUnion()) {
3487 for (RecordDecl::field_iterator Field = RD->field_begin(),
3488 E = RD->field_end(); Field != E; ++Field)
3489 PopulateKeysForFields(*Field, IdealInits);
3490 return;
3491 }
Eli Friedman6347f422009-07-21 19:28:10 +00003492 }
David Blaikieee000bb2013-01-17 08:49:22 +00003493 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003494}
3495
Anders Carlssonea356fb2010-04-02 05:42:15 +00003496static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003497 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003498}
3499
Anders Carlssonea356fb2010-04-02 05:42:15 +00003500static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003501 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003502 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003503 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003504
David Blaikieee000bb2013-01-17 08:49:22 +00003505 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003506}
3507
David Blaikie93c86172013-01-17 05:26:25 +00003508static void DiagnoseBaseOrMemInitializerOrder(
3509 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3510 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003511 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003512 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003514 // Don't check initializers order unless the warning is enabled at the
3515 // location of at least one initializer.
3516 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003517 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003518 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003519 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3520 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003521 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003522 ShouldCheckOrder = true;
3523 break;
3524 }
3525 }
3526 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003527 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003528
John McCalld6ca8da2010-04-10 07:37:23 +00003529 // Build the list of bases and members in the order that they'll
3530 // actually be initialized. The explicit initializers should be in
3531 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003532 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Anders Carlsson071d6102010-04-02 03:38:04 +00003534 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3535
John McCalld6ca8da2010-04-10 07:37:23 +00003536 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003537 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003538 ClassDecl->vbases_begin(),
3539 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003540 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003541
John McCalld6ca8da2010-04-10 07:37:23 +00003542 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003543 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003544 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003545 if (Base->isVirtual())
3546 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003547 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003548 }
Mike Stump1eb44332009-09-09 15:08:12 +00003549
John McCalld6ca8da2010-04-10 07:37:23 +00003550 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003551 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003552 E = ClassDecl->field_end(); Field != E; ++Field) {
3553 if (Field->isUnnamedBitfield())
3554 continue;
3555
David Blaikieee000bb2013-01-17 08:49:22 +00003556 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003557 }
3558
John McCalld6ca8da2010-04-10 07:37:23 +00003559 unsigned NumIdealInits = IdealInitKeys.size();
3560 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003561
Sean Huntcbb67482011-01-08 20:30:50 +00003562 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003563 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003564 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003565 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003566
3567 // Scan forward to try to find this initializer in the idealized
3568 // initializers list.
3569 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3570 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003571 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003572
3573 // If we didn't find this initializer, it must be because we
3574 // scanned past it on a previous iteration. That can only
3575 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003576 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003577 Sema::SemaDiagnosticBuilder D =
3578 SemaRef.Diag(PrevInit->getSourceLocation(),
3579 diag::warn_initializer_out_of_order);
3580
Francois Pichet00eb3f92010-12-04 09:14:42 +00003581 if (PrevInit->isAnyMemberInitializer())
3582 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003583 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003584 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003585
Francois Pichet00eb3f92010-12-04 09:14:42 +00003586 if (Init->isAnyMemberInitializer())
3587 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003588 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003589 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003590
3591 // Move back to the initializer's location in the ideal list.
3592 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3593 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003594 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003595
3596 assert(IdealIndex != NumIdealInits &&
3597 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003598 }
John McCalld6ca8da2010-04-10 07:37:23 +00003599
3600 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003601 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003602}
3603
John McCall3c3ccdb2010-04-10 09:28:51 +00003604namespace {
3605bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003606 CXXCtorInitializer *Init,
3607 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003608 if (!PrevInit) {
3609 PrevInit = Init;
3610 return false;
3611 }
3612
Douglas Gregordc392c12013-03-25 23:28:23 +00003613 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003614 S.Diag(Init->getSourceLocation(),
3615 diag::err_multiple_mem_initialization)
3616 << Field->getDeclName()
3617 << Init->getSourceRange();
3618 else {
John McCallf4c73712011-01-19 06:33:43 +00003619 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003620 assert(BaseClass && "neither field nor base");
3621 S.Diag(Init->getSourceLocation(),
3622 diag::err_multiple_base_initialization)
3623 << QualType(BaseClass, 0)
3624 << Init->getSourceRange();
3625 }
3626 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3627 << 0 << PrevInit->getSourceRange();
3628
3629 return true;
3630}
3631
Sean Huntcbb67482011-01-08 20:30:50 +00003632typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003633typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3634
3635bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003636 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003637 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003638 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003639 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003640 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003641
3642 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003643 if (Parent->isUnion()) {
3644 UnionEntry &En = Unions[Parent];
3645 if (En.first && En.first != Child) {
3646 S.Diag(Init->getSourceLocation(),
3647 diag::err_multiple_mem_union_initialization)
3648 << Field->getDeclName()
3649 << Init->getSourceRange();
3650 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3651 << 0 << En.second->getSourceRange();
3652 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003653 }
3654 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003655 En.first = Child;
3656 En.second = Init;
3657 }
David Blaikie6fe29652011-11-17 06:01:57 +00003658 if (!Parent->isAnonymousStructOrUnion())
3659 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003660 }
3661
3662 Child = Parent;
3663 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003664 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003665
3666 return false;
3667}
3668}
3669
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003670/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003671void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003672 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003673 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003674 bool AnyErrors) {
3675 if (!ConstructorDecl)
3676 return;
3677
3678 AdjustDeclIfTemplate(ConstructorDecl);
3679
3680 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003681 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003682
3683 if (!Constructor) {
3684 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3685 return;
3686 }
3687
John McCall3c3ccdb2010-04-10 09:28:51 +00003688 // Mapping for the duplicate initializers check.
3689 // For member initializers, this is keyed with a FieldDecl*.
3690 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003691 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003692
3693 // Mapping for the inconsistent anonymous-union initializers check.
3694 RedundantUnionMap MemberUnions;
3695
Anders Carlssonea356fb2010-04-02 05:42:15 +00003696 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003697 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003698 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003699
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003700 // Set the source order index.
3701 Init->setSourceOrder(i);
3702
Francois Pichet00eb3f92010-12-04 09:14:42 +00003703 if (Init->isAnyMemberInitializer()) {
3704 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003705 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3706 CheckRedundantUnionInit(*this, Init, MemberUnions))
3707 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003708 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003709 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3710 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
Eli Friedman5f2987c2012-02-02 03:46:19 +00003781 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(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
Eli Friedman5f2987c2012-02-02 03:46:19 +00003814 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(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
Eli Friedman5f2987c2012-02-02 03:46:19 +00003850 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(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) { }
3873
3874 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
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 Smithcbc820a2013-07-22 02:56:56 +00005079 // Defect report (no number yet): do not consider virtual bases of
5080 // constructors of abstract classes, since we are not going to construct
5081 // them. This is an extension of DR257 into the C++11 behavior for special
5082 // members.
5083 if (!RD->isAbstract() || !SMI.IsConstructor) {
5084 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5085 BE = RD->vbases_end();
5086 BI != BE; ++BI)
5087 if (SMI.shouldDeleteForBase(BI))
5088 return true;
5089 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005090
5091 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005092 FE = RD->field_end(); FI != FE; ++FI)
5093 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005094 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005095 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005096
Richard Smith7d5088a2012-02-18 02:02:13 +00005097 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005098 return true;
5099
5100 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005101}
5102
Richard Smithac713512012-12-08 02:53:02 +00005103/// Perform lookup for a special member of the specified kind, and determine
5104/// whether it is trivial. If the triviality can be determined without the
5105/// lookup, skip it. This is intended for use when determining whether a
5106/// special member of a containing object is trivial, and thus does not ever
5107/// perform overload resolution for default constructors.
5108///
5109/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5110/// member that was most likely to be intended to be trivial, if any.
5111static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5112 Sema::CXXSpecialMember CSM, unsigned Quals,
5113 CXXMethodDecl **Selected) {
5114 if (Selected)
5115 *Selected = 0;
5116
5117 switch (CSM) {
5118 case Sema::CXXInvalid:
5119 llvm_unreachable("not a special member");
5120
5121 case Sema::CXXDefaultConstructor:
5122 // C++11 [class.ctor]p5:
5123 // A default constructor is trivial if:
5124 // - all the [direct subobjects] have trivial default constructors
5125 //
5126 // Note, no overload resolution is performed in this case.
5127 if (RD->hasTrivialDefaultConstructor())
5128 return true;
5129
5130 if (Selected) {
5131 // If there's a default constructor which could have been trivial, dig it
5132 // out. Otherwise, if there's any user-provided default constructor, point
5133 // to that as an example of why there's not a trivial one.
5134 CXXConstructorDecl *DefCtor = 0;
5135 if (RD->needsImplicitDefaultConstructor())
5136 S.DeclareImplicitDefaultConstructor(RD);
5137 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5138 CE = RD->ctor_end(); CI != CE; ++CI) {
5139 if (!CI->isDefaultConstructor())
5140 continue;
5141 DefCtor = *CI;
5142 if (!DefCtor->isUserProvided())
5143 break;
5144 }
5145
5146 *Selected = DefCtor;
5147 }
5148
5149 return false;
5150
5151 case Sema::CXXDestructor:
5152 // C++11 [class.dtor]p5:
5153 // A destructor is trivial if:
5154 // - all the direct [subobjects] have trivial destructors
5155 if (RD->hasTrivialDestructor())
5156 return true;
5157
5158 if (Selected) {
5159 if (RD->needsImplicitDestructor())
5160 S.DeclareImplicitDestructor(RD);
5161 *Selected = RD->getDestructor();
5162 }
5163
5164 return false;
5165
5166 case Sema::CXXCopyConstructor:
5167 // C++11 [class.copy]p12:
5168 // A copy constructor is trivial if:
5169 // - the constructor selected to copy each direct [subobject] is trivial
5170 if (RD->hasTrivialCopyConstructor()) {
5171 if (Quals == Qualifiers::Const)
5172 // We must either select the trivial copy constructor or reach an
5173 // ambiguity; no need to actually perform overload resolution.
5174 return true;
5175 } else if (!Selected) {
5176 return false;
5177 }
5178 // In C++98, we are not supposed to perform overload resolution here, but we
5179 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5180 // cases like B as having a non-trivial copy constructor:
5181 // struct A { template<typename T> A(T&); };
5182 // struct B { mutable A a; };
5183 goto NeedOverloadResolution;
5184
5185 case Sema::CXXCopyAssignment:
5186 // C++11 [class.copy]p25:
5187 // A copy assignment operator is trivial if:
5188 // - the assignment operator selected to copy each direct [subobject] is
5189 // trivial
5190 if (RD->hasTrivialCopyAssignment()) {
5191 if (Quals == Qualifiers::Const)
5192 return true;
5193 } else if (!Selected) {
5194 return false;
5195 }
5196 // In C++98, we are not supposed to perform overload resolution here, but we
5197 // treat that as a language defect.
5198 goto NeedOverloadResolution;
5199
5200 case Sema::CXXMoveConstructor:
5201 case Sema::CXXMoveAssignment:
5202 NeedOverloadResolution:
5203 Sema::SpecialMemberOverloadResult *SMOR =
5204 S.LookupSpecialMember(RD, CSM,
5205 Quals & Qualifiers::Const,
5206 Quals & Qualifiers::Volatile,
5207 /*RValueThis*/false, /*ConstThis*/false,
5208 /*VolatileThis*/false);
5209
5210 // The standard doesn't describe how to behave if the lookup is ambiguous.
5211 // We treat it as not making the member non-trivial, just like the standard
5212 // mandates for the default constructor. This should rarely matter, because
5213 // the member will also be deleted.
5214 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5215 return true;
5216
5217 if (!SMOR->getMethod()) {
5218 assert(SMOR->getKind() ==
5219 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5220 return false;
5221 }
5222
5223 // We deliberately don't check if we found a deleted special member. We're
5224 // not supposed to!
5225 if (Selected)
5226 *Selected = SMOR->getMethod();
5227 return SMOR->getMethod()->isTrivial();
5228 }
5229
5230 llvm_unreachable("unknown special method kind");
5231}
5232
Benjamin Kramera574c892013-02-15 12:30:38 +00005233static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005234 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5235 CI != CE; ++CI)
5236 if (!CI->isImplicit())
5237 return *CI;
5238
5239 // Look for constructor templates.
5240 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5241 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5242 if (CXXConstructorDecl *CD =
5243 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5244 return CD;
5245 }
5246
5247 return 0;
5248}
5249
5250/// The kind of subobject we are checking for triviality. The values of this
5251/// enumeration are used in diagnostics.
5252enum TrivialSubobjectKind {
5253 /// The subobject is a base class.
5254 TSK_BaseClass,
5255 /// The subobject is a non-static data member.
5256 TSK_Field,
5257 /// The object is actually the complete object.
5258 TSK_CompleteObject
5259};
5260
5261/// Check whether the special member selected for a given type would be trivial.
5262static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5263 QualType SubType,
5264 Sema::CXXSpecialMember CSM,
5265 TrivialSubobjectKind Kind,
5266 bool Diagnose) {
5267 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5268 if (!SubRD)
5269 return true;
5270
5271 CXXMethodDecl *Selected;
5272 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5273 Diagnose ? &Selected : 0))
5274 return true;
5275
5276 if (Diagnose) {
5277 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5278 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5279 << Kind << SubType.getUnqualifiedType();
5280 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5281 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5282 } else if (!Selected)
5283 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5284 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5285 else if (Selected->isUserProvided()) {
5286 if (Kind == TSK_CompleteObject)
5287 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5288 << Kind << SubType.getUnqualifiedType() << CSM;
5289 else {
5290 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5291 << Kind << SubType.getUnqualifiedType() << CSM;
5292 S.Diag(Selected->getLocation(), diag::note_declared_at);
5293 }
5294 } else {
5295 if (Kind != TSK_CompleteObject)
5296 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5297 << Kind << SubType.getUnqualifiedType() << CSM;
5298
5299 // Explain why the defaulted or deleted special member isn't trivial.
5300 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5301 }
5302 }
5303
5304 return false;
5305}
5306
5307/// Check whether the members of a class type allow a special member to be
5308/// trivial.
5309static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5310 Sema::CXXSpecialMember CSM,
5311 bool ConstArg, bool Diagnose) {
5312 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5313 FE = RD->field_end(); FI != FE; ++FI) {
5314 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5315 continue;
5316
5317 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5318
5319 // Pretend anonymous struct or union members are members of this class.
5320 if (FI->isAnonymousStructOrUnion()) {
5321 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5322 CSM, ConstArg, Diagnose))
5323 return false;
5324 continue;
5325 }
5326
5327 // C++11 [class.ctor]p5:
5328 // A default constructor is trivial if [...]
5329 // -- no non-static data member of its class has a
5330 // brace-or-equal-initializer
5331 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5332 if (Diagnose)
5333 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5334 return false;
5335 }
5336
5337 // Objective C ARC 4.3.5:
5338 // [...] nontrivally ownership-qualified types are [...] not trivially
5339 // default constructible, copy constructible, move constructible, copy
5340 // assignable, move assignable, or destructible [...]
5341 if (S.getLangOpts().ObjCAutoRefCount &&
5342 FieldType.hasNonTrivialObjCLifetime()) {
5343 if (Diagnose)
5344 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5345 << RD << FieldType.getObjCLifetime();
5346 return false;
5347 }
5348
5349 if (ConstArg && !FI->isMutable())
5350 FieldType.addConst();
5351 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5352 TSK_Field, Diagnose))
5353 return false;
5354 }
5355
5356 return true;
5357}
5358
5359/// Diagnose why the specified class does not have a trivial special member of
5360/// the given kind.
5361void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5362 QualType Ty = Context.getRecordType(RD);
5363 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5364 Ty.addConst();
5365
5366 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5367 TSK_CompleteObject, /*Diagnose*/true);
5368}
5369
5370/// Determine whether a defaulted or deleted special member function is trivial,
5371/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5372/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5373bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5374 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005375 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5376
5377 CXXRecordDecl *RD = MD->getParent();
5378
5379 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005380
5381 // C++11 [class.copy]p12, p25:
5382 // A [special member] is trivial if its declared parameter type is the same
5383 // as if it had been implicitly declared [...]
5384 switch (CSM) {
5385 case CXXDefaultConstructor:
5386 case CXXDestructor:
5387 // Trivial default constructors and destructors cannot have parameters.
5388 break;
5389
5390 case CXXCopyConstructor:
5391 case CXXCopyAssignment: {
5392 // Trivial copy operations always have const, non-volatile parameter types.
5393 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005394 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005395 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5396 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5397 if (Diagnose)
5398 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5399 << Param0->getSourceRange() << Param0->getType()
5400 << Context.getLValueReferenceType(
5401 Context.getRecordType(RD).withConst());
5402 return false;
5403 }
5404 break;
5405 }
5406
5407 case CXXMoveConstructor:
5408 case CXXMoveAssignment: {
5409 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005410 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005411 const RValueReferenceType *RT =
5412 Param0->getType()->getAs<RValueReferenceType>();
5413 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5414 if (Diagnose)
5415 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5416 << Param0->getSourceRange() << Param0->getType()
5417 << Context.getRValueReferenceType(Context.getRecordType(RD));
5418 return false;
5419 }
5420 break;
5421 }
5422
5423 case CXXInvalid:
5424 llvm_unreachable("not a special member");
5425 }
5426
5427 // FIXME: We require that the parameter-declaration-clause is equivalent to
5428 // that of an implicit declaration, not just that the declared parameter type
5429 // matches, in order to prevent absuridities like a function simultaneously
5430 // being a trivial copy constructor and a non-trivial default constructor.
5431 // This issue has not yet been assigned a core issue number.
5432 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5433 if (Diagnose)
5434 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5435 diag::note_nontrivial_default_arg)
5436 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5437 return false;
5438 }
5439 if (MD->isVariadic()) {
5440 if (Diagnose)
5441 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5442 return false;
5443 }
5444
5445 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5446 // A copy/move [constructor or assignment operator] is trivial if
5447 // -- the [member] selected to copy/move each direct base class subobject
5448 // is trivial
5449 //
5450 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5451 // A [default constructor or destructor] is trivial if
5452 // -- all the direct base classes have trivial [default constructors or
5453 // destructors]
5454 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5455 BE = RD->bases_end(); BI != BE; ++BI)
5456 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5457 ConstArg ? BI->getType().withConst()
5458 : BI->getType(),
5459 CSM, TSK_BaseClass, Diagnose))
5460 return false;
5461
5462 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5463 // A copy/move [constructor or assignment operator] for a class X is
5464 // trivial if
5465 // -- for each non-static data member of X that is of class type (or array
5466 // thereof), the constructor selected to copy/move that member is
5467 // trivial
5468 //
5469 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5470 // A [default constructor or destructor] is trivial if
5471 // -- for all of the non-static data members of its class that are of class
5472 // type (or array thereof), each such class has a trivial [default
5473 // constructor or destructor]
5474 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5475 return false;
5476
5477 // C++11 [class.dtor]p5:
5478 // A destructor is trivial if [...]
5479 // -- the destructor is not virtual
5480 if (CSM == CXXDestructor && MD->isVirtual()) {
5481 if (Diagnose)
5482 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5483 return false;
5484 }
5485
5486 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5487 // A [special member] for class X is trivial if [...]
5488 // -- class X has no virtual functions and no virtual base classes
5489 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5490 if (!Diagnose)
5491 return false;
5492
5493 if (RD->getNumVBases()) {
5494 // Check for virtual bases. We already know that the corresponding
5495 // member in all bases is trivial, so vbases must all be direct.
5496 CXXBaseSpecifier &BS = *RD->vbases_begin();
5497 assert(BS.isVirtual());
5498 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5499 return false;
5500 }
5501
5502 // Must have a virtual method.
5503 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5504 ME = RD->method_end(); MI != ME; ++MI) {
5505 if (MI->isVirtual()) {
5506 SourceLocation MLoc = MI->getLocStart();
5507 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5508 return false;
5509 }
5510 }
5511
5512 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5513 }
5514
5515 // Looks like it's trivial!
5516 return true;
5517}
5518
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005519/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005520namespace {
5521 struct FindHiddenVirtualMethodData {
5522 Sema *S;
5523 CXXMethodDecl *Method;
5524 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005525 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005526 };
5527}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005528
David Blaikie5f750682012-10-19 00:53:08 +00005529/// \brief Check whether any most overriden method from MD in Methods
5530static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5531 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5532 if (MD->size_overridden_methods() == 0)
5533 return Methods.count(MD->getCanonicalDecl());
5534 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5535 E = MD->end_overridden_methods();
5536 I != E; ++I)
5537 if (CheckMostOverridenMethods(*I, Methods))
5538 return true;
5539 return false;
5540}
5541
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005542/// \brief Member lookup function that determines whether a given C++
5543/// method overloads virtual methods in a base class without overriding any,
5544/// to be used with CXXRecordDecl::lookupInBases().
5545static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5546 CXXBasePath &Path,
5547 void *UserData) {
5548 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5549
5550 FindHiddenVirtualMethodData &Data
5551 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5552
5553 DeclarationName Name = Data.Method->getDeclName();
5554 assert(Name.getNameKind() == DeclarationName::Identifier);
5555
5556 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005557 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005558 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005559 !Path.Decls.empty();
5560 Path.Decls = Path.Decls.slice(1)) {
5561 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005562 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005563 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005564 foundSameNameMethod = true;
5565 // Interested only in hidden virtual methods.
5566 if (!MD->isVirtual())
5567 continue;
5568 // If the method we are checking overrides a method from its base
5569 // don't warn about the other overloaded methods.
5570 if (!Data.S->IsOverload(Data.Method, MD, false))
5571 return true;
5572 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005573 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005574 overloadedMethods.push_back(MD);
5575 }
5576 }
5577
5578 if (foundSameNameMethod)
5579 Data.OverloadedMethods.append(overloadedMethods.begin(),
5580 overloadedMethods.end());
5581 return foundSameNameMethod;
5582}
5583
David Blaikie5f750682012-10-19 00:53:08 +00005584/// \brief Add the most overriden methods from MD to Methods
5585static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5586 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5587 if (MD->size_overridden_methods() == 0)
5588 Methods.insert(MD->getCanonicalDecl());
5589 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5590 E = MD->end_overridden_methods();
5591 I != E; ++I)
5592 AddMostOverridenMethods(*I, Methods);
5593}
5594
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005595/// \brief See if a method overloads virtual methods in a base class without
5596/// overriding any.
5597void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5598 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005599 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005600 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005601 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005602 return;
5603
5604 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5605 /*bool RecordPaths=*/false,
5606 /*bool DetectVirtual=*/false);
5607 FindHiddenVirtualMethodData Data;
5608 Data.Method = MD;
5609 Data.S = this;
5610
5611 // Keep the base methods that were overriden or introduced in the subclass
5612 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005613 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5614 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5615 NamedDecl *ND = *I;
5616 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005617 ND = shad->getTargetDecl();
5618 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5619 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005620 }
5621
5622 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5623 !Data.OverloadedMethods.empty()) {
5624 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5625 << MD << (Data.OverloadedMethods.size() > 1);
5626
5627 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5628 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005629 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005630 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005631 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5632 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005633 }
5634 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005635}
5636
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005637void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005638 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005639 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005640 SourceLocation RBrac,
5641 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005642 if (!TagDecl)
5643 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005644
Douglas Gregor42af25f2009-05-11 19:58:34 +00005645 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005646
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005647 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5648 if (l->getKind() != AttributeList::AT_Visibility)
5649 continue;
5650 l->setInvalid();
5651 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5652 l->getName();
5653 }
5654
David Blaikie77b6de02011-09-22 02:58:26 +00005655 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005656 // strict aliasing violation!
5657 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005658 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005659
Douglas Gregor23c94db2010-07-02 17:43:08 +00005660 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005661 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005662}
5663
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005664/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5665/// special functions, such as the default constructor, copy
5666/// constructor, or destructor, to the given C++ class (C++
5667/// [special]p1). This routine can only be executed just before the
5668/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005669void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005670 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005671 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005672
Richard Smithbc2a35d2012-12-08 08:32:28 +00005673 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005674 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005675
Richard Smithbc2a35d2012-12-08 08:32:28 +00005676 // If the properties or semantics of the copy constructor couldn't be
5677 // determined while the class was being declared, force a declaration
5678 // of it now.
5679 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5680 DeclareImplicitCopyConstructor(ClassDecl);
5681 }
5682
Richard Smith80ad52f2013-01-02 11:42:31 +00005683 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005684 ++ASTContext::NumImplicitMoveConstructors;
5685
Richard Smithbc2a35d2012-12-08 08:32:28 +00005686 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5687 DeclareImplicitMoveConstructor(ClassDecl);
5688 }
5689
Douglas Gregora376d102010-07-02 21:50:04 +00005690 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5691 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005692
5693 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005694 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005695 // it shows up in the right place in the vtable and that we diagnose
5696 // problems with the implicit exception specification.
5697 if (ClassDecl->isDynamicClass() ||
5698 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005699 DeclareImplicitCopyAssignment(ClassDecl);
5700 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005701
Richard Smith80ad52f2013-01-02 11:42:31 +00005702 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005703 ++ASTContext::NumImplicitMoveAssignmentOperators;
5704
5705 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005706 if (ClassDecl->isDynamicClass() ||
5707 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005708 DeclareImplicitMoveAssignment(ClassDecl);
5709 }
5710
Douglas Gregor4923aa22010-07-02 20:37:36 +00005711 if (!ClassDecl->hasUserDeclaredDestructor()) {
5712 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005713
5714 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005715 // have to declare the destructor immediately. This ensures that, e.g., it
5716 // shows up in the right place in the vtable and that we diagnose problems
5717 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005718 if (ClassDecl->isDynamicClass() ||
5719 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005720 DeclareImplicitDestructor(ClassDecl);
5721 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005722}
5723
Francois Pichet8387e2a2011-04-22 22:18:13 +00005724void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5725 if (!D)
5726 return;
5727
5728 int NumParamList = D->getNumTemplateParameterLists();
5729 for (int i = 0; i < NumParamList; i++) {
5730 TemplateParameterList* Params = D->getTemplateParameterList(i);
5731 for (TemplateParameterList::iterator Param = Params->begin(),
5732 ParamEnd = Params->end();
5733 Param != ParamEnd; ++Param) {
5734 NamedDecl *Named = cast<NamedDecl>(*Param);
5735 if (Named->getDeclName()) {
5736 S->AddDecl(Named);
5737 IdResolver.AddDecl(Named);
5738 }
5739 }
5740 }
5741}
5742
John McCalld226f652010-08-21 09:40:31 +00005743void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005744 if (!D)
5745 return;
5746
5747 TemplateParameterList *Params = 0;
5748 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5749 Params = Template->getTemplateParameters();
5750 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5751 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5752 Params = PartialSpec->getTemplateParameters();
5753 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005754 return;
5755
Douglas Gregor6569d682009-05-27 23:11:45 +00005756 for (TemplateParameterList::iterator Param = Params->begin(),
5757 ParamEnd = Params->end();
5758 Param != ParamEnd; ++Param) {
5759 NamedDecl *Named = cast<NamedDecl>(*Param);
5760 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005761 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005762 IdResolver.AddDecl(Named);
5763 }
5764 }
5765}
5766
John McCalld226f652010-08-21 09:40:31 +00005767void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005768 if (!RecordD) return;
5769 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005770 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005771 PushDeclContext(S, Record);
5772}
5773
John McCalld226f652010-08-21 09:40:31 +00005774void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005775 if (!RecordD) return;
5776 PopDeclContext();
5777}
5778
Douglas Gregor72b505b2008-12-16 21:30:33 +00005779/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5780/// parsing a top-level (non-nested) C++ class, and we are now
5781/// parsing those parts of the given Method declaration that could
5782/// not be parsed earlier (C++ [class.mem]p2), such as default
5783/// arguments. This action should enter the scope of the given
5784/// Method declaration as if we had just parsed the qualified method
5785/// name. However, it should not bring the parameters into scope;
5786/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005787void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005788}
5789
5790/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5791/// C++ method declaration. We're (re-)introducing the given
5792/// function parameter into scope for use in parsing later parts of
5793/// the method declaration. For example, we could see an
5794/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005795void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005796 if (!ParamD)
5797 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005798
John McCalld226f652010-08-21 09:40:31 +00005799 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005800
5801 // If this parameter has an unparsed default argument, clear it out
5802 // to make way for the parsed default argument.
5803 if (Param->hasUnparsedDefaultArg())
5804 Param->setDefaultArg(0);
5805
John McCalld226f652010-08-21 09:40:31 +00005806 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005807 if (Param->getDeclName())
5808 IdResolver.AddDecl(Param);
5809}
5810
5811/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5812/// processing the delayed method declaration for Method. The method
5813/// declaration is now considered finished. There may be a separate
5814/// ActOnStartOfFunctionDef action later (not necessarily
5815/// immediately!) for this method, if it was also defined inside the
5816/// class body.
John McCalld226f652010-08-21 09:40:31 +00005817void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005818 if (!MethodD)
5819 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005820
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005821 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005822
John McCalld226f652010-08-21 09:40:31 +00005823 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005824
5825 // Now that we have our default arguments, check the constructor
5826 // again. It could produce additional diagnostics or affect whether
5827 // the class has implicitly-declared destructors, among other
5828 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005829 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5830 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005831
5832 // Check the default arguments, which we may have added.
5833 if (!Method->isInvalidDecl())
5834 CheckCXXDefaultArguments(Method);
5835}
5836
Douglas Gregor42a552f2008-11-05 20:51:48 +00005837/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005838/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005839/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005840/// emit diagnostics and set the invalid bit to true. In any case, the type
5841/// will be updated to reflect a well-formed type for the constructor and
5842/// returned.
5843QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005844 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005845 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005846
5847 // C++ [class.ctor]p3:
5848 // A constructor shall not be virtual (10.3) or static (9.4). A
5849 // constructor can be invoked for a const, volatile or const
5850 // volatile object. A constructor shall not be declared const,
5851 // volatile, or const volatile (9.3.2).
5852 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005853 if (!D.isInvalidType())
5854 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5855 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5856 << SourceRange(D.getIdentifierLoc());
5857 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005858 }
John McCalld931b082010-08-26 03:08:43 +00005859 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005860 if (!D.isInvalidType())
5861 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5862 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5863 << SourceRange(D.getIdentifierLoc());
5864 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005865 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005866 }
Mike Stump1eb44332009-09-09 15:08:12 +00005867
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005868 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005869 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005870 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005871 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5872 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005873 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005874 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5875 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005876 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005877 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5878 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005879 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005880 }
Mike Stump1eb44332009-09-09 15:08:12 +00005881
Douglas Gregorc938c162011-01-26 05:01:58 +00005882 // C++0x [class.ctor]p4:
5883 // A constructor shall not be declared with a ref-qualifier.
5884 if (FTI.hasRefQualifier()) {
5885 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5886 << FTI.RefQualifierIsLValueRef
5887 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5888 D.setInvalidType();
5889 }
5890
Douglas Gregor42a552f2008-11-05 20:51:48 +00005891 // Rebuild the function type "R" without any type qualifiers (in
5892 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005893 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005894 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005895 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5896 return R;
5897
5898 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5899 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005900 EPI.RefQualifier = RQ_None;
5901
Richard Smith07b0fdc2013-03-18 21:12:30 +00005902 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005903}
5904
Douglas Gregor72b505b2008-12-16 21:30:33 +00005905/// CheckConstructor - Checks a fully-formed constructor for
5906/// well-formedness, issuing any diagnostics required. Returns true if
5907/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005908void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005909 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005910 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5911 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005912 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005913
5914 // C++ [class.copy]p3:
5915 // A declaration of a constructor for a class X is ill-formed if
5916 // its first parameter is of type (optionally cv-qualified) X and
5917 // either there are no other parameters or else all other
5918 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005919 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005920 ((Constructor->getNumParams() == 1) ||
5921 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005922 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5923 Constructor->getTemplateSpecializationKind()
5924 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005925 QualType ParamType = Constructor->getParamDecl(0)->getType();
5926 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5927 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005928 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005929 const char *ConstRef
5930 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5931 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005932 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005933 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005934
5935 // FIXME: Rather that making the constructor invalid, we should endeavor
5936 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005937 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005938 }
5939 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005940}
5941
John McCall15442822010-08-04 01:04:25 +00005942/// CheckDestructor - Checks a fully-formed destructor definition for
5943/// well-formedness, issuing any diagnostics required. Returns true
5944/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005945bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005946 CXXRecordDecl *RD = Destructor->getParent();
5947
Peter Collingbournef51cfb82013-05-20 14:12:25 +00005948 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005949 SourceLocation Loc;
5950
5951 if (!Destructor->isImplicit())
5952 Loc = Destructor->getLocation();
5953 else
5954 Loc = RD->getLocation();
5955
5956 // If we have a virtual destructor, look up the deallocation function
5957 FunctionDecl *OperatorDelete = 0;
5958 DeclarationName Name =
5959 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005960 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005961 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005962
Eli Friedman5f2987c2012-02-02 03:46:19 +00005963 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005964
5965 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005966 }
Anders Carlsson37909802009-11-30 21:24:50 +00005967
5968 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005969}
5970
Mike Stump1eb44332009-09-09 15:08:12 +00005971static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005972FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5973 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5974 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005975 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005976}
5977
Douglas Gregor42a552f2008-11-05 20:51:48 +00005978/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5979/// the well-formednes of the destructor declarator @p D with type @p
5980/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005981/// emit diagnostics and set the declarator to invalid. Even if this happens,
5982/// will be updated to reflect a well-formed type for the destructor and
5983/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005984QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005985 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005986 // C++ [class.dtor]p1:
5987 // [...] A typedef-name that names a class is a class-name
5988 // (7.1.3); however, a typedef-name that names a class shall not
5989 // be used as the identifier in the declarator for a destructor
5990 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005991 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005992 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005993 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005994 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005995 else if (const TemplateSpecializationType *TST =
5996 DeclaratorType->getAs<TemplateSpecializationType>())
5997 if (TST->isTypeAlias())
5998 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5999 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006000
6001 // C++ [class.dtor]p2:
6002 // A destructor is used to destroy objects of its class type. A
6003 // destructor takes no parameters, and no return type can be
6004 // specified for it (not even void). The address of a destructor
6005 // shall not be taken. A destructor shall not be static. A
6006 // destructor can be invoked for a const, volatile or const
6007 // volatile object. A destructor shall not be declared const,
6008 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006009 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006010 if (!D.isInvalidType())
6011 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6012 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006013 << SourceRange(D.getIdentifierLoc())
6014 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6015
John McCalld931b082010-08-26 03:08:43 +00006016 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006017 }
Chris Lattner65401802009-04-25 08:28:21 +00006018 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006019 // Destructors don't have return types, but the parser will
6020 // happily parse something like:
6021 //
6022 // class X {
6023 // float ~X();
6024 // };
6025 //
6026 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006027 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6028 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6029 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006030 }
Mike Stump1eb44332009-09-09 15:08:12 +00006031
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006032 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006033 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006034 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006035 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6036 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006037 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006038 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6039 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006040 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006041 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6042 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006043 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006044 }
6045
Douglas Gregorc938c162011-01-26 05:01:58 +00006046 // C++0x [class.dtor]p2:
6047 // A destructor shall not be declared with a ref-qualifier.
6048 if (FTI.hasRefQualifier()) {
6049 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6050 << FTI.RefQualifierIsLValueRef
6051 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6052 D.setInvalidType();
6053 }
6054
Douglas Gregor42a552f2008-11-05 20:51:48 +00006055 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006056 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006057 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6058
6059 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006060 FTI.freeArgs();
6061 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006062 }
6063
Mike Stump1eb44332009-09-09 15:08:12 +00006064 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006065 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006066 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006067 D.setInvalidType();
6068 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006069
6070 // Rebuild the function type "R" without any type qualifiers or
6071 // parameters (in case any of the errors above fired) and with
6072 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006073 // types.
John McCalle23cf432010-12-14 08:05:40 +00006074 if (!D.isInvalidType())
6075 return R;
6076
Douglas Gregord92ec472010-07-01 05:10:53 +00006077 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006078 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6079 EPI.Variadic = false;
6080 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006081 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006082 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006083}
6084
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006085/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6086/// well-formednes of the conversion function declarator @p D with
6087/// type @p R. If there are any errors in the declarator, this routine
6088/// will emit diagnostics and return true. Otherwise, it will return
6089/// false. Either way, the type @p R will be updated to reflect a
6090/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006091void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006092 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006093 // C++ [class.conv.fct]p1:
6094 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006095 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006096 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006097 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006098 if (!D.isInvalidType())
6099 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006100 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6101 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006102 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006103 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006104 }
John McCalla3f81372010-04-13 00:04:31 +00006105
6106 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6107
Chris Lattner6e475012009-04-25 08:35:12 +00006108 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006109 // Conversion functions don't have return types, but the parser will
6110 // happily parse something like:
6111 //
6112 // class X {
6113 // float operator bool();
6114 // };
6115 //
6116 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006117 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6118 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6119 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006120 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006121 }
6122
John McCalla3f81372010-04-13 00:04:31 +00006123 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6124
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006125 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006126 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006127 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6128
6129 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006130 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006131 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006132 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006133 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006134 D.setInvalidType();
6135 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006136
John McCalla3f81372010-04-13 00:04:31 +00006137 // Diagnose "&operator bool()" and other such nonsense. This
6138 // is actually a gcc extension which we don't support.
6139 if (Proto->getResultType() != ConvType) {
6140 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6141 << Proto->getResultType();
6142 D.setInvalidType();
6143 ConvType = Proto->getResultType();
6144 }
6145
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006146 // C++ [class.conv.fct]p4:
6147 // The conversion-type-id shall not represent a function type nor
6148 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006149 if (ConvType->isArrayType()) {
6150 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6151 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006152 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006153 } else if (ConvType->isFunctionType()) {
6154 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6155 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006156 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006157 }
6158
6159 // Rebuild the function type "R" without any parameters (in case any
6160 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006161 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006162 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006163 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006164
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006165 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006166 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006167 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006168 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006169 diag::warn_cxx98_compat_explicit_conversion_functions :
6170 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006171 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006172}
6173
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006174/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6175/// the declaration of the given C++ conversion function. This routine
6176/// is responsible for recording the conversion function in the C++
6177/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006178Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006179 assert(Conversion && "Expected to receive a conversion function declaration");
6180
Douglas Gregor9d350972008-12-12 08:25:50 +00006181 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006182
6183 // Make sure we aren't redeclaring the conversion function.
6184 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006185
6186 // C++ [class.conv.fct]p1:
6187 // [...] A conversion function is never used to convert a
6188 // (possibly cv-qualified) object to the (possibly cv-qualified)
6189 // same object type (or a reference to it), to a (possibly
6190 // cv-qualified) base class of that type (or a reference to it),
6191 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006192 // FIXME: Suppress this warning if the conversion function ends up being a
6193 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006194 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006195 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006196 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006197 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006198 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6199 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006200 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006201 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006202 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6203 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006204 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006205 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006206 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006207 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006208 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006209 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006210 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006211 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006212 }
6213
Douglas Gregore80622f2010-09-29 04:25:11 +00006214 if (FunctionTemplateDecl *ConversionTemplate
6215 = Conversion->getDescribedFunctionTemplate())
6216 return ConversionTemplate;
6217
John McCalld226f652010-08-21 09:40:31 +00006218 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006219}
6220
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006221//===----------------------------------------------------------------------===//
6222// Namespace Handling
6223//===----------------------------------------------------------------------===//
6224
Richard Smithd1a55a62012-10-04 22:13:39 +00006225/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6226/// reopened.
6227static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6228 SourceLocation Loc,
6229 IdentifierInfo *II, bool *IsInline,
6230 NamespaceDecl *PrevNS) {
6231 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006232
Richard Smithc969e6a2012-10-05 01:46:25 +00006233 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6234 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6235 // inline namespaces, with the intention of bringing names into namespace std.
6236 //
6237 // We support this just well enough to get that case working; this is not
6238 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006239 if (*IsInline && II && II->getName().startswith("__atomic") &&
6240 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006241 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006242 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6243 NS = NS->getPreviousDecl())
6244 NS->setInline(*IsInline);
6245 // Patch up the lookup table for the containing namespace. This isn't really
6246 // correct, but it's good enough for this particular case.
6247 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6248 E = PrevNS->decls_end(); I != E; ++I)
6249 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6250 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6251 return;
6252 }
6253
6254 if (PrevNS->isInline())
6255 // The user probably just forgot the 'inline', so suggest that it
6256 // be added back.
6257 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6258 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6259 else
6260 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6261 << IsInline;
6262
6263 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6264 *IsInline = PrevNS->isInline();
6265}
John McCallea318642010-08-26 09:15:37 +00006266
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006267/// ActOnStartNamespaceDef - This is called at the start of a namespace
6268/// definition.
John McCalld226f652010-08-21 09:40:31 +00006269Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006270 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006271 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006272 SourceLocation IdentLoc,
6273 IdentifierInfo *II,
6274 SourceLocation LBrace,
6275 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006276 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6277 // For anonymous namespace, take the location of the left brace.
6278 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006279 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006280 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006281 bool IsStd = false;
6282 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006283 Scope *DeclRegionScope = NamespcScope->getParent();
6284
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006285 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006286 if (II) {
6287 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006288 // The identifier in an original-namespace-definition shall not
6289 // have been previously defined in the declarative region in
6290 // which the original-namespace-definition appears. The
6291 // identifier in an original-namespace-definition is the name of
6292 // the namespace. Subsequently in that declarative region, it is
6293 // treated as an original-namespace-name.
6294 //
6295 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006296 // look through using directives, just look for any ordinary names.
6297
6298 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006299 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6300 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006301 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006302 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6303 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6304 ++I) {
6305 if ((*I)->getIdentifierNamespace() & IDNS) {
6306 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006307 break;
6308 }
6309 }
6310
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006311 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6312
6313 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006314 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006315 if (IsInline != PrevNS->isInline())
6316 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6317 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006318 } else if (PrevDecl) {
6319 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006320 Diag(Loc, diag::err_redefinition_different_kind)
6321 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006322 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006323 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006324 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006325 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006326 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006327 // This is the first "real" definition of the namespace "std", so update
6328 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006329 PrevNS = getStdNamespace();
6330 IsStd = true;
6331 AddToKnown = !IsInline;
6332 } else {
6333 // We've seen this namespace for the first time.
6334 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006335 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006336 } else {
John McCall9aeed322009-10-01 00:25:31 +00006337 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006338
6339 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006340 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006341 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006342 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006343 } else {
6344 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006345 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006346 }
6347
Richard Smithd1a55a62012-10-04 22:13:39 +00006348 if (PrevNS && IsInline != PrevNS->isInline())
6349 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6350 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006351 }
6352
6353 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6354 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006355 if (IsInvalid)
6356 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006357
6358 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006359
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006360 // FIXME: Should we be merging attributes?
6361 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006362 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006363
6364 if (IsStd)
6365 StdNamespace = Namespc;
6366 if (AddToKnown)
6367 KnownNamespaces[Namespc] = false;
6368
6369 if (II) {
6370 PushOnScopeChains(Namespc, DeclRegionScope);
6371 } else {
6372 // Link the anonymous namespace into its parent.
6373 DeclContext *Parent = CurContext->getRedeclContext();
6374 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6375 TU->setAnonymousNamespace(Namespc);
6376 } else {
6377 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006378 }
John McCall9aeed322009-10-01 00:25:31 +00006379
Douglas Gregora4181472010-03-24 00:46:35 +00006380 CurContext->addDecl(Namespc);
6381
John McCall9aeed322009-10-01 00:25:31 +00006382 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6383 // behaves as if it were replaced by
6384 // namespace unique { /* empty body */ }
6385 // using namespace unique;
6386 // namespace unique { namespace-body }
6387 // where all occurrences of 'unique' in a translation unit are
6388 // replaced by the same identifier and this identifier differs
6389 // from all other identifiers in the entire program.
6390
6391 // We just create the namespace with an empty name and then add an
6392 // implicit using declaration, just like the standard suggests.
6393 //
6394 // CodeGen enforces the "universally unique" aspect by giving all
6395 // declarations semantically contained within an anonymous
6396 // namespace internal linkage.
6397
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006398 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006399 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006400 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006401 /* 'using' */ LBrace,
6402 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006403 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006404 /* identifier */ SourceLocation(),
6405 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006406 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006407 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006408 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006409 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006410 }
6411
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006412 ActOnDocumentableDecl(Namespc);
6413
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006414 // Although we could have an invalid decl (i.e. the namespace name is a
6415 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006416 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6417 // for the namespace has the declarations that showed up in that particular
6418 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006419 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006420 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006421}
6422
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006423/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6424/// is a namespace alias, returns the namespace it points to.
6425static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6426 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6427 return AD->getNamespace();
6428 return dyn_cast_or_null<NamespaceDecl>(D);
6429}
6430
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006431/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6432/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006433void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006434 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6435 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006436 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006437 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006438 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006439 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006440}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006441
John McCall384aff82010-08-25 07:42:41 +00006442CXXRecordDecl *Sema::getStdBadAlloc() const {
6443 return cast_or_null<CXXRecordDecl>(
6444 StdBadAlloc.get(Context.getExternalSource()));
6445}
6446
6447NamespaceDecl *Sema::getStdNamespace() const {
6448 return cast_or_null<NamespaceDecl>(
6449 StdNamespace.get(Context.getExternalSource()));
6450}
6451
Douglas Gregor66992202010-06-29 17:53:46 +00006452/// \brief Retrieve the special "std" namespace, which may require us to
6453/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006454NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006455 if (!StdNamespace) {
6456 // The "std" namespace has not yet been defined, so build one implicitly.
6457 StdNamespace = NamespaceDecl::Create(Context,
6458 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006459 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006460 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006461 &PP.getIdentifierTable().get("std"),
6462 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006463 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006464 }
6465
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006466 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006467}
6468
Sebastian Redl395e04d2012-01-17 22:49:33 +00006469bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006470 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006471 "Looking for std::initializer_list outside of C++.");
6472
6473 // We're looking for implicit instantiations of
6474 // template <typename E> class std::initializer_list.
6475
6476 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6477 return false;
6478
Sebastian Redl84760e32012-01-17 22:49:58 +00006479 ClassTemplateDecl *Template = 0;
6480 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006481
Sebastian Redl84760e32012-01-17 22:49:58 +00006482 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006483
Sebastian Redl84760e32012-01-17 22:49:58 +00006484 ClassTemplateSpecializationDecl *Specialization =
6485 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6486 if (!Specialization)
6487 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006488
Sebastian Redl84760e32012-01-17 22:49:58 +00006489 Template = Specialization->getSpecializedTemplate();
6490 Arguments = Specialization->getTemplateArgs().data();
6491 } else if (const TemplateSpecializationType *TST =
6492 Ty->getAs<TemplateSpecializationType>()) {
6493 Template = dyn_cast_or_null<ClassTemplateDecl>(
6494 TST->getTemplateName().getAsTemplateDecl());
6495 Arguments = TST->getArgs();
6496 }
6497 if (!Template)
6498 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006499
6500 if (!StdInitializerList) {
6501 // Haven't recognized std::initializer_list yet, maybe this is it.
6502 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6503 if (TemplateClass->getIdentifier() !=
6504 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006505 !getStdNamespace()->InEnclosingNamespaceSetOf(
6506 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006507 return false;
6508 // This is a template called std::initializer_list, but is it the right
6509 // template?
6510 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006511 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006512 return false;
6513 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6514 return false;
6515
6516 // It's the right template.
6517 StdInitializerList = Template;
6518 }
6519
6520 if (Template != StdInitializerList)
6521 return false;
6522
6523 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006524 if (Element)
6525 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006526 return true;
6527}
6528
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006529static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6530 NamespaceDecl *Std = S.getStdNamespace();
6531 if (!Std) {
6532 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6533 return 0;
6534 }
6535
6536 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6537 Loc, Sema::LookupOrdinaryName);
6538 if (!S.LookupQualifiedName(Result, Std)) {
6539 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6540 return 0;
6541 }
6542 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6543 if (!Template) {
6544 Result.suppressDiagnostics();
6545 // We found something weird. Complain about the first thing we found.
6546 NamedDecl *Found = *Result.begin();
6547 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6548 return 0;
6549 }
6550
6551 // We found some template called std::initializer_list. Now verify that it's
6552 // correct.
6553 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006554 if (Params->getMinRequiredArguments() != 1 ||
6555 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006556 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6557 return 0;
6558 }
6559
6560 return Template;
6561}
6562
6563QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6564 if (!StdInitializerList) {
6565 StdInitializerList = LookupStdInitializerList(*this, Loc);
6566 if (!StdInitializerList)
6567 return QualType();
6568 }
6569
6570 TemplateArgumentListInfo Args(Loc, Loc);
6571 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6572 Context.getTrivialTypeSourceInfo(Element,
6573 Loc)));
6574 return Context.getCanonicalType(
6575 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6576}
6577
Sebastian Redl98d36062012-01-17 22:50:14 +00006578bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6579 // C++ [dcl.init.list]p2:
6580 // A constructor is an initializer-list constructor if its first parameter
6581 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6582 // std::initializer_list<E> for some type E, and either there are no other
6583 // parameters or else all other parameters have default arguments.
6584 if (Ctor->getNumParams() < 1 ||
6585 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6586 return false;
6587
6588 QualType ArgType = Ctor->getParamDecl(0)->getType();
6589 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6590 ArgType = RT->getPointeeType().getUnqualifiedType();
6591
6592 return isStdInitializerList(ArgType, 0);
6593}
6594
Douglas Gregor9172aa62011-03-26 22:25:30 +00006595/// \brief Determine whether a using statement is in a context where it will be
6596/// apply in all contexts.
6597static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6598 switch (CurContext->getDeclKind()) {
6599 case Decl::TranslationUnit:
6600 return true;
6601 case Decl::LinkageSpec:
6602 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6603 default:
6604 return false;
6605 }
6606}
6607
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006608namespace {
6609
6610// Callback to only accept typo corrections that are namespaces.
6611class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6612 public:
6613 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6614 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6615 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6616 }
6617 return false;
6618 }
6619};
6620
6621}
6622
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006623static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6624 CXXScopeSpec &SS,
6625 SourceLocation IdentLoc,
6626 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006627 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006628 R.clear();
6629 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006630 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006631 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006632 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6633 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006634 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6635 bool droppedSpecifier = Corrected.WillReplaceSpecifier() &&
6636 Ident->getName().equals(CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006637 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006638 << Ident << DC << droppedSpecifier << CorrectedQuotedStr
6639 << SS.getRange() << FixItHint::CreateReplacement(
6640 Corrected.getCorrectionRange(), CorrectedStr);
6641 } else {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006642 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6643 << Ident << CorrectedQuotedStr
6644 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006645 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006646
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006647 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6648 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006649
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006650 R.addDecl(Corrected.getCorrectionDecl());
6651 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006652 }
6653 return false;
6654}
6655
John McCalld226f652010-08-21 09:40:31 +00006656Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006657 SourceLocation UsingLoc,
6658 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006659 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006660 SourceLocation IdentLoc,
6661 IdentifierInfo *NamespcName,
6662 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006663 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6664 assert(NamespcName && "Invalid NamespcName.");
6665 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006666
6667 // This can only happen along a recovery path.
6668 while (S->getFlags() & Scope::TemplateParamScope)
6669 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006670 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006671
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006672 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006673 NestedNameSpecifier *Qualifier = 0;
6674 if (SS.isSet())
6675 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6676
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006677 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006678 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6679 LookupParsedName(R, S, &SS);
6680 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006681 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006682
Douglas Gregor66992202010-06-29 17:53:46 +00006683 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006684 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006685 // Allow "using namespace std;" or "using namespace ::std;" even if
6686 // "std" hasn't been defined yet, for GCC compatibility.
6687 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6688 NamespcName->isStr("std")) {
6689 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006690 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006691 R.resolveKind();
6692 }
6693 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006694 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006695 }
6696
John McCallf36e02d2009-10-09 21:13:30 +00006697 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006698 NamedDecl *Named = R.getFoundDecl();
6699 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6700 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006701 // C++ [namespace.udir]p1:
6702 // A using-directive specifies that the names in the nominated
6703 // namespace can be used in the scope in which the
6704 // using-directive appears after the using-directive. During
6705 // unqualified name lookup (3.4.1), the names appear as if they
6706 // were declared in the nearest enclosing namespace which
6707 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006708 // namespace. [Note: in this context, "contains" means "contains
6709 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006710
6711 // Find enclosing context containing both using-directive and
6712 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006713 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006714 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6715 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6716 CommonAncestor = CommonAncestor->getParent();
6717
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006718 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006719 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006720 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006721
Douglas Gregor9172aa62011-03-26 22:25:30 +00006722 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006723 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006724 Diag(IdentLoc, diag::warn_using_directive_in_header);
6725 }
6726
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006727 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006728 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006729 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006730 }
6731
Richard Smith6b3d3e52013-02-20 19:22:51 +00006732 if (UDir)
6733 ProcessDeclAttributeList(S, UDir, AttrList);
6734
John McCalld226f652010-08-21 09:40:31 +00006735 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006736}
6737
6738void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006739 // If the scope has an associated entity and the using directive is at
6740 // namespace or translation unit scope, add the UsingDirectiveDecl into
6741 // its lookup structure so qualified name lookup can find it.
6742 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6743 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006744 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006745 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006746 // Otherwise, it is at block sope. The using-directives will affect lookup
6747 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006748 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006749}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006750
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006751
John McCalld226f652010-08-21 09:40:31 +00006752Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006753 AccessSpecifier AS,
6754 bool HasUsingKeyword,
6755 SourceLocation UsingLoc,
6756 CXXScopeSpec &SS,
6757 UnqualifiedId &Name,
6758 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006759 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00006760 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006761 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006762
Douglas Gregor12c118a2009-11-04 16:30:06 +00006763 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006764 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006765 case UnqualifiedId::IK_Identifier:
6766 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006767 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006768 case UnqualifiedId::IK_ConversionFunctionId:
6769 break;
6770
6771 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006772 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006773 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006774 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006775 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006776 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006777 diag::err_using_decl_constructor)
6778 << SS.getRange();
6779
Richard Smith80ad52f2013-01-02 11:42:31 +00006780 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006781
John McCalld226f652010-08-21 09:40:31 +00006782 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006783
6784 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006785 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006786 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006787 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006788
6789 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006790 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006791 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006792 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006793 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006794
6795 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6796 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006797 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006798 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006799
Richard Smith07b0fdc2013-03-18 21:12:30 +00006800 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006801 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00006802 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00006803 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6804 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006805 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006806 }
6807
Douglas Gregor56c04582010-12-16 00:46:58 +00006808 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6809 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6810 return 0;
6811
John McCall9488ea12009-11-17 05:59:44 +00006812 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006813 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006814 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006815 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006816 if (UD)
6817 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006818
John McCalld226f652010-08-21 09:40:31 +00006819 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006820}
6821
Douglas Gregor09acc982010-07-07 23:08:52 +00006822/// \brief Determine whether a using declaration considers the given
6823/// declarations as "equivalent", e.g., if they are redeclarations of
6824/// the same entity or are both typedefs of the same type.
6825static bool
6826IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6827 bool &SuppressRedeclaration) {
6828 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6829 SuppressRedeclaration = false;
6830 return true;
6831 }
6832
Richard Smith162e1c12011-04-15 14:24:37 +00006833 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6834 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006835 SuppressRedeclaration = true;
6836 return Context.hasSameType(TD1->getUnderlyingType(),
6837 TD2->getUnderlyingType());
6838 }
6839
6840 return false;
6841}
6842
6843
John McCall9f54ad42009-12-10 09:41:52 +00006844/// Determines whether to create a using shadow decl for a particular
6845/// decl, given the set of decls existing prior to this using lookup.
6846bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6847 const LookupResult &Previous) {
6848 // Diagnose finding a decl which is not from a base class of the
6849 // current class. We do this now because there are cases where this
6850 // function will silently decide not to build a shadow decl, which
6851 // will pre-empt further diagnostics.
6852 //
6853 // We don't need to do this in C++0x because we do the check once on
6854 // the qualifier.
6855 //
6856 // FIXME: diagnose the following if we care enough:
6857 // struct A { int foo; };
6858 // struct B : A { using A::foo; };
6859 // template <class T> struct C : A {};
6860 // template <class T> struct D : C<T> { using B::foo; } // <---
6861 // This is invalid (during instantiation) in C++03 because B::foo
6862 // resolves to the using decl in B, which is not a base class of D<T>.
6863 // We can't diagnose it immediately because C<T> is an unknown
6864 // specialization. The UsingShadowDecl in D<T> then points directly
6865 // to A::foo, which will look well-formed when we instantiate.
6866 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006867 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006868 DeclContext *OrigDC = Orig->getDeclContext();
6869
6870 // Handle enums and anonymous structs.
6871 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6872 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6873 while (OrigRec->isAnonymousStructOrUnion())
6874 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6875
6876 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6877 if (OrigDC == CurContext) {
6878 Diag(Using->getLocation(),
6879 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006880 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006881 Diag(Orig->getLocation(), diag::note_using_decl_target);
6882 return true;
6883 }
6884
Douglas Gregordc355712011-02-25 00:36:19 +00006885 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006886 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006887 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006888 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006889 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006890 Diag(Orig->getLocation(), diag::note_using_decl_target);
6891 return true;
6892 }
6893 }
6894
6895 if (Previous.empty()) return false;
6896
6897 NamedDecl *Target = Orig;
6898 if (isa<UsingShadowDecl>(Target))
6899 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6900
John McCalld7533ec2009-12-11 02:33:26 +00006901 // If the target happens to be one of the previous declarations, we
6902 // don't have a conflict.
6903 //
6904 // FIXME: but we might be increasing its access, in which case we
6905 // should redeclare it.
6906 NamedDecl *NonTag = 0, *Tag = 0;
6907 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6908 I != E; ++I) {
6909 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006910 bool Result;
6911 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6912 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006913
6914 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6915 }
6916
John McCall9f54ad42009-12-10 09:41:52 +00006917 if (Target->isFunctionOrFunctionTemplate()) {
6918 FunctionDecl *FD;
6919 if (isa<FunctionTemplateDecl>(Target))
6920 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6921 else
6922 FD = cast<FunctionDecl>(Target);
6923
6924 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006925 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006926 case Ovl_Overload:
6927 return false;
6928
6929 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006930 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006931 break;
6932
6933 // We found a decl with the exact signature.
6934 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006935 // If we're in a record, we want to hide the target, so we
6936 // return true (without a diagnostic) to tell the caller not to
6937 // build a shadow decl.
6938 if (CurContext->isRecord())
6939 return true;
6940
6941 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006942 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006943 break;
6944 }
6945
6946 Diag(Target->getLocation(), diag::note_using_decl_target);
6947 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6948 return true;
6949 }
6950
6951 // Target is not a function.
6952
John McCall9f54ad42009-12-10 09:41:52 +00006953 if (isa<TagDecl>(Target)) {
6954 // No conflict between a tag and a non-tag.
6955 if (!Tag) return false;
6956
John McCall41ce66f2009-12-10 19:51:03 +00006957 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006958 Diag(Target->getLocation(), diag::note_using_decl_target);
6959 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6960 return true;
6961 }
6962
6963 // No conflict between a tag and a non-tag.
6964 if (!NonTag) return false;
6965
John McCall41ce66f2009-12-10 19:51:03 +00006966 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006967 Diag(Target->getLocation(), diag::note_using_decl_target);
6968 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6969 return true;
6970}
6971
John McCall9488ea12009-11-17 05:59:44 +00006972/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006973UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006974 UsingDecl *UD,
6975 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006976
6977 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006978 NamedDecl *Target = Orig;
6979 if (isa<UsingShadowDecl>(Target)) {
6980 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6981 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006982 }
6983
6984 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006985 = UsingShadowDecl::Create(Context, CurContext,
6986 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006987 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006988
6989 Shadow->setAccess(UD->getAccess());
6990 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6991 Shadow->setInvalidDecl();
6992
John McCall9488ea12009-11-17 05:59:44 +00006993 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006994 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006995 else
John McCall604e7f12009-12-08 07:46:18 +00006996 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006997
John McCall604e7f12009-12-08 07:46:18 +00006998
John McCall9f54ad42009-12-10 09:41:52 +00006999 return Shadow;
7000}
John McCall604e7f12009-12-08 07:46:18 +00007001
John McCall9f54ad42009-12-10 09:41:52 +00007002/// Hides a using shadow declaration. This is required by the current
7003/// using-decl implementation when a resolvable using declaration in a
7004/// class is followed by a declaration which would hide or override
7005/// one or more of the using decl's targets; for example:
7006///
7007/// struct Base { void foo(int); };
7008/// struct Derived : Base {
7009/// using Base::foo;
7010/// void foo(int);
7011/// };
7012///
7013/// The governing language is C++03 [namespace.udecl]p12:
7014///
7015/// When a using-declaration brings names from a base class into a
7016/// derived class scope, member functions in the derived class
7017/// override and/or hide member functions with the same name and
7018/// parameter types in a base class (rather than conflicting).
7019///
7020/// There are two ways to implement this:
7021/// (1) optimistically create shadow decls when they're not hidden
7022/// by existing declarations, or
7023/// (2) don't create any shadow decls (or at least don't make them
7024/// visible) until we've fully parsed/instantiated the class.
7025/// The problem with (1) is that we might have to retroactively remove
7026/// a shadow decl, which requires several O(n) operations because the
7027/// decl structures are (very reasonably) not designed for removal.
7028/// (2) avoids this but is very fiddly and phase-dependent.
7029void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007030 if (Shadow->getDeclName().getNameKind() ==
7031 DeclarationName::CXXConversionFunctionName)
7032 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7033
John McCall9f54ad42009-12-10 09:41:52 +00007034 // Remove it from the DeclContext...
7035 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007036
John McCall9f54ad42009-12-10 09:41:52 +00007037 // ...and the scope, if applicable...
7038 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007039 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007040 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007041 }
7042
John McCall9f54ad42009-12-10 09:41:52 +00007043 // ...and the using decl.
7044 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7045
7046 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007047 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007048}
7049
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007050class UsingValidatorCCC : public CorrectionCandidateCallback {
7051public:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007052 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation)
7053 : HasTypenameKeyword(HasTypenameKeyword),
7054 IsInstantiation(IsInstantiation) {}
7055
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007056 virtual bool ValidateCandidate(const TypoCorrection &Candidate) {
7057 if (NamedDecl *ND = Candidate.getCorrectionDecl()) {
7058 if (isa<NamespaceDecl>(ND))
7059 return false;
7060 // Completely unqualified names are invalid for a 'using' declaration.
7061 bool droppedSpecifier = Candidate.WillReplaceSpecifier() &&
7062 !Candidate.getCorrectionSpecifier();
7063 if (droppedSpecifier)
7064 return false;
7065 else if (isa<TypeDecl>(ND))
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007066 return HasTypenameKeyword || !IsInstantiation;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007067 else
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007068 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007069 } else {
7070 // Keywords are not valid here.
7071 return false;
7072 }
7073 }
7074
7075private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007076 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007077 bool IsInstantiation;
7078};
7079
John McCall7ba107a2009-11-18 02:36:19 +00007080/// Builds a using declaration.
7081///
7082/// \param IsInstantiation - Whether this call arises from an
7083/// instantiation of an unresolved using declaration. We treat
7084/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007085NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7086 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007087 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007088 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007089 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007090 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007091 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007092 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007093 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007094 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007095 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007096
Anders Carlsson550b14b2009-08-28 05:49:21 +00007097 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007098
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007099 if (SS.isEmpty()) {
7100 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007101 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007102 }
Mike Stump1eb44332009-09-09 15:08:12 +00007103
John McCall9f54ad42009-12-10 09:41:52 +00007104 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007105 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007106 ForRedeclaration);
7107 Previous.setHideTags(false);
7108 if (S) {
7109 LookupName(Previous, S);
7110
7111 // It is really dumb that we have to do this.
7112 LookupResult::Filter F = Previous.makeFilter();
7113 while (F.hasNext()) {
7114 NamedDecl *D = F.next();
7115 if (!isDeclInScope(D, CurContext, S))
7116 F.erase();
7117 }
7118 F.done();
7119 } else {
7120 assert(IsInstantiation && "no scope in non-instantiation");
7121 assert(CurContext->isRecord() && "scope not record in instantiation");
7122 LookupQualifiedName(Previous, CurContext);
7123 }
7124
John McCall9f54ad42009-12-10 09:41:52 +00007125 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007126 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7127 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007128 return 0;
7129
7130 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007131 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7132 return 0;
7133
John McCallaf8e6ed2009-11-12 03:15:40 +00007134 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007135 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007136 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007137 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007138 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007139 // FIXME: not all declaration name kinds are legal here
7140 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7141 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007142 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007143 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007144 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007145 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7146 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007147 }
John McCalled976492009-12-04 22:46:56 +00007148 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007149 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007150 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007151 }
John McCalled976492009-12-04 22:46:56 +00007152 D->setAccess(AS);
7153 CurContext->addDecl(D);
7154
7155 if (!LookupContext) return D;
7156 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007157
John McCall77bb1aa2010-05-01 00:40:08 +00007158 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007159 UD->setInvalidDecl();
7160 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007161 }
7162
Richard Smithc5a89a12012-04-02 01:30:27 +00007163 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007164 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007165 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007166 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007167 return UD;
7168 }
7169
7170 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007171
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007172 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007173
John McCall604e7f12009-12-08 07:46:18 +00007174 // Unlike most lookups, we don't always want to hide tag
7175 // declarations: tag names are visible through the using declaration
7176 // even if hidden by ordinary names, *except* in a dependent context
7177 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007178 if (!IsInstantiation)
7179 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007180
John McCallb9abd8722012-04-07 03:04:20 +00007181 // For the purposes of this lookup, we have a base object type
7182 // equal to that of the current context.
7183 if (CurContext->isRecord()) {
7184 R.setBaseObjectType(
7185 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7186 }
7187
John McCalla24dc2e2009-11-17 02:14:36 +00007188 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007189
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007190 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007191 if (R.empty()) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007192 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation);
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007193 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7194 R.getLookupKind(), S, &SS, CCC)){
7195 // We reject any correction for which ND would be NULL.
7196 NamedDecl *ND = Corrected.getCorrectionDecl();
7197 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
7198 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
7199 R.setLookupName(Corrected.getCorrection());
7200 R.addDecl(ND);
7201 // We reject candidates where droppedSpecifier == true, hence the
7202 // literal '0' below.
7203 Diag(R.getNameLoc(), diag::err_no_member_suggest)
7204 << NameInfo.getName() << LookupContext << 0
7205 << CorrectedQuotedStr << SS.getRange()
7206 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
7207 CorrectedStr);
7208 Diag(ND->getLocation(), diag::note_previous_decl)
7209 << CorrectedQuotedStr;
7210 } else {
7211 Diag(IdentLoc, diag::err_no_member)
7212 << NameInfo.getName() << LookupContext << SS.getRange();
7213 UD->setInvalidDecl();
7214 return UD;
7215 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007216 }
7217
John McCalled976492009-12-04 22:46:56 +00007218 if (R.isAmbiguous()) {
7219 UD->setInvalidDecl();
7220 return UD;
7221 }
Mike Stump1eb44332009-09-09 15:08:12 +00007222
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007223 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007224 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007225 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007226 Diag(IdentLoc, diag::err_using_typename_non_type);
7227 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7228 Diag((*I)->getUnderlyingDecl()->getLocation(),
7229 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007230 UD->setInvalidDecl();
7231 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007232 }
7233 } else {
7234 // If we asked for a non-typename and we got a type, error out,
7235 // but only if this is an instantiation of an unresolved using
7236 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007237 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007238 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7239 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007240 UD->setInvalidDecl();
7241 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007242 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007243 }
7244
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007245 // C++0x N2914 [namespace.udecl]p6:
7246 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007247 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007248 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7249 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007250 UD->setInvalidDecl();
7251 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007252 }
Mike Stump1eb44332009-09-09 15:08:12 +00007253
John McCall9f54ad42009-12-10 09:41:52 +00007254 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7255 if (!CheckUsingShadowDecl(UD, *I, Previous))
7256 BuildUsingShadowDecl(S, UD, *I);
7257 }
John McCall9488ea12009-11-17 05:59:44 +00007258
7259 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007260}
7261
Sebastian Redlf677ea32011-02-05 19:23:19 +00007262/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007263bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007264 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007265
Douglas Gregordc355712011-02-25 00:36:19 +00007266 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007267 assert(SourceType &&
7268 "Using decl naming constructor doesn't have type in scope spec.");
7269 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7270
7271 // Check whether the named type is a direct base class.
7272 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7273 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7274 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7275 BaseIt != BaseE; ++BaseIt) {
7276 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7277 if (CanonicalSourceType == BaseType)
7278 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007279 if (BaseIt->getType()->isDependentType())
7280 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007281 }
7282
7283 if (BaseIt == BaseE) {
7284 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007285 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007286 diag::err_using_decl_constructor_not_in_direct_base)
7287 << UD->getNameInfo().getSourceRange()
7288 << QualType(SourceType, 0) << TargetClass;
7289 return true;
7290 }
7291
Richard Smithc5a89a12012-04-02 01:30:27 +00007292 if (!CurContext->isDependentContext())
7293 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007294
7295 return false;
7296}
7297
John McCall9f54ad42009-12-10 09:41:52 +00007298/// Checks that the given using declaration is not an invalid
7299/// redeclaration. Note that this is checking only for the using decl
7300/// itself, not for any ill-formedness among the UsingShadowDecls.
7301bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007302 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007303 const CXXScopeSpec &SS,
7304 SourceLocation NameLoc,
7305 const LookupResult &Prev) {
7306 // C++03 [namespace.udecl]p8:
7307 // C++0x [namespace.udecl]p10:
7308 // A using-declaration is a declaration and can therefore be used
7309 // repeatedly where (and only where) multiple declarations are
7310 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007311 //
John McCall8a726212010-11-29 18:01:58 +00007312 // That's in non-member contexts.
7313 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007314 return false;
7315
7316 NestedNameSpecifier *Qual
7317 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7318
7319 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7320 NamedDecl *D = *I;
7321
7322 bool DTypename;
7323 NestedNameSpecifier *DQual;
7324 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007325 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007326 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007327 } else if (UnresolvedUsingValueDecl *UD
7328 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7329 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007330 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007331 } else if (UnresolvedUsingTypenameDecl *UD
7332 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7333 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007334 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007335 } else continue;
7336
7337 // using decls differ if one says 'typename' and the other doesn't.
7338 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007339 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007340
7341 // using decls differ if they name different scopes (but note that
7342 // template instantiation can cause this check to trigger when it
7343 // didn't before instantiation).
7344 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7345 Context.getCanonicalNestedNameSpecifier(DQual))
7346 continue;
7347
7348 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007349 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007350 return true;
7351 }
7352
7353 return false;
7354}
7355
John McCall604e7f12009-12-08 07:46:18 +00007356
John McCalled976492009-12-04 22:46:56 +00007357/// Checks that the given nested-name qualifier used in a using decl
7358/// in the current context is appropriately related to the current
7359/// scope. If an error is found, diagnoses it and returns true.
7360bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7361 const CXXScopeSpec &SS,
7362 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007363 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007364
John McCall604e7f12009-12-08 07:46:18 +00007365 if (!CurContext->isRecord()) {
7366 // C++03 [namespace.udecl]p3:
7367 // C++0x [namespace.udecl]p8:
7368 // A using-declaration for a class member shall be a member-declaration.
7369
7370 // If we weren't able to compute a valid scope, it must be a
7371 // dependent class scope.
7372 if (!NamedContext || NamedContext->isRecord()) {
7373 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7374 << SS.getRange();
7375 return true;
7376 }
7377
7378 // Otherwise, everything is known to be fine.
7379 return false;
7380 }
7381
7382 // The current scope is a record.
7383
7384 // If the named context is dependent, we can't decide much.
7385 if (!NamedContext) {
7386 // FIXME: in C++0x, we can diagnose if we can prove that the
7387 // nested-name-specifier does not refer to a base class, which is
7388 // still possible in some cases.
7389
7390 // Otherwise we have to conservatively report that things might be
7391 // okay.
7392 return false;
7393 }
7394
7395 if (!NamedContext->isRecord()) {
7396 // Ideally this would point at the last name in the specifier,
7397 // but we don't have that level of source info.
7398 Diag(SS.getRange().getBegin(),
7399 diag::err_using_decl_nested_name_specifier_is_not_class)
7400 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7401 return true;
7402 }
7403
Douglas Gregor6fb07292010-12-21 07:41:49 +00007404 if (!NamedContext->isDependentContext() &&
7405 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7406 return true;
7407
Richard Smith80ad52f2013-01-02 11:42:31 +00007408 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007409 // C++0x [namespace.udecl]p3:
7410 // In a using-declaration used as a member-declaration, the
7411 // nested-name-specifier shall name a base class of the class
7412 // being defined.
7413
7414 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7415 cast<CXXRecordDecl>(NamedContext))) {
7416 if (CurContext == NamedContext) {
7417 Diag(NameLoc,
7418 diag::err_using_decl_nested_name_specifier_is_current_class)
7419 << SS.getRange();
7420 return true;
7421 }
7422
7423 Diag(SS.getRange().getBegin(),
7424 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7425 << (NestedNameSpecifier*) SS.getScopeRep()
7426 << cast<CXXRecordDecl>(CurContext)
7427 << SS.getRange();
7428 return true;
7429 }
7430
7431 return false;
7432 }
7433
7434 // C++03 [namespace.udecl]p4:
7435 // A using-declaration used as a member-declaration shall refer
7436 // to a member of a base class of the class being defined [etc.].
7437
7438 // Salient point: SS doesn't have to name a base class as long as
7439 // lookup only finds members from base classes. Therefore we can
7440 // diagnose here only if we can prove that that can't happen,
7441 // i.e. if the class hierarchies provably don't intersect.
7442
7443 // TODO: it would be nice if "definitely valid" results were cached
7444 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7445 // need to be repeated.
7446
7447 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007448 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007449
7450 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7451 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7452 Data->Bases.insert(Base);
7453 return true;
7454 }
7455
7456 bool hasDependentBases(const CXXRecordDecl *Class) {
7457 return !Class->forallBases(collect, this);
7458 }
7459
7460 /// Returns true if the base is dependent or is one of the
7461 /// accumulated base classes.
7462 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7463 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7464 return !Data->Bases.count(Base);
7465 }
7466
7467 bool mightShareBases(const CXXRecordDecl *Class) {
7468 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7469 }
7470 };
7471
7472 UserData Data;
7473
7474 // Returns false if we find a dependent base.
7475 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7476 return false;
7477
7478 // Returns false if the class has a dependent base or if it or one
7479 // of its bases is present in the base set of the current context.
7480 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7481 return false;
7482
7483 Diag(SS.getRange().getBegin(),
7484 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7485 << (NestedNameSpecifier*) SS.getScopeRep()
7486 << cast<CXXRecordDecl>(CurContext)
7487 << SS.getRange();
7488
7489 return true;
John McCalled976492009-12-04 22:46:56 +00007490}
7491
Richard Smith162e1c12011-04-15 14:24:37 +00007492Decl *Sema::ActOnAliasDeclaration(Scope *S,
7493 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007494 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007495 SourceLocation UsingLoc,
7496 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007497 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007498 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007499 // Skip up to the relevant declaration scope.
7500 while (S->getFlags() & Scope::TemplateParamScope)
7501 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007502 assert((S->getFlags() & Scope::DeclScope) &&
7503 "got alias-declaration outside of declaration scope");
7504
7505 if (Type.isInvalid())
7506 return 0;
7507
7508 bool Invalid = false;
7509 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7510 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007511 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007512
7513 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7514 return 0;
7515
7516 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007517 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007518 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007519 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7520 TInfo->getTypeLoc().getBeginLoc());
7521 }
Richard Smith162e1c12011-04-15 14:24:37 +00007522
7523 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7524 LookupName(Previous, S);
7525
7526 // Warn about shadowing the name of a template parameter.
7527 if (Previous.isSingleResult() &&
7528 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007529 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007530 Previous.clear();
7531 }
7532
7533 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7534 "name in alias declaration must be an identifier");
7535 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7536 Name.StartLocation,
7537 Name.Identifier, TInfo);
7538
7539 NewTD->setAccess(AS);
7540
7541 if (Invalid)
7542 NewTD->setInvalidDecl();
7543
Richard Smith6b3d3e52013-02-20 19:22:51 +00007544 ProcessDeclAttributeList(S, NewTD, AttrList);
7545
Richard Smith3e4c6c42011-05-05 21:57:07 +00007546 CheckTypedefForVariablyModifiedType(S, NewTD);
7547 Invalid |= NewTD->isInvalidDecl();
7548
Richard Smith162e1c12011-04-15 14:24:37 +00007549 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007550
7551 NamedDecl *NewND;
7552 if (TemplateParamLists.size()) {
7553 TypeAliasTemplateDecl *OldDecl = 0;
7554 TemplateParameterList *OldTemplateParams = 0;
7555
7556 if (TemplateParamLists.size() != 1) {
7557 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007558 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7559 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007560 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007561 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007562
7563 // Only consider previous declarations in the same scope.
7564 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7565 /*ExplicitInstantiationOrSpecialization*/false);
7566 if (!Previous.empty()) {
7567 Redeclaration = true;
7568
7569 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7570 if (!OldDecl && !Invalid) {
7571 Diag(UsingLoc, diag::err_redefinition_different_kind)
7572 << Name.Identifier;
7573
7574 NamedDecl *OldD = Previous.getRepresentativeDecl();
7575 if (OldD->getLocation().isValid())
7576 Diag(OldD->getLocation(), diag::note_previous_definition);
7577
7578 Invalid = true;
7579 }
7580
7581 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7582 if (TemplateParameterListsAreEqual(TemplateParams,
7583 OldDecl->getTemplateParameters(),
7584 /*Complain=*/true,
7585 TPL_TemplateMatch))
7586 OldTemplateParams = OldDecl->getTemplateParameters();
7587 else
7588 Invalid = true;
7589
7590 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7591 if (!Invalid &&
7592 !Context.hasSameType(OldTD->getUnderlyingType(),
7593 NewTD->getUnderlyingType())) {
7594 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7595 // but we can't reasonably accept it.
7596 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7597 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7598 if (OldTD->getLocation().isValid())
7599 Diag(OldTD->getLocation(), diag::note_previous_definition);
7600 Invalid = true;
7601 }
7602 }
7603 }
7604
7605 // Merge any previous default template arguments into our parameters,
7606 // and check the parameter list.
7607 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7608 TPC_TypeAliasTemplate))
7609 return 0;
7610
7611 TypeAliasTemplateDecl *NewDecl =
7612 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7613 Name.Identifier, TemplateParams,
7614 NewTD);
7615
7616 NewDecl->setAccess(AS);
7617
7618 if (Invalid)
7619 NewDecl->setInvalidDecl();
7620 else if (OldDecl)
7621 NewDecl->setPreviousDeclaration(OldDecl);
7622
7623 NewND = NewDecl;
7624 } else {
7625 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7626 NewND = NewTD;
7627 }
Richard Smith162e1c12011-04-15 14:24:37 +00007628
7629 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007630 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007631
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007632 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007633 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007634}
7635
John McCalld226f652010-08-21 09:40:31 +00007636Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007637 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007638 SourceLocation AliasLoc,
7639 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007640 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007641 SourceLocation IdentLoc,
7642 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007643
Anders Carlsson81c85c42009-03-28 23:53:49 +00007644 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007645 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7646 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007647
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007648 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007649 NamedDecl *PrevDecl
7650 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7651 ForRedeclaration);
7652 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7653 PrevDecl = 0;
7654
7655 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007656 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007657 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007658 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007659 // FIXME: At some point, we'll want to create the (redundant)
7660 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007661 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007662 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007663 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007664 }
Mike Stump1eb44332009-09-09 15:08:12 +00007665
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007666 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7667 diag::err_redefinition_different_kind;
7668 Diag(AliasLoc, DiagID) << Alias;
7669 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007670 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007671 }
7672
John McCalla24dc2e2009-11-17 02:14:36 +00007673 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007674 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007675
John McCallf36e02d2009-10-09 21:13:30 +00007676 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007677 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007678 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007679 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007680 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007681 }
Mike Stump1eb44332009-09-09 15:08:12 +00007682
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007683 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007684 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007685 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007686 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007687
John McCall3dbd3d52010-02-16 06:53:13 +00007688 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007689 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007690}
7691
Sean Hunt001cad92011-05-10 00:49:42 +00007692Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007693Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7694 CXXMethodDecl *MD) {
7695 CXXRecordDecl *ClassDecl = MD->getParent();
7696
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007697 // C++ [except.spec]p14:
7698 // An implicitly declared special member function (Clause 12) shall have an
7699 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007700 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007701 if (ClassDecl->isInvalidDecl())
7702 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007703
Sebastian Redl60618fa2011-03-12 11:50:43 +00007704 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007705 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7706 BEnd = ClassDecl->bases_end();
7707 B != BEnd; ++B) {
7708 if (B->isVirtual()) // Handled below.
7709 continue;
7710
Douglas Gregor18274032010-07-03 00:47:00 +00007711 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7712 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007713 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7714 // If this is a deleted function, add it anyway. This might be conformant
7715 // with the standard. This might not. I'm not sure. It might not matter.
7716 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007717 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007718 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007719 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007720
7721 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007722 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7723 BEnd = ClassDecl->vbases_end();
7724 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007725 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7726 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007727 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7728 // If this is a deleted function, add it anyway. This might be conformant
7729 // with the standard. This might not. I'm not sure. It might not matter.
7730 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007731 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007732 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007733 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007734
7735 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007736 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7737 FEnd = ClassDecl->field_end();
7738 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007739 if (F->hasInClassInitializer()) {
7740 if (Expr *E = F->getInClassInitializer())
7741 ExceptSpec.CalledExpr(E);
7742 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007743 // DR1351:
7744 // If the brace-or-equal-initializer of a non-static data member
7745 // invokes a defaulted default constructor of its class or of an
7746 // enclosing class in a potentially evaluated subexpression, the
7747 // program is ill-formed.
7748 //
7749 // This resolution is unworkable: the exception specification of the
7750 // default constructor can be needed in an unevaluated context, in
7751 // particular, in the operand of a noexcept-expression, and we can be
7752 // unable to compute an exception specification for an enclosed class.
7753 //
7754 // We do not allow an in-class initializer to require the evaluation
7755 // of the exception specification for any in-class initializer whose
7756 // definition is not lexically complete.
7757 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007758 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007759 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007760 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7761 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7762 // If this is a deleted function, add it anyway. This might be conformant
7763 // with the standard. This might not. I'm not sure. It might not matter.
7764 // In particular, the problem is that this function never gets called. It
7765 // might just be ill-formed because this function attempts to refer to
7766 // a deleted function here.
7767 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007768 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007769 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007770 }
John McCalle23cf432010-12-14 08:05:40 +00007771
Sean Hunt001cad92011-05-10 00:49:42 +00007772 return ExceptSpec;
7773}
7774
Richard Smith07b0fdc2013-03-18 21:12:30 +00007775Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007776Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7777 CXXRecordDecl *ClassDecl = CD->getParent();
7778
7779 // C++ [except.spec]p14:
7780 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007781 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007782 if (ClassDecl->isInvalidDecl())
7783 return ExceptSpec;
7784
7785 // Inherited constructor.
7786 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7787 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7788 // FIXME: Copying or moving the parameters could add extra exceptions to the
7789 // set, as could the default arguments for the inherited constructor. This
7790 // will be addressed when we implement the resolution of core issue 1351.
7791 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7792
7793 // Direct base-class constructors.
7794 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7795 BEnd = ClassDecl->bases_end();
7796 B != BEnd; ++B) {
7797 if (B->isVirtual()) // Handled below.
7798 continue;
7799
7800 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7801 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7802 if (BaseClassDecl == InheritedDecl)
7803 continue;
7804 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7805 if (Constructor)
7806 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7807 }
7808 }
7809
7810 // Virtual base-class constructors.
7811 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7812 BEnd = ClassDecl->vbases_end();
7813 B != BEnd; ++B) {
7814 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7815 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7816 if (BaseClassDecl == InheritedDecl)
7817 continue;
7818 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7819 if (Constructor)
7820 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7821 }
7822 }
7823
7824 // Field constructors.
7825 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7826 FEnd = ClassDecl->field_end();
7827 F != FEnd; ++F) {
7828 if (F->hasInClassInitializer()) {
7829 if (Expr *E = F->getInClassInitializer())
7830 ExceptSpec.CalledExpr(E);
7831 else if (!F->isInvalidDecl())
7832 Diag(CD->getLocation(),
7833 diag::err_in_class_initializer_references_def_ctor) << CD;
7834 } else if (const RecordType *RecordTy
7835 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7836 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7837 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7838 if (Constructor)
7839 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7840 }
7841 }
7842
Richard Smith07b0fdc2013-03-18 21:12:30 +00007843 return ExceptSpec;
7844}
7845
Richard Smithafb49182012-11-29 01:34:07 +00007846namespace {
7847/// RAII object to register a special member as being currently declared.
7848struct DeclaringSpecialMember {
7849 Sema &S;
7850 Sema::SpecialMemberDecl D;
7851 bool WasAlreadyBeingDeclared;
7852
7853 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7854 : S(S), D(RD, CSM) {
7855 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7856 if (WasAlreadyBeingDeclared)
7857 // This almost never happens, but if it does, ensure that our cache
7858 // doesn't contain a stale result.
7859 S.SpecialMemberCache.clear();
7860
7861 // FIXME: Register a note to be produced if we encounter an error while
7862 // declaring the special member.
7863 }
7864 ~DeclaringSpecialMember() {
7865 if (!WasAlreadyBeingDeclared)
7866 S.SpecialMembersBeingDeclared.erase(D);
7867 }
7868
7869 /// \brief Are we already trying to declare this special member?
7870 bool isAlreadyBeingDeclared() const {
7871 return WasAlreadyBeingDeclared;
7872 }
7873};
7874}
7875
Sean Hunt001cad92011-05-10 00:49:42 +00007876CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7877 CXXRecordDecl *ClassDecl) {
7878 // C++ [class.ctor]p5:
7879 // A default constructor for a class X is a constructor of class X
7880 // that can be called without an argument. If there is no
7881 // user-declared constructor for class X, a default constructor is
7882 // implicitly declared. An implicitly-declared default constructor
7883 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007884 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007885 "Should not build implicit default constructor!");
7886
Richard Smithafb49182012-11-29 01:34:07 +00007887 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7888 if (DSM.isAlreadyBeingDeclared())
7889 return 0;
7890
Richard Smith7756afa2012-06-10 05:43:50 +00007891 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7892 CXXDefaultConstructor,
7893 false);
7894
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007895 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007896 CanQualType ClassType
7897 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007898 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007899 DeclarationName Name
7900 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007901 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007902 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007903 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007904 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007905 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007906 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007907 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007908 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007909
7910 // Build an exception specification pointing back at this constructor.
7911 FunctionProtoType::ExtProtoInfo EPI;
7912 EPI.ExceptionSpecType = EST_Unevaluated;
7913 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007914 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007915
Richard Smithbc2a35d2012-12-08 08:32:28 +00007916 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7917 // constructors is easy to compute.
7918 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7919
7920 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007921 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007922
Douglas Gregor18274032010-07-03 00:47:00 +00007923 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007924 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007925
Douglas Gregor23c94db2010-07-02 17:43:08 +00007926 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007927 PushOnScopeChains(DefaultCon, S, false);
7928 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007929
Douglas Gregor32df23e2010-07-01 22:02:46 +00007930 return DefaultCon;
7931}
7932
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007933void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7934 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007935 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007936 !Constructor->doesThisDeclarationHaveABody() &&
7937 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007938 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007939
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007940 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007941 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007942
Eli Friedman9a14db32012-10-18 20:14:08 +00007943 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007944 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007945 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007946 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007947 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007948 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007949 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007950 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007951 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007952
7953 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007954 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007955
7956 Constructor->setUsed();
7957 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007958
7959 if (ASTMutationListener *L = getASTMutationListener()) {
7960 L->CompletedImplicitDefinition(Constructor);
7961 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007962}
7963
Richard Smith7a614d82011-06-11 17:19:42 +00007964void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007965 // Check that any explicitly-defaulted methods have exception specifications
7966 // compatible with their implicit exception specifications.
7967 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007968}
7969
Richard Smith4841ca52013-04-10 05:48:59 +00007970namespace {
7971/// Information on inheriting constructors to declare.
7972class InheritingConstructorInfo {
7973public:
7974 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7975 : SemaRef(SemaRef), Derived(Derived) {
7976 // Mark the constructors that we already have in the derived class.
7977 //
7978 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7979 // unless there is a user-declared constructor with the same signature in
7980 // the class where the using-declaration appears.
7981 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7982 }
7983
7984 void inheritAll(CXXRecordDecl *RD) {
7985 visitAll(RD, &InheritingConstructorInfo::inherit);
7986 }
7987
7988private:
7989 /// Information about an inheriting constructor.
7990 struct InheritingConstructor {
7991 InheritingConstructor()
7992 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7993
7994 /// If \c true, a constructor with this signature is already declared
7995 /// in the derived class.
7996 bool DeclaredInDerived;
7997
7998 /// The constructor which is inherited.
7999 const CXXConstructorDecl *BaseCtor;
8000
8001 /// The derived constructor we declared.
8002 CXXConstructorDecl *DerivedCtor;
8003 };
8004
8005 /// Inheriting constructors with a given canonical type. There can be at
8006 /// most one such non-template constructor, and any number of templated
8007 /// constructors.
8008 struct InheritingConstructorsForType {
8009 InheritingConstructor NonTemplate;
8010 llvm::SmallVector<
8011 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
8012
8013 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8014 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8015 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8016 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8017 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8018 false, S.TPL_TemplateMatch))
8019 return Templates[I].second;
8020 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8021 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008022 }
Richard Smith4841ca52013-04-10 05:48:59 +00008023
8024 return NonTemplate;
8025 }
8026 };
8027
8028 /// Get or create the inheriting constructor record for a constructor.
8029 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8030 QualType CtorType) {
8031 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8032 .getEntry(SemaRef, Ctor);
8033 }
8034
8035 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8036
8037 /// Process all constructors for a class.
8038 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8039 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8040 CtorE = RD->ctor_end();
8041 CtorIt != CtorE; ++CtorIt)
8042 (this->*Callback)(*CtorIt);
8043 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8044 I(RD->decls_begin()), E(RD->decls_end());
8045 I != E; ++I) {
8046 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8047 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8048 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008049 }
8050 }
Richard Smith4841ca52013-04-10 05:48:59 +00008051
8052 /// Note that a constructor (or constructor template) was declared in Derived.
8053 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8054 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8055 }
8056
8057 /// Inherit a single constructor.
8058 void inherit(const CXXConstructorDecl *Ctor) {
8059 const FunctionProtoType *CtorType =
8060 Ctor->getType()->castAs<FunctionProtoType>();
8061 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8062 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8063
8064 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8065
8066 // Core issue (no number yet): the ellipsis is always discarded.
8067 if (EPI.Variadic) {
8068 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8069 SemaRef.Diag(Ctor->getLocation(),
8070 diag::note_using_decl_constructor_ellipsis);
8071 EPI.Variadic = false;
8072 }
8073
8074 // Declare a constructor for each number of parameters.
8075 //
8076 // C++11 [class.inhctor]p1:
8077 // The candidate set of inherited constructors from the class X named in
8078 // the using-declaration consists of [... modulo defects ...] for each
8079 // constructor or constructor template of X, the set of constructors or
8080 // constructor templates that results from omitting any ellipsis parameter
8081 // specification and successively omitting parameters with a default
8082 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008083 unsigned MinParams = minParamsToInherit(Ctor);
8084 unsigned Params = Ctor->getNumParams();
8085 if (Params >= MinParams) {
8086 do
8087 declareCtor(UsingLoc, Ctor,
8088 SemaRef.Context.getFunctionType(
8089 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8090 while (Params > MinParams &&
8091 Ctor->getParamDecl(--Params)->hasDefaultArg());
8092 }
Richard Smith4841ca52013-04-10 05:48:59 +00008093 }
8094
8095 /// Find the using-declaration which specified that we should inherit the
8096 /// constructors of \p Base.
8097 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8098 // No fancy lookup required; just look for the base constructor name
8099 // directly within the derived class.
8100 ASTContext &Context = SemaRef.Context;
8101 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8102 Context.getCanonicalType(Context.getRecordType(Base)));
8103 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8104 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8105 }
8106
8107 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8108 // C++11 [class.inhctor]p3:
8109 // [F]or each constructor template in the candidate set of inherited
8110 // constructors, a constructor template is implicitly declared
8111 if (Ctor->getDescribedFunctionTemplate())
8112 return 0;
8113
8114 // For each non-template constructor in the candidate set of inherited
8115 // constructors other than a constructor having no parameters or a
8116 // copy/move constructor having a single parameter, a constructor is
8117 // implicitly declared [...]
8118 if (Ctor->getNumParams() == 0)
8119 return 1;
8120 if (Ctor->isCopyOrMoveConstructor())
8121 return 2;
8122
8123 // Per discussion on core reflector, never inherit a constructor which
8124 // would become a default, copy, or move constructor of Derived either.
8125 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8126 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8127 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8128 }
8129
8130 /// Declare a single inheriting constructor, inheriting the specified
8131 /// constructor, with the given type.
8132 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8133 QualType DerivedType) {
8134 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8135
8136 // C++11 [class.inhctor]p3:
8137 // ... a constructor is implicitly declared with the same constructor
8138 // characteristics unless there is a user-declared constructor with
8139 // the same signature in the class where the using-declaration appears
8140 if (Entry.DeclaredInDerived)
8141 return;
8142
8143 // C++11 [class.inhctor]p7:
8144 // If two using-declarations declare inheriting constructors with the
8145 // same signature, the program is ill-formed
8146 if (Entry.DerivedCtor) {
8147 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8148 // Only diagnose this once per constructor.
8149 if (Entry.DerivedCtor->isInvalidDecl())
8150 return;
8151 Entry.DerivedCtor->setInvalidDecl();
8152
8153 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8154 SemaRef.Diag(BaseCtor->getLocation(),
8155 diag::note_using_decl_constructor_conflict_current_ctor);
8156 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8157 diag::note_using_decl_constructor_conflict_previous_ctor);
8158 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8159 diag::note_using_decl_constructor_conflict_previous_using);
8160 } else {
8161 // Core issue (no number): if the same inheriting constructor is
8162 // produced by multiple base class constructors from the same base
8163 // class, the inheriting constructor is defined as deleted.
8164 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8165 }
8166
8167 return;
8168 }
8169
8170 ASTContext &Context = SemaRef.Context;
8171 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8172 Context.getCanonicalType(Context.getRecordType(Derived)));
8173 DeclarationNameInfo NameInfo(Name, UsingLoc);
8174
8175 TemplateParameterList *TemplateParams = 0;
8176 if (const FunctionTemplateDecl *FTD =
8177 BaseCtor->getDescribedFunctionTemplate()) {
8178 TemplateParams = FTD->getTemplateParameters();
8179 // We're reusing template parameters from a different DeclContext. This
8180 // is questionable at best, but works out because the template depth in
8181 // both places is guaranteed to be 0.
8182 // FIXME: Rebuild the template parameters in the new context, and
8183 // transform the function type to refer to them.
8184 }
8185
8186 // Build type source info pointing at the using-declaration. This is
8187 // required by template instantiation.
8188 TypeSourceInfo *TInfo =
8189 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8190 FunctionProtoTypeLoc ProtoLoc =
8191 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8192
8193 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8194 Context, Derived, UsingLoc, NameInfo, DerivedType,
8195 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8196 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8197
8198 // Build an unevaluated exception specification for this constructor.
8199 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8200 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8201 EPI.ExceptionSpecType = EST_Unevaluated;
8202 EPI.ExceptionSpecDecl = DerivedCtor;
8203 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8204 FPT->getArgTypes(), EPI));
8205
8206 // Build the parameter declarations.
8207 SmallVector<ParmVarDecl *, 16> ParamDecls;
8208 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8209 TypeSourceInfo *TInfo =
8210 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8211 ParmVarDecl *PD = ParmVarDecl::Create(
8212 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8213 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8214 PD->setScopeInfo(0, I);
8215 PD->setImplicit();
8216 ParamDecls.push_back(PD);
8217 ProtoLoc.setArg(I, PD);
8218 }
8219
8220 // Set up the new constructor.
8221 DerivedCtor->setAccess(BaseCtor->getAccess());
8222 DerivedCtor->setParams(ParamDecls);
8223 DerivedCtor->setInheritedConstructor(BaseCtor);
8224 if (BaseCtor->isDeleted())
8225 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8226
8227 // If this is a constructor template, build the template declaration.
8228 if (TemplateParams) {
8229 FunctionTemplateDecl *DerivedTemplate =
8230 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8231 TemplateParams, DerivedCtor);
8232 DerivedTemplate->setAccess(BaseCtor->getAccess());
8233 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8234 Derived->addDecl(DerivedTemplate);
8235 } else {
8236 Derived->addDecl(DerivedCtor);
8237 }
8238
8239 Entry.BaseCtor = BaseCtor;
8240 Entry.DerivedCtor = DerivedCtor;
8241 }
8242
8243 Sema &SemaRef;
8244 CXXRecordDecl *Derived;
8245 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8246 MapType Map;
8247};
8248}
8249
8250void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8251 // Defer declaring the inheriting constructors until the class is
8252 // instantiated.
8253 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008254 return;
8255
Richard Smith4841ca52013-04-10 05:48:59 +00008256 // Find base classes from which we might inherit constructors.
8257 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8258 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8259 BaseE = ClassDecl->bases_end();
8260 BaseIt != BaseE; ++BaseIt)
8261 if (BaseIt->getInheritConstructors())
8262 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008263
Richard Smith4841ca52013-04-10 05:48:59 +00008264 // Go no further if we're not inheriting any constructors.
8265 if (InheritedBases.empty())
8266 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008267
Richard Smith4841ca52013-04-10 05:48:59 +00008268 // Declare the inherited constructors.
8269 InheritingConstructorInfo ICI(*this, ClassDecl);
8270 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8271 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008272}
8273
Richard Smith07b0fdc2013-03-18 21:12:30 +00008274void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8275 CXXConstructorDecl *Constructor) {
8276 CXXRecordDecl *ClassDecl = Constructor->getParent();
8277 assert(Constructor->getInheritedConstructor() &&
8278 !Constructor->doesThisDeclarationHaveABody() &&
8279 !Constructor->isDeleted());
8280
8281 SynthesizedFunctionScope Scope(*this, Constructor);
8282 DiagnosticErrorTrap Trap(Diags);
8283 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8284 Trap.hasErrorOccurred()) {
8285 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8286 << Context.getTagDeclType(ClassDecl);
8287 Constructor->setInvalidDecl();
8288 return;
8289 }
8290
8291 SourceLocation Loc = Constructor->getLocation();
8292 Constructor->setBody(new (Context) CompoundStmt(Loc));
8293
8294 Constructor->setUsed();
8295 MarkVTableUsed(CurrentLocation, ClassDecl);
8296
8297 if (ASTMutationListener *L = getASTMutationListener()) {
8298 L->CompletedImplicitDefinition(Constructor);
8299 }
8300}
8301
8302
Sean Huntcb45a0f2011-05-12 22:46:25 +00008303Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008304Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8305 CXXRecordDecl *ClassDecl = MD->getParent();
8306
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008307 // C++ [except.spec]p14:
8308 // An implicitly declared special member function (Clause 12) shall have
8309 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008310 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008311 if (ClassDecl->isInvalidDecl())
8312 return ExceptSpec;
8313
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008314 // Direct base-class destructors.
8315 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8316 BEnd = ClassDecl->bases_end();
8317 B != BEnd; ++B) {
8318 if (B->isVirtual()) // Handled below.
8319 continue;
8320
8321 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008322 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008323 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008324 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008325
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008326 // Virtual base-class destructors.
8327 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8328 BEnd = ClassDecl->vbases_end();
8329 B != BEnd; ++B) {
8330 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008331 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008332 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008333 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008334
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008335 // Field destructors.
8336 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8337 FEnd = ClassDecl->field_end();
8338 F != FEnd; ++F) {
8339 if (const RecordType *RecordTy
8340 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008341 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008342 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008343 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008344
Sean Huntcb45a0f2011-05-12 22:46:25 +00008345 return ExceptSpec;
8346}
8347
8348CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8349 // C++ [class.dtor]p2:
8350 // If a class has no user-declared destructor, a destructor is
8351 // declared implicitly. An implicitly-declared destructor is an
8352 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008353 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008354
Richard Smithafb49182012-11-29 01:34:07 +00008355 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8356 if (DSM.isAlreadyBeingDeclared())
8357 return 0;
8358
Douglas Gregor4923aa22010-07-02 20:37:36 +00008359 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008360 CanQualType ClassType
8361 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008362 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008363 DeclarationName Name
8364 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008365 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008366 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008367 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8368 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008369 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008370 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008371 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008372 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008373
8374 // Build an exception specification pointing back at this destructor.
8375 FunctionProtoType::ExtProtoInfo EPI;
8376 EPI.ExceptionSpecType = EST_Unevaluated;
8377 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008378 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008379
Richard Smithbc2a35d2012-12-08 08:32:28 +00008380 AddOverriddenMethods(ClassDecl, Destructor);
8381
8382 // We don't need to use SpecialMemberIsTrivial here; triviality for
8383 // destructors is easy to compute.
8384 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8385
8386 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008387 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008388
Douglas Gregor4923aa22010-07-02 20:37:36 +00008389 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008390 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008391
Douglas Gregor4923aa22010-07-02 20:37:36 +00008392 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008393 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008394 PushOnScopeChains(Destructor, S, false);
8395 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008396
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008397 return Destructor;
8398}
8399
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008400void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008401 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008402 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008403 !Destructor->doesThisDeclarationHaveABody() &&
8404 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008405 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008406 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008407 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008408
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008409 if (Destructor->isInvalidDecl())
8410 return;
8411
Eli Friedman9a14db32012-10-18 20:14:08 +00008412 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008413
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008414 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008415 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8416 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008417
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008418 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008419 Diag(CurrentLocation, diag::note_member_synthesized_at)
8420 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8421
8422 Destructor->setInvalidDecl();
8423 return;
8424 }
8425
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008426 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008427 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008428 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008429 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008430 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008431
8432 if (ASTMutationListener *L = getASTMutationListener()) {
8433 L->CompletedImplicitDefinition(Destructor);
8434 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008435}
8436
Richard Smitha4156b82012-04-21 18:42:51 +00008437/// \brief Perform any semantic analysis which needs to be delayed until all
8438/// pending class member declarations have been parsed.
8439void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008440 // If the context is an invalid C++ class, just suppress these checks.
8441 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8442 if (Record->isInvalidDecl()) {
8443 DelayedDestructorExceptionSpecChecks.clear();
8444 return;
8445 }
8446 }
8447
Richard Smitha4156b82012-04-21 18:42:51 +00008448 // Perform any deferred checking of exception specifications for virtual
8449 // destructors.
8450 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8451 i != e; ++i) {
8452 const CXXDestructorDecl *Dtor =
8453 DelayedDestructorExceptionSpecChecks[i].first;
8454 assert(!Dtor->getParent()->isDependentType() &&
8455 "Should not ever add destructors of templates into the list.");
8456 CheckOverridingFunctionExceptionSpec(Dtor,
8457 DelayedDestructorExceptionSpecChecks[i].second);
8458 }
8459 DelayedDestructorExceptionSpecChecks.clear();
8460}
8461
Richard Smithb9d0b762012-07-27 04:22:15 +00008462void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8463 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008464 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008465 "adjusting dtor exception specs was introduced in c++11");
8466
Sebastian Redl0ee33912011-05-19 05:13:44 +00008467 // C++11 [class.dtor]p3:
8468 // A declaration of a destructor that does not have an exception-
8469 // specification is implicitly considered to have the same exception-
8470 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008471 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008472 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008473 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008474 return;
8475
Chandler Carruth3f224b22011-09-20 04:55:26 +00008476 // Replace the destructor's type, building off the existing one. Fortunately,
8477 // the only thing of interest in the destructor type is its extended info.
8478 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008479 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8480 EPI.ExceptionSpecType = EST_Unevaluated;
8481 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008482 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008483
Sebastian Redl0ee33912011-05-19 05:13:44 +00008484 // FIXME: If the destructor has a body that could throw, and the newly created
8485 // spec doesn't allow exceptions, we should emit a warning, because this
8486 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008487 // However, we don't have a body or an exception specification yet, so it
8488 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008489}
8490
Richard Smith8c889532012-11-14 00:50:40 +00008491/// When generating a defaulted copy or move assignment operator, if a field
8492/// should be copied with __builtin_memcpy rather than via explicit assignments,
8493/// do so. This optimization only applies for arrays of scalars, and for arrays
8494/// of class type where the selected copy/move-assignment operator is trivial.
8495static StmtResult
8496buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8497 Expr *To, Expr *From) {
8498 // Compute the size of the memory buffer to be copied.
8499 QualType SizeType = S.Context.getSizeType();
8500 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8501 S.Context.getTypeSizeInChars(T).getQuantity());
8502
8503 // Take the address of the field references for "from" and "to". We
8504 // directly construct UnaryOperators here because semantic analysis
8505 // does not permit us to take the address of an xvalue.
8506 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8507 S.Context.getPointerType(From->getType()),
8508 VK_RValue, OK_Ordinary, Loc);
8509 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8510 S.Context.getPointerType(To->getType()),
8511 VK_RValue, OK_Ordinary, Loc);
8512
8513 const Type *E = T->getBaseElementTypeUnsafe();
8514 bool NeedsCollectableMemCpy =
8515 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8516
8517 // Create a reference to the __builtin_objc_memmove_collectable function
8518 StringRef MemCpyName = NeedsCollectableMemCpy ?
8519 "__builtin_objc_memmove_collectable" :
8520 "__builtin_memcpy";
8521 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8522 Sema::LookupOrdinaryName);
8523 S.LookupName(R, S.TUScope, true);
8524
8525 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8526 if (!MemCpy)
8527 // Something went horribly wrong earlier, and we will have complained
8528 // about it.
8529 return StmtError();
8530
8531 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8532 VK_RValue, Loc, 0);
8533 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8534
8535 Expr *CallArgs[] = {
8536 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8537 };
8538 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8539 Loc, CallArgs, Loc);
8540
8541 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8542 return S.Owned(Call.takeAs<Stmt>());
8543}
8544
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008545/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008546/// \c To.
8547///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008548/// This routine is used to copy/move the members of a class with an
8549/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008550/// copied are arrays, this routine builds for loops to copy them.
8551///
8552/// \param S The Sema object used for type-checking.
8553///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008554/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008555///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008556/// \param T The type of the expressions being copied/moved. Both expressions
8557/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008558///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008559/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008560///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008561/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008562///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008563/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008564/// Otherwise, it's a non-static member subobject.
8565///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008566/// \param Copying Whether we're copying or moving.
8567///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008568/// \param Depth Internal parameter recording the depth of the recursion.
8569///
Richard Smith8c889532012-11-14 00:50:40 +00008570/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8571/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008572static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008573buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8574 Expr *To, Expr *From,
8575 bool CopyingBaseSubobject, bool Copying,
8576 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008577 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008578 // Each subobject is assigned in the manner appropriate to its type:
8579 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008580 // - if the subobject is of class type, as if by a call to operator= with
8581 // the subobject as the object expression and the corresponding
8582 // subobject of x as a single function argument (as if by explicit
8583 // qualification; that is, ignoring any possible virtual overriding
8584 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008585 //
8586 // C++03 [class.copy]p13:
8587 // - if the subobject is of class type, the copy assignment operator for
8588 // the class is used (as if by explicit qualification; that is,
8589 // ignoring any possible virtual overriding functions in more derived
8590 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008591 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8592 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008593
Douglas Gregor06a9f362010-05-01 20:49:11 +00008594 // Look for operator=.
8595 DeclarationName Name
8596 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8597 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8598 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008599
Richard Smith044c8aa2012-11-13 00:54:12 +00008600 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8601 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008602 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008603 LookupResult::Filter F = OpLookup.makeFilter();
8604 while (F.hasNext()) {
8605 NamedDecl *D = F.next();
8606 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8607 if (Method->isCopyAssignmentOperator() ||
8608 (!Copying && Method->isMoveAssignmentOperator()))
8609 continue;
8610
8611 F.erase();
8612 }
8613 F.done();
John McCallb0207482010-03-16 06:11:48 +00008614 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008615
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008616 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008617 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008618 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008619 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008620 // ambiguities), we need to cast "this" to that subobject type; to
8621 // ensure that we don't go through the virtual call mechanism, we need
8622 // to qualify the operator= name with the base class (see below). However,
8623 // this means that if the base class has a protected copy assignment
8624 // operator, the protected member access check will fail. So, we
8625 // rewrite "protected" access to "public" access in this case, since we
8626 // know by construction that we're calling from a derived class.
8627 if (CopyingBaseSubobject) {
8628 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8629 L != LEnd; ++L) {
8630 if (L.getAccess() == AS_protected)
8631 L.setAccess(AS_public);
8632 }
8633 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008634
Douglas Gregor06a9f362010-05-01 20:49:11 +00008635 // Create the nested-name-specifier that will be used to qualify the
8636 // reference to operator=; this is required to suppress the virtual
8637 // call mechanism.
8638 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008639 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008640 SS.MakeTrivial(S.Context,
8641 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008642 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008643 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008644
Douglas Gregor06a9f362010-05-01 20:49:11 +00008645 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008646 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008647 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008648 /*TemplateKWLoc=*/SourceLocation(),
8649 /*FirstQualifierInScope=*/0,
8650 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008651 /*TemplateArgs=*/0,
8652 /*SuppressQualifierCheck=*/true);
8653 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008654 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008655
Douglas Gregor06a9f362010-05-01 20:49:11 +00008656 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008657
Richard Smith044c8aa2012-11-13 00:54:12 +00008658 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008659 OpEqualRef.takeAs<Expr>(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00008660 Loc, From, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008661 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008662 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008663
Richard Smith8c889532012-11-14 00:50:40 +00008664 // If we built a call to a trivial 'operator=' while copying an array,
8665 // bail out. We'll replace the whole shebang with a memcpy.
8666 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8667 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8668 return StmtResult((Stmt*)0);
8669
Richard Smith044c8aa2012-11-13 00:54:12 +00008670 // Convert to an expression-statement, and clean up any produced
8671 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008672 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008673 }
John McCallb0207482010-03-16 06:11:48 +00008674
Richard Smith044c8aa2012-11-13 00:54:12 +00008675 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008676 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008677 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008678 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008679 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008680 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008681 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008682 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008683 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008684
8685 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008686 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008687
Douglas Gregor06a9f362010-05-01 20:49:11 +00008688 // Construct a loop over the array bounds, e.g.,
8689 //
8690 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8691 //
8692 // that will copy each of the array elements.
8693 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008694
Douglas Gregor06a9f362010-05-01 20:49:11 +00008695 // Create the iteration variable.
8696 IdentifierInfo *IterationVarName = 0;
8697 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008698 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008699 llvm::raw_svector_ostream OS(Str);
8700 OS << "__i" << Depth;
8701 IterationVarName = &S.Context.Idents.get(OS.str());
8702 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008703 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008704 IterationVarName, SizeType,
8705 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008706 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008707
Douglas Gregor06a9f362010-05-01 20:49:11 +00008708 // Initialize the iteration variable to zero.
8709 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008710 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008711
8712 // Create a reference to the iteration variable; we'll use this several
8713 // times throughout.
8714 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008715 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008716 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008717 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8718 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8719
Douglas Gregor06a9f362010-05-01 20:49:11 +00008720 // Create the DeclStmt that holds the iteration variable.
8721 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008722
Douglas Gregor06a9f362010-05-01 20:49:11 +00008723 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008724 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008725 IterationVarRefRVal,
8726 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008727 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008728 IterationVarRefRVal,
8729 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008730 if (!Copying) // Cast to rvalue
8731 From = CastForMoving(S, From);
8732
8733 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008734 StmtResult Copy =
8735 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8736 To, From, CopyingBaseSubobject,
8737 Copying, Depth + 1);
8738 // Bail out if copying fails or if we determined that we should use memcpy.
8739 if (Copy.isInvalid() || !Copy.get())
8740 return Copy;
8741
8742 // Create the comparison against the array bound.
8743 llvm::APInt Upper
8744 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8745 Expr *Comparison
8746 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8747 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8748 BO_NE, S.Context.BoolTy,
8749 VK_RValue, OK_Ordinary, Loc, false);
8750
8751 // Create the pre-increment of the iteration variable.
8752 Expr *Increment
8753 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8754 VK_LValue, OK_Ordinary, Loc);
8755
Douglas Gregor06a9f362010-05-01 20:49:11 +00008756 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008757 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008758 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008759 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008760 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008761}
8762
Richard Smith8c889532012-11-14 00:50:40 +00008763static StmtResult
8764buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8765 Expr *To, Expr *From,
8766 bool CopyingBaseSubobject, bool Copying) {
8767 // Maybe we should use a memcpy?
8768 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8769 T.isTriviallyCopyableType(S.Context))
8770 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8771
8772 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8773 CopyingBaseSubobject,
8774 Copying, 0));
8775
8776 // If we ended up picking a trivial assignment operator for an array of a
8777 // non-trivially-copyable class type, just emit a memcpy.
8778 if (!Result.isInvalid() && !Result.get())
8779 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8780
8781 return Result;
8782}
8783
Richard Smithb9d0b762012-07-27 04:22:15 +00008784Sema::ImplicitExceptionSpecification
8785Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8786 CXXRecordDecl *ClassDecl = MD->getParent();
8787
8788 ImplicitExceptionSpecification ExceptSpec(*this);
8789 if (ClassDecl->isInvalidDecl())
8790 return ExceptSpec;
8791
8792 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8793 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8794 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8795
Douglas Gregorb87786f2010-07-01 17:48:08 +00008796 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008797 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008798 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008799
8800 // It is unspecified whether or not an implicit copy assignment operator
8801 // attempts to deduplicate calls to assignment operators of virtual bases are
8802 // made. As such, this exception specification is effectively unspecified.
8803 // Based on a similar decision made for constness in C++0x, we're erring on
8804 // the side of assuming such calls to be made regardless of whether they
8805 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008806 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8807 BaseEnd = ClassDecl->bases_end();
8808 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008809 if (Base->isVirtual())
8810 continue;
8811
Douglas Gregora376d102010-07-02 21:50:04 +00008812 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008813 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008814 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8815 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008816 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008817 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008818
8819 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8820 BaseEnd = ClassDecl->vbases_end();
8821 Base != BaseEnd; ++Base) {
8822 CXXRecordDecl *BaseClassDecl
8823 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8824 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8825 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008826 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008827 }
8828
Douglas Gregorb87786f2010-07-01 17:48:08 +00008829 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8830 FieldEnd = ClassDecl->field_end();
8831 Field != FieldEnd;
8832 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008833 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008834 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8835 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008836 LookupCopyingAssignment(FieldClassDecl,
8837 ArgQuals | FieldType.getCVRQualifiers(),
8838 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008839 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008840 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008841 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008842
Richard Smithb9d0b762012-07-27 04:22:15 +00008843 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008844}
8845
8846CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8847 // Note: The following rules are largely analoguous to the copy
8848 // constructor rules. Note that virtual bases are not taken into account
8849 // for determining the argument type of the operator. Note also that
8850 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008851 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008852
Richard Smithafb49182012-11-29 01:34:07 +00008853 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8854 if (DSM.isAlreadyBeingDeclared())
8855 return 0;
8856
Sean Hunt30de05c2011-05-14 05:23:20 +00008857 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8858 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008859 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8860 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008861 ArgType = ArgType.withConst();
8862 ArgType = Context.getLValueReferenceType(ArgType);
8863
Richard Smitha8942d72013-05-07 03:19:20 +00008864 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8865 CXXCopyAssignment,
8866 Const);
8867
Douglas Gregord3c35902010-07-01 16:36:15 +00008868 // An implicitly-declared copy assignment operator is an inline public
8869 // member of its class.
8870 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008871 SourceLocation ClassLoc = ClassDecl->getLocation();
8872 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00008873 CXXMethodDecl *CopyAssignment =
8874 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8875 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8876 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008877 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008878 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008879 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008880
8881 // Build an exception specification pointing back at this member.
8882 FunctionProtoType::ExtProtoInfo EPI;
8883 EPI.ExceptionSpecType = EST_Unevaluated;
8884 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008885 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008886
Douglas Gregord3c35902010-07-01 16:36:15 +00008887 // Add the parameter to the operator.
8888 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008889 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008890 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008891 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008892 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008893
Richard Smithbc2a35d2012-12-08 08:32:28 +00008894 AddOverriddenMethods(ClassDecl, CopyAssignment);
8895
8896 CopyAssignment->setTrivial(
8897 ClassDecl->needsOverloadResolutionForCopyAssignment()
8898 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8899 : ClassDecl->hasTrivialCopyAssignment());
8900
Richard Smitha8942d72013-05-07 03:19:20 +00008901 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00008902 // .... If the class definition does not explicitly declare a copy
8903 // assignment operator, there is no user-declared move constructor, and
8904 // there is no user-declared move assignment operator, a copy assignment
8905 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008906 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008907 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008908
Richard Smithbc2a35d2012-12-08 08:32:28 +00008909 // Note that we have added this copy-assignment operator.
8910 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8911
8912 if (Scope *S = getScopeForContext(ClassDecl))
8913 PushOnScopeChains(CopyAssignment, S, false);
8914 ClassDecl->addDecl(CopyAssignment);
8915
Douglas Gregord3c35902010-07-01 16:36:15 +00008916 return CopyAssignment;
8917}
8918
Richard Smith36155c12013-06-13 03:23:42 +00008919/// Diagnose an implicit copy operation for a class which is odr-used, but
8920/// which is deprecated because the class has a user-declared copy constructor,
8921/// copy assignment operator, or destructor.
8922static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
8923 SourceLocation UseLoc) {
8924 assert(CopyOp->isImplicit());
8925
8926 CXXRecordDecl *RD = CopyOp->getParent();
8927 CXXMethodDecl *UserDeclaredOperation = 0;
8928
8929 // In Microsoft mode, assignment operations don't affect constructors and
8930 // vice versa.
8931 if (RD->hasUserDeclaredDestructor()) {
8932 UserDeclaredOperation = RD->getDestructor();
8933 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
8934 RD->hasUserDeclaredCopyConstructor() &&
8935 !S.getLangOpts().MicrosoftMode) {
8936 // Find any user-declared copy constructor.
8937 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
8938 E = RD->ctor_end(); I != E; ++I) {
8939 if (I->isCopyConstructor()) {
8940 UserDeclaredOperation = *I;
8941 break;
8942 }
8943 }
8944 assert(UserDeclaredOperation);
8945 } else if (isa<CXXConstructorDecl>(CopyOp) &&
8946 RD->hasUserDeclaredCopyAssignment() &&
8947 !S.getLangOpts().MicrosoftMode) {
8948 // Find any user-declared move assignment operator.
8949 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
8950 E = RD->method_end(); I != E; ++I) {
8951 if (I->isCopyAssignmentOperator()) {
8952 UserDeclaredOperation = *I;
8953 break;
8954 }
8955 }
8956 assert(UserDeclaredOperation);
8957 }
8958
8959 if (UserDeclaredOperation) {
8960 S.Diag(UserDeclaredOperation->getLocation(),
8961 diag::warn_deprecated_copy_operation)
8962 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
8963 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
8964 S.Diag(UseLoc, diag::note_member_synthesized_at)
8965 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
8966 : Sema::CXXCopyAssignment)
8967 << RD;
8968 }
8969}
8970
Douglas Gregor06a9f362010-05-01 20:49:11 +00008971void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8972 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008973 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008974 CopyAssignOperator->isOverloadedOperator() &&
8975 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008976 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8977 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008978 "DefineImplicitCopyAssignment called for wrong function");
8979
8980 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8981
8982 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8983 CopyAssignOperator->setInvalidDecl();
8984 return;
8985 }
Richard Smith36155c12013-06-13 03:23:42 +00008986
8987 // C++11 [class.copy]p18:
8988 // The [definition of an implicitly declared copy assignment operator] is
8989 // deprecated if the class has a user-declared copy constructor or a
8990 // user-declared destructor.
8991 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
8992 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
8993
Douglas Gregor06a9f362010-05-01 20:49:11 +00008994 CopyAssignOperator->setUsed();
8995
Eli Friedman9a14db32012-10-18 20:14:08 +00008996 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008997 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008998
8999 // C++0x [class.copy]p30:
9000 // The implicitly-defined or explicitly-defaulted copy assignment operator
9001 // for a non-union class X performs memberwise copy assignment of its
9002 // subobjects. The direct base classes of X are assigned first, in the
9003 // order of their declaration in the base-specifier-list, and then the
9004 // immediate non-static data members of X are assigned, in the order in
9005 // which they were declared in the class definition.
9006
9007 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009008 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009009
9010 // The parameter for the "other" object, which we are copying from.
9011 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9012 Qualifiers OtherQuals = Other->getType().getQualifiers();
9013 QualType OtherRefType = Other->getType();
9014 if (const LValueReferenceType *OtherRef
9015 = OtherRefType->getAs<LValueReferenceType>()) {
9016 OtherRefType = OtherRef->getPointeeType();
9017 OtherQuals = OtherRefType.getQualifiers();
9018 }
9019
9020 // Our location for everything implicitly-generated.
9021 SourceLocation Loc = CopyAssignOperator->getLocation();
9022
9023 // Construct a reference to the "other" object. We'll be using this
9024 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00009025 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00009026 assert(OtherRef && "Reference to parameter cannot fail!");
9027
9028 // Construct the "this" pointer. We'll be using this throughout the generated
9029 // ASTs.
9030 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9031 assert(This && "Reference to this cannot fail!");
9032
9033 // Assign base classes.
9034 bool Invalid = false;
9035 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9036 E = ClassDecl->bases_end(); Base != E; ++Base) {
9037 // Form the assignment:
9038 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9039 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009040 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009041 Invalid = true;
9042 continue;
9043 }
9044
John McCallf871d0c2010-08-07 06:22:56 +00009045 CXXCastPath BasePath;
9046 BasePath.push_back(Base);
9047
Douglas Gregor06a9f362010-05-01 20:49:11 +00009048 // Construct the "from" expression, which is an implicit cast to the
9049 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00009050 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00009051 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
9052 CK_UncheckedDerivedToBase,
9053 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00009054
9055 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00009056 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009057
9058 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00009059 To = ImpCastExprToType(To.take(),
9060 Context.getCVRQualifiedType(BaseType,
9061 CopyAssignOperator->getTypeQualifiers()),
9062 CK_UncheckedDerivedToBase,
9063 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009064
9065 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009066 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00009067 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009068 /*CopyingBaseSubobject=*/true,
9069 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009070 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009071 Diag(CurrentLocation, diag::note_member_synthesized_at)
9072 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9073 CopyAssignOperator->setInvalidDecl();
9074 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009075 }
9076
9077 // Success! Record the copy.
9078 Statements.push_back(Copy.takeAs<Expr>());
9079 }
9080
Douglas Gregor06a9f362010-05-01 20:49:11 +00009081 // Assign non-static members.
9082 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9083 FieldEnd = ClassDecl->field_end();
9084 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009085 if (Field->isUnnamedBitfield())
9086 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009087
9088 if (Field->isInvalidDecl()) {
9089 Invalid = true;
9090 continue;
9091 }
9092
Douglas Gregor06a9f362010-05-01 20:49:11 +00009093 // Check for members of reference type; we can't copy those.
9094 if (Field->getType()->isReferenceType()) {
9095 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9096 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9097 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009098 Diag(CurrentLocation, diag::note_member_synthesized_at)
9099 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009100 Invalid = true;
9101 continue;
9102 }
9103
9104 // Check for members of const-qualified, non-class type.
9105 QualType BaseType = Context.getBaseElementType(Field->getType());
9106 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9107 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9108 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9109 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009110 Diag(CurrentLocation, diag::note_member_synthesized_at)
9111 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009112 Invalid = true;
9113 continue;
9114 }
John McCallb77115d2011-06-17 00:18:42 +00009115
9116 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009117 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9118 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009119
9120 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009121 if (FieldType->isIncompleteArrayType()) {
9122 assert(ClassDecl->hasFlexibleArrayMember() &&
9123 "Incomplete array type is not valid");
9124 continue;
9125 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009126
9127 // Build references to the field in the object we're copying from and to.
9128 CXXScopeSpec SS; // Intentionally empty
9129 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9130 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009131 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009132 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00009133 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00009134 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009135 SS, SourceLocation(), 0,
9136 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009137 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00009138 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009139 SS, SourceLocation(), 0,
9140 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009141 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9142 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00009143
Douglas Gregor06a9f362010-05-01 20:49:11 +00009144 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009145 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009146 To.get(), From.get(),
9147 /*CopyingBaseSubobject=*/false,
9148 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009149 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009150 Diag(CurrentLocation, diag::note_member_synthesized_at)
9151 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9152 CopyAssignOperator->setInvalidDecl();
9153 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009154 }
9155
9156 // Success! Record the copy.
9157 Statements.push_back(Copy.takeAs<Stmt>());
9158 }
9159
9160 if (!Invalid) {
9161 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00009162 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009163
John McCall60d7b3a2010-08-24 06:29:42 +00009164 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009165 if (Return.isInvalid())
9166 Invalid = true;
9167 else {
9168 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009169
9170 if (Trap.hasErrorOccurred()) {
9171 Diag(CurrentLocation, diag::note_member_synthesized_at)
9172 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9173 Invalid = true;
9174 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009175 }
9176 }
9177
9178 if (Invalid) {
9179 CopyAssignOperator->setInvalidDecl();
9180 return;
9181 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009182
9183 StmtResult Body;
9184 {
9185 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009186 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009187 /*isStmtExpr=*/false);
9188 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9189 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009190 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009191
9192 if (ASTMutationListener *L = getASTMutationListener()) {
9193 L->CompletedImplicitDefinition(CopyAssignOperator);
9194 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009195}
9196
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009197Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009198Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9199 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009200
Richard Smithb9d0b762012-07-27 04:22:15 +00009201 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009202 if (ClassDecl->isInvalidDecl())
9203 return ExceptSpec;
9204
9205 // C++0x [except.spec]p14:
9206 // An implicitly declared special member function (Clause 12) shall have an
9207 // exception-specification. [...]
9208
9209 // It is unspecified whether or not an implicit move assignment operator
9210 // attempts to deduplicate calls to assignment operators of virtual bases are
9211 // made. As such, this exception specification is effectively unspecified.
9212 // Based on a similar decision made for constness in C++0x, we're erring on
9213 // the side of assuming such calls to be made regardless of whether they
9214 // actually happen.
9215 // Note that a move constructor is not implicitly declared when there are
9216 // virtual bases, but it can still be user-declared and explicitly defaulted.
9217 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9218 BaseEnd = ClassDecl->bases_end();
9219 Base != BaseEnd; ++Base) {
9220 if (Base->isVirtual())
9221 continue;
9222
9223 CXXRecordDecl *BaseClassDecl
9224 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9225 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009226 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009227 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009228 }
9229
9230 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9231 BaseEnd = ClassDecl->vbases_end();
9232 Base != BaseEnd; ++Base) {
9233 CXXRecordDecl *BaseClassDecl
9234 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9235 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009236 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009237 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009238 }
9239
9240 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9241 FieldEnd = ClassDecl->field_end();
9242 Field != FieldEnd;
9243 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009244 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009245 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009246 if (CXXMethodDecl *MoveAssign =
9247 LookupMovingAssignment(FieldClassDecl,
9248 FieldType.getCVRQualifiers(),
9249 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009250 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009251 }
9252 }
9253
9254 return ExceptSpec;
9255}
9256
Richard Smith1c931be2012-04-02 18:40:40 +00009257/// Determine whether the class type has any direct or indirect virtual base
9258/// classes which have a non-trivial move assignment operator.
9259static bool
9260hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9261 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9262 BaseEnd = ClassDecl->vbases_end();
9263 Base != BaseEnd; ++Base) {
9264 CXXRecordDecl *BaseClass =
9265 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9266
9267 // Try to declare the move assignment. If it would be deleted, then the
9268 // class does not have a non-trivial move assignment.
9269 if (BaseClass->needsImplicitMoveAssignment())
9270 S.DeclareImplicitMoveAssignment(BaseClass);
9271
Richard Smith426391c2012-11-16 00:53:38 +00009272 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009273 return true;
9274 }
9275
9276 return false;
9277}
9278
9279/// Determine whether the given type either has a move constructor or is
9280/// trivially copyable.
9281static bool
9282hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9283 Type = S.Context.getBaseElementType(Type);
9284
9285 // FIXME: Technically, non-trivially-copyable non-class types, such as
9286 // reference types, are supposed to return false here, but that appears
9287 // to be a standard defect.
9288 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009289 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009290 return true;
9291
9292 if (Type.isTriviallyCopyableType(S.Context))
9293 return true;
9294
9295 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009296 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9297 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009298 if (ClassDecl->needsImplicitMoveConstructor())
9299 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009300 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009301 }
9302
Richard Smithe5411b72012-12-01 02:35:44 +00009303 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9304 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009305 if (ClassDecl->needsImplicitMoveAssignment())
9306 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009307 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009308}
9309
9310/// Determine whether all non-static data members and direct or virtual bases
9311/// of class \p ClassDecl have either a move operation, or are trivially
9312/// copyable.
9313static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9314 bool IsConstructor) {
9315 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9316 BaseEnd = ClassDecl->bases_end();
9317 Base != BaseEnd; ++Base) {
9318 if (Base->isVirtual())
9319 continue;
9320
9321 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9322 return false;
9323 }
9324
9325 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9326 BaseEnd = ClassDecl->vbases_end();
9327 Base != BaseEnd; ++Base) {
9328 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9329 return false;
9330 }
9331
9332 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9333 FieldEnd = ClassDecl->field_end();
9334 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009335 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009336 return false;
9337 }
9338
9339 return true;
9340}
9341
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009342CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009343 // C++11 [class.copy]p20:
9344 // If the definition of a class X does not explicitly declare a move
9345 // assignment operator, one will be implicitly declared as defaulted
9346 // if and only if:
9347 //
9348 // - [first 4 bullets]
9349 assert(ClassDecl->needsImplicitMoveAssignment());
9350
Richard Smithafb49182012-11-29 01:34:07 +00009351 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9352 if (DSM.isAlreadyBeingDeclared())
9353 return 0;
9354
Richard Smith1c931be2012-04-02 18:40:40 +00009355 // [Checked after we build the declaration]
9356 // - the move assignment operator would not be implicitly defined as
9357 // deleted,
9358
9359 // [DR1402]:
9360 // - X has no direct or indirect virtual base class with a non-trivial
9361 // move assignment operator, and
9362 // - each of X's non-static data members and direct or virtual base classes
9363 // has a type that either has a move assignment operator or is trivially
9364 // copyable.
9365 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9366 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9367 ClassDecl->setFailedImplicitMoveAssignment();
9368 return 0;
9369 }
9370
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009371 // Note: The following rules are largely analoguous to the move
9372 // constructor rules.
9373
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009374 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9375 QualType RetType = Context.getLValueReferenceType(ArgType);
9376 ArgType = Context.getRValueReferenceType(ArgType);
9377
Richard Smitha8942d72013-05-07 03:19:20 +00009378 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9379 CXXMoveAssignment,
9380 false);
9381
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009382 // An implicitly-declared move assignment operator is an inline public
9383 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009384 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9385 SourceLocation ClassLoc = ClassDecl->getLocation();
9386 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009387 CXXMethodDecl *MoveAssignment =
9388 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9389 /*TInfo=*/0, /*StorageClass=*/SC_None,
9390 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009391 MoveAssignment->setAccess(AS_public);
9392 MoveAssignment->setDefaulted();
9393 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009394
Richard Smithb9d0b762012-07-27 04:22:15 +00009395 // Build an exception specification pointing back at this member.
9396 FunctionProtoType::ExtProtoInfo EPI;
9397 EPI.ExceptionSpecType = EST_Unevaluated;
9398 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009399 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009400
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009401 // Add the parameter to the operator.
9402 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9403 ClassLoc, ClassLoc, /*Id=*/0,
9404 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009405 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009406 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009407
Richard Smithbc2a35d2012-12-08 08:32:28 +00009408 AddOverriddenMethods(ClassDecl, MoveAssignment);
9409
9410 MoveAssignment->setTrivial(
9411 ClassDecl->needsOverloadResolutionForMoveAssignment()
9412 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9413 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009414
9415 // C++0x [class.copy]p9:
9416 // If the definition of a class X does not explicitly declare a move
9417 // assignment operator, one will be implicitly declared as defaulted if and
9418 // only if:
9419 // [...]
9420 // - the move assignment operator would not be implicitly defined as
9421 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009422 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009423 // Cache this result so that we don't try to generate this over and over
9424 // on every lookup, leaking memory and wasting time.
9425 ClassDecl->setFailedImplicitMoveAssignment();
9426 return 0;
9427 }
9428
Richard Smithbc2a35d2012-12-08 08:32:28 +00009429 // Note that we have added this copy-assignment operator.
9430 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9431
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009432 if (Scope *S = getScopeForContext(ClassDecl))
9433 PushOnScopeChains(MoveAssignment, S, false);
9434 ClassDecl->addDecl(MoveAssignment);
9435
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009436 return MoveAssignment;
9437}
9438
9439void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9440 CXXMethodDecl *MoveAssignOperator) {
9441 assert((MoveAssignOperator->isDefaulted() &&
9442 MoveAssignOperator->isOverloadedOperator() &&
9443 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009444 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9445 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009446 "DefineImplicitMoveAssignment called for wrong function");
9447
9448 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9449
9450 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9451 MoveAssignOperator->setInvalidDecl();
9452 return;
9453 }
9454
9455 MoveAssignOperator->setUsed();
9456
Eli Friedman9a14db32012-10-18 20:14:08 +00009457 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009458 DiagnosticErrorTrap Trap(Diags);
9459
9460 // C++0x [class.copy]p28:
9461 // The implicitly-defined or move assignment operator for a non-union class
9462 // X performs memberwise move assignment of its subobjects. The direct base
9463 // classes of X are assigned first, in the order of their declaration in the
9464 // base-specifier-list, and then the immediate non-static data members of X
9465 // are assigned, in the order in which they were declared in the class
9466 // definition.
9467
9468 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009469 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009470
9471 // The parameter for the "other" object, which we are move from.
9472 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9473 QualType OtherRefType = Other->getType()->
9474 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009475 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009476 "Bad argument type of defaulted move assignment");
9477
9478 // Our location for everything implicitly-generated.
9479 SourceLocation Loc = MoveAssignOperator->getLocation();
9480
9481 // Construct a reference to the "other" object. We'll be using this
9482 // throughout the generated ASTs.
9483 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9484 assert(OtherRef && "Reference to parameter cannot fail!");
9485 // Cast to rvalue.
9486 OtherRef = CastForMoving(*this, OtherRef);
9487
9488 // Construct the "this" pointer. We'll be using this throughout the generated
9489 // ASTs.
9490 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9491 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009492
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009493 // Assign base classes.
9494 bool Invalid = false;
9495 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9496 E = ClassDecl->bases_end(); Base != E; ++Base) {
9497 // Form the assignment:
9498 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9499 QualType BaseType = Base->getType().getUnqualifiedType();
9500 if (!BaseType->isRecordType()) {
9501 Invalid = true;
9502 continue;
9503 }
9504
9505 CXXCastPath BasePath;
9506 BasePath.push_back(Base);
9507
9508 // Construct the "from" expression, which is an implicit cast to the
9509 // appropriately-qualified base type.
9510 Expr *From = OtherRef;
9511 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009512 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009513
9514 // Dereference "this".
9515 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9516
9517 // Implicitly cast "this" to the appropriately-qualified base type.
9518 To = ImpCastExprToType(To.take(),
9519 Context.getCVRQualifiedType(BaseType,
9520 MoveAssignOperator->getTypeQualifiers()),
9521 CK_UncheckedDerivedToBase,
9522 VK_LValue, &BasePath);
9523
9524 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009525 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009526 To.get(), From,
9527 /*CopyingBaseSubobject=*/true,
9528 /*Copying=*/false);
9529 if (Move.isInvalid()) {
9530 Diag(CurrentLocation, diag::note_member_synthesized_at)
9531 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9532 MoveAssignOperator->setInvalidDecl();
9533 return;
9534 }
9535
9536 // Success! Record the move.
9537 Statements.push_back(Move.takeAs<Expr>());
9538 }
9539
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009540 // Assign non-static members.
9541 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9542 FieldEnd = ClassDecl->field_end();
9543 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009544 if (Field->isUnnamedBitfield())
9545 continue;
9546
Eli Friedman8150da32013-06-07 01:48:56 +00009547 if (Field->isInvalidDecl()) {
9548 Invalid = true;
9549 continue;
9550 }
9551
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009552 // Check for members of reference type; we can't move those.
9553 if (Field->getType()->isReferenceType()) {
9554 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9555 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9556 Diag(Field->getLocation(), diag::note_declared_at);
9557 Diag(CurrentLocation, diag::note_member_synthesized_at)
9558 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9559 Invalid = true;
9560 continue;
9561 }
9562
9563 // Check for members of const-qualified, non-class type.
9564 QualType BaseType = Context.getBaseElementType(Field->getType());
9565 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9566 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9567 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9568 Diag(Field->getLocation(), diag::note_declared_at);
9569 Diag(CurrentLocation, diag::note_member_synthesized_at)
9570 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9571 Invalid = true;
9572 continue;
9573 }
9574
9575 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009576 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9577 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009578
9579 QualType FieldType = Field->getType().getNonReferenceType();
9580 if (FieldType->isIncompleteArrayType()) {
9581 assert(ClassDecl->hasFlexibleArrayMember() &&
9582 "Incomplete array type is not valid");
9583 continue;
9584 }
9585
9586 // Build references to the field in the object we're copying from and to.
9587 CXXScopeSpec SS; // Intentionally empty
9588 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9589 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009590 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009591 MemberLookup.resolveKind();
9592 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9593 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009594 SS, SourceLocation(), 0,
9595 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009596 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9597 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009598 SS, SourceLocation(), 0,
9599 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009600 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9601 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9602
9603 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9604 "Member reference with rvalue base must be rvalue except for reference "
9605 "members, which aren't allowed for move assignment.");
9606
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009607 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009608 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009609 To.get(), From.get(),
9610 /*CopyingBaseSubobject=*/false,
9611 /*Copying=*/false);
9612 if (Move.isInvalid()) {
9613 Diag(CurrentLocation, diag::note_member_synthesized_at)
9614 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9615 MoveAssignOperator->setInvalidDecl();
9616 return;
9617 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009618
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009619 // Success! Record the copy.
9620 Statements.push_back(Move.takeAs<Stmt>());
9621 }
9622
9623 if (!Invalid) {
9624 // Add a "return *this;"
9625 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9626
9627 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9628 if (Return.isInvalid())
9629 Invalid = true;
9630 else {
9631 Statements.push_back(Return.takeAs<Stmt>());
9632
9633 if (Trap.hasErrorOccurred()) {
9634 Diag(CurrentLocation, diag::note_member_synthesized_at)
9635 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9636 Invalid = true;
9637 }
9638 }
9639 }
9640
9641 if (Invalid) {
9642 MoveAssignOperator->setInvalidDecl();
9643 return;
9644 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009645
9646 StmtResult Body;
9647 {
9648 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009649 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009650 /*isStmtExpr=*/false);
9651 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9652 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009653 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9654
9655 if (ASTMutationListener *L = getASTMutationListener()) {
9656 L->CompletedImplicitDefinition(MoveAssignOperator);
9657 }
9658}
9659
Richard Smithb9d0b762012-07-27 04:22:15 +00009660Sema::ImplicitExceptionSpecification
9661Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9662 CXXRecordDecl *ClassDecl = MD->getParent();
9663
9664 ImplicitExceptionSpecification ExceptSpec(*this);
9665 if (ClassDecl->isInvalidDecl())
9666 return ExceptSpec;
9667
9668 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9669 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9670 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9671
Douglas Gregor0d405db2010-07-01 20:59:04 +00009672 // C++ [except.spec]p14:
9673 // An implicitly declared special member function (Clause 12) shall have an
9674 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009675 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9676 BaseEnd = ClassDecl->bases_end();
9677 Base != BaseEnd;
9678 ++Base) {
9679 // Virtual bases are handled below.
9680 if (Base->isVirtual())
9681 continue;
9682
Douglas Gregor22584312010-07-02 23:41:54 +00009683 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009684 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009685 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009686 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009687 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009688 }
9689 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9690 BaseEnd = ClassDecl->vbases_end();
9691 Base != BaseEnd;
9692 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009693 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009694 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009695 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009696 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009697 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009698 }
9699 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9700 FieldEnd = ClassDecl->field_end();
9701 Field != FieldEnd;
9702 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009703 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009704 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9705 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009706 LookupCopyingConstructor(FieldClassDecl,
9707 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009708 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009709 }
9710 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009711
Richard Smithb9d0b762012-07-27 04:22:15 +00009712 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009713}
9714
9715CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9716 CXXRecordDecl *ClassDecl) {
9717 // C++ [class.copy]p4:
9718 // If the class definition does not explicitly declare a copy
9719 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009720 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009721
Richard Smithafb49182012-11-29 01:34:07 +00009722 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9723 if (DSM.isAlreadyBeingDeclared())
9724 return 0;
9725
Sean Hunt49634cf2011-05-13 06:10:58 +00009726 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9727 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009728 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009729 if (Const)
9730 ArgType = ArgType.withConst();
9731 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009732
Richard Smith7756afa2012-06-10 05:43:50 +00009733 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9734 CXXCopyConstructor,
9735 Const);
9736
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009737 DeclarationName Name
9738 = Context.DeclarationNames.getCXXConstructorName(
9739 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009740 SourceLocation ClassLoc = ClassDecl->getLocation();
9741 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009742
9743 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009744 // member of its class.
9745 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009746 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009747 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009748 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009749 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009750 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009751
Richard Smithb9d0b762012-07-27 04:22:15 +00009752 // Build an exception specification pointing back at this member.
9753 FunctionProtoType::ExtProtoInfo EPI;
9754 EPI.ExceptionSpecType = EST_Unevaluated;
9755 EPI.ExceptionSpecDecl = CopyConstructor;
9756 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009757 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009758
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009759 // Add the parameter to the constructor.
9760 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009761 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009762 /*IdentifierInfo=*/0,
9763 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009764 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009765 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009766
Richard Smithbc2a35d2012-12-08 08:32:28 +00009767 CopyConstructor->setTrivial(
9768 ClassDecl->needsOverloadResolutionForCopyConstructor()
9769 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9770 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009771
Nico Weberafcc96a2012-01-23 03:19:29 +00009772 // C++11 [class.copy]p8:
9773 // ... If the class definition does not explicitly declare a copy
9774 // constructor, there is no user-declared move constructor, and there is no
9775 // user-declared move assignment operator, a copy constructor is implicitly
9776 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009777 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009778 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009779
Richard Smithbc2a35d2012-12-08 08:32:28 +00009780 // Note that we have declared this constructor.
9781 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9782
9783 if (Scope *S = getScopeForContext(ClassDecl))
9784 PushOnScopeChains(CopyConstructor, S, false);
9785 ClassDecl->addDecl(CopyConstructor);
9786
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009787 return CopyConstructor;
9788}
9789
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009790void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009791 CXXConstructorDecl *CopyConstructor) {
9792 assert((CopyConstructor->isDefaulted() &&
9793 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009794 !CopyConstructor->doesThisDeclarationHaveABody() &&
9795 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009796 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009797
Anders Carlsson63010a72010-04-23 16:24:12 +00009798 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009799 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009800
Richard Smith36155c12013-06-13 03:23:42 +00009801 // C++11 [class.copy]p7:
9802 // The [definition of an implicitly declared copy constructro] is
9803 // deprecated if the class has a user-declared copy assignment operator
9804 // or a user-declared destructor.
9805 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9806 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9807
Eli Friedman9a14db32012-10-18 20:14:08 +00009808 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009809 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009810
David Blaikie93c86172013-01-17 05:26:25 +00009811 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009812 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009813 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009814 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009815 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009816 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009817 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009818 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9819 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009820 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009821 /*isStmtExpr=*/false)
9822 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009823 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009824 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009825
9826 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009827 if (ASTMutationListener *L = getASTMutationListener()) {
9828 L->CompletedImplicitDefinition(CopyConstructor);
9829 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009830}
9831
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009832Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009833Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9834 CXXRecordDecl *ClassDecl = MD->getParent();
9835
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009836 // C++ [except.spec]p14:
9837 // An implicitly declared special member function (Clause 12) shall have an
9838 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009839 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009840 if (ClassDecl->isInvalidDecl())
9841 return ExceptSpec;
9842
9843 // Direct base-class constructors.
9844 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9845 BEnd = ClassDecl->bases_end();
9846 B != BEnd; ++B) {
9847 if (B->isVirtual()) // Handled below.
9848 continue;
9849
9850 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9851 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009852 CXXConstructorDecl *Constructor =
9853 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009854 // If this is a deleted function, add it anyway. This might be conformant
9855 // with the standard. This might not. I'm not sure. It might not matter.
9856 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009857 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009858 }
9859 }
9860
9861 // Virtual base-class constructors.
9862 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9863 BEnd = ClassDecl->vbases_end();
9864 B != BEnd; ++B) {
9865 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9866 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009867 CXXConstructorDecl *Constructor =
9868 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009869 // If this is a deleted function, add it anyway. This might be conformant
9870 // with the standard. This might not. I'm not sure. It might not matter.
9871 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009872 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009873 }
9874 }
9875
9876 // Field constructors.
9877 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9878 FEnd = ClassDecl->field_end();
9879 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009880 QualType FieldType = Context.getBaseElementType(F->getType());
9881 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9882 CXXConstructorDecl *Constructor =
9883 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009884 // If this is a deleted function, add it anyway. This might be conformant
9885 // with the standard. This might not. I'm not sure. It might not matter.
9886 // In particular, the problem is that this function never gets called. It
9887 // might just be ill-formed because this function attempts to refer to
9888 // a deleted function here.
9889 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009890 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009891 }
9892 }
9893
9894 return ExceptSpec;
9895}
9896
9897CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9898 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009899 // C++11 [class.copy]p9:
9900 // If the definition of a class X does not explicitly declare a move
9901 // constructor, one will be implicitly declared as defaulted if and only if:
9902 //
9903 // - [first 4 bullets]
9904 assert(ClassDecl->needsImplicitMoveConstructor());
9905
Richard Smithafb49182012-11-29 01:34:07 +00009906 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9907 if (DSM.isAlreadyBeingDeclared())
9908 return 0;
9909
Richard Smith1c931be2012-04-02 18:40:40 +00009910 // [Checked after we build the declaration]
9911 // - the move assignment operator would not be implicitly defined as
9912 // deleted,
9913
9914 // [DR1402]:
9915 // - each of X's non-static data members and direct or virtual base classes
9916 // has a type that either has a move constructor or is trivially copyable.
9917 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9918 ClassDecl->setFailedImplicitMoveConstructor();
9919 return 0;
9920 }
9921
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009922 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9923 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009924
Richard Smith7756afa2012-06-10 05:43:50 +00009925 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9926 CXXMoveConstructor,
9927 false);
9928
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009929 DeclarationName Name
9930 = Context.DeclarationNames.getCXXConstructorName(
9931 Context.getCanonicalType(ClassType));
9932 SourceLocation ClassLoc = ClassDecl->getLocation();
9933 DeclarationNameInfo NameInfo(Name, ClassLoc);
9934
Richard Smitha8942d72013-05-07 03:19:20 +00009935 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009936 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009937 // member of its class.
9938 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009939 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009940 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009941 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009942 MoveConstructor->setAccess(AS_public);
9943 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009944
Richard Smithb9d0b762012-07-27 04:22:15 +00009945 // Build an exception specification pointing back at this member.
9946 FunctionProtoType::ExtProtoInfo EPI;
9947 EPI.ExceptionSpecType = EST_Unevaluated;
9948 EPI.ExceptionSpecDecl = MoveConstructor;
9949 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009950 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009951
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009952 // Add the parameter to the constructor.
9953 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9954 ClassLoc, ClassLoc,
9955 /*IdentifierInfo=*/0,
9956 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009957 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009958 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009959
Richard Smithbc2a35d2012-12-08 08:32:28 +00009960 MoveConstructor->setTrivial(
9961 ClassDecl->needsOverloadResolutionForMoveConstructor()
9962 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9963 : ClassDecl->hasTrivialMoveConstructor());
9964
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009965 // C++0x [class.copy]p9:
9966 // If the definition of a class X does not explicitly declare a move
9967 // constructor, one will be implicitly declared as defaulted if and only if:
9968 // [...]
9969 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009970 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009971 // Cache this result so that we don't try to generate this over and over
9972 // on every lookup, leaking memory and wasting time.
9973 ClassDecl->setFailedImplicitMoveConstructor();
9974 return 0;
9975 }
9976
9977 // Note that we have declared this constructor.
9978 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9979
9980 if (Scope *S = getScopeForContext(ClassDecl))
9981 PushOnScopeChains(MoveConstructor, S, false);
9982 ClassDecl->addDecl(MoveConstructor);
9983
9984 return MoveConstructor;
9985}
9986
9987void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9988 CXXConstructorDecl *MoveConstructor) {
9989 assert((MoveConstructor->isDefaulted() &&
9990 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009991 !MoveConstructor->doesThisDeclarationHaveABody() &&
9992 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009993 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9994
9995 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9996 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9997
Eli Friedman9a14db32012-10-18 20:14:08 +00009998 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009999 DiagnosticErrorTrap Trap(Diags);
10000
David Blaikie93c86172013-01-17 05:26:25 +000010001 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010002 Trap.hasErrorOccurred()) {
10003 Diag(CurrentLocation, diag::note_member_synthesized_at)
10004 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10005 MoveConstructor->setInvalidDecl();
10006 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010007 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010008 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
10009 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +000010010 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010011 /*isStmtExpr=*/false)
10012 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +000010013 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010014 }
10015
10016 MoveConstructor->setUsed();
10017
10018 if (ASTMutationListener *L = getASTMutationListener()) {
10019 L->CompletedImplicitDefinition(MoveConstructor);
10020 }
10021}
10022
Douglas Gregore4e68d42012-02-15 19:33:52 +000010023bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010024 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010025}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010026
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010027/// \brief Mark the call operator of the given lambda closure type as "used".
10028static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
10029 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +000010030 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +000010031 Lambda->lookup(
10032 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010033 CallOperator->setReferenced();
10034 CallOperator->setUsed();
10035}
10036
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010037void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10038 SourceLocation CurrentLocation,
10039 CXXConversionDecl *Conv)
10040{
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010041 CXXRecordDecl *Lambda = Conv->getParent();
10042
10043 // Make sure that the lambda call operator is marked used.
10044 markLambdaCallOperatorUsed(*this, Lambda);
10045
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010046 Conv->setUsed();
10047
Eli Friedman9a14db32012-10-18 20:14:08 +000010048 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010049 DiagnosticErrorTrap Trap(Diags);
10050
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010051 // Return the address of the __invoke function.
10052 DeclarationName InvokeName = &Context.Idents.get("__invoke");
10053 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +000010054 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010055 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
10056 VK_LValue, Conv->getLocation()).take();
10057 assert(FunctionRef && "Can't refer to __invoke function?");
10058 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +000010059 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010060 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010061 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010062
10063 // Fill in the __invoke function with a dummy implementation. IR generation
10064 // will fill in the actual details.
10065 Invoke->setUsed();
10066 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +000010067 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010068
10069 if (ASTMutationListener *L = getASTMutationListener()) {
10070 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010071 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010072 }
10073}
10074
10075void Sema::DefineImplicitLambdaToBlockPointerConversion(
10076 SourceLocation CurrentLocation,
10077 CXXConversionDecl *Conv)
10078{
10079 Conv->setUsed();
10080
Eli Friedman9a14db32012-10-18 20:14:08 +000010081 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010082 DiagnosticErrorTrap Trap(Diags);
10083
Douglas Gregorac1303e2012-02-22 05:02:47 +000010084 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010085 Expr *This = ActOnCXXThis(CurrentLocation).take();
10086 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010087
Eli Friedman23f02672012-03-01 04:01:32 +000010088 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10089 Conv->getLocation(),
10090 Conv, DerefThis);
10091
10092 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10093 // behavior. Note that only the general conversion function does this
10094 // (since it's unusable otherwise); in the case where we inline the
10095 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010096 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010097 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10098 CK_CopyAndAutoreleaseBlockObject,
10099 BuildBlock.get(), 0, VK_RValue);
10100
10101 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010102 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010103 Conv->setInvalidDecl();
10104 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010105 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010106
Douglas Gregorac1303e2012-02-22 05:02:47 +000010107 // Create the return statement that returns the block from the conversion
10108 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010109 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010110 if (Return.isInvalid()) {
10111 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10112 Conv->setInvalidDecl();
10113 return;
10114 }
10115
10116 // Set the body of the conversion function.
10117 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010118 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010119 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010120 Conv->getLocation()));
10121
Douglas Gregorac1303e2012-02-22 05:02:47 +000010122 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010123 if (ASTMutationListener *L = getASTMutationListener()) {
10124 L->CompletedImplicitDefinition(Conv);
10125 }
10126}
10127
Douglas Gregorf52757d2012-03-10 06:53:13 +000010128/// \brief Determine whether the given list arguments contains exactly one
10129/// "real" (non-default) argument.
10130static bool hasOneRealArgument(MultiExprArg Args) {
10131 switch (Args.size()) {
10132 case 0:
10133 return false;
10134
10135 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010136 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010137 return false;
10138
10139 // fall through
10140 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010141 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010142 }
10143
10144 return false;
10145}
10146
John McCall60d7b3a2010-08-24 06:29:42 +000010147ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010148Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010149 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010150 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010151 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010152 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010153 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010154 unsigned ConstructKind,
10155 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010156 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010157
Douglas Gregor2f599792010-04-02 18:24:57 +000010158 // C++0x [class.copy]p34:
10159 // When certain criteria are met, an implementation is allowed to
10160 // omit the copy/move construction of a class object, even if the
10161 // copy/move constructor and/or destructor for the object have
10162 // side effects. [...]
10163 // - when a temporary class object that has not been bound to a
10164 // reference (12.2) would be copied/moved to a class object
10165 // with the same cv-unqualified type, the copy/move operation
10166 // can be omitted by constructing the temporary object
10167 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010168 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010169 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010170 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010171 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010172 }
Mike Stump1eb44332009-09-09 15:08:12 +000010173
10174 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010175 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010176 IsListInitialization, RequiresZeroInit,
10177 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010178}
10179
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010180/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10181/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010182ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010183Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10184 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010185 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010186 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010187 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010188 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010189 unsigned ConstructKind,
10190 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010191 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010192 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010193 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010194 HadMultipleCandidates,
10195 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010196 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10197 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010198}
10199
John McCall68c6c9a2010-02-02 09:10:11 +000010200void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010201 if (VD->isInvalidDecl()) return;
10202
John McCall68c6c9a2010-02-02 09:10:11 +000010203 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010204 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010205 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010206 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010207
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010208 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010209 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010210 CheckDestructorAccess(VD->getLocation(), Destructor,
10211 PDiag(diag::err_access_dtor_var)
10212 << VD->getDeclName()
10213 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010214 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010215
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010216 if (!VD->hasGlobalStorage()) return;
10217
10218 // Emit warning for non-trivial dtor in global scope (a real global,
10219 // class-static, function-static).
10220 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10221
10222 // TODO: this should be re-enabled for static locals by !CXAAtExit
10223 if (!VD->isStaticLocal())
10224 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010225}
10226
Douglas Gregor39da0b82009-09-09 23:08:42 +000010227/// \brief Given a constructor and the set of arguments provided for the
10228/// constructor, convert the arguments and add any required default arguments
10229/// to form a proper call to this constructor.
10230///
10231/// \returns true if an error occurred, false otherwise.
10232bool
10233Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10234 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010235 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010236 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010237 bool AllowExplicit,
10238 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010239 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10240 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010241 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010242
10243 const FunctionProtoType *Proto
10244 = Constructor->getType()->getAs<FunctionProtoType>();
10245 assert(Proto && "Constructor without a prototype?");
10246 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010247
10248 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010249 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010250 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010251 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010252 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010253
10254 VariadicCallType CallType =
10255 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010256 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010257 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010258 Proto, 0,
10259 llvm::makeArrayRef(Args, NumArgs),
10260 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010261 CallType, AllowExplicit,
10262 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010263 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010264
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010265 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010266
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010267 CheckConstructorCall(Constructor,
10268 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10269 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010270 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010271
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010272 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010273}
10274
Anders Carlsson20d45d22009-12-12 00:32:00 +000010275static inline bool
10276CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10277 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010278 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010279 if (isa<NamespaceDecl>(DC)) {
10280 return SemaRef.Diag(FnDecl->getLocation(),
10281 diag::err_operator_new_delete_declared_in_namespace)
10282 << FnDecl->getDeclName();
10283 }
10284
10285 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010286 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010287 return SemaRef.Diag(FnDecl->getLocation(),
10288 diag::err_operator_new_delete_declared_static)
10289 << FnDecl->getDeclName();
10290 }
10291
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010292 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010293}
10294
Anders Carlsson156c78e2009-12-13 17:53:43 +000010295static inline bool
10296CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10297 CanQualType ExpectedResultType,
10298 CanQualType ExpectedFirstParamType,
10299 unsigned DependentParamTypeDiag,
10300 unsigned InvalidParamTypeDiag) {
10301 QualType ResultType =
10302 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10303
10304 // Check that the result type is not dependent.
10305 if (ResultType->isDependentType())
10306 return SemaRef.Diag(FnDecl->getLocation(),
10307 diag::err_operator_new_delete_dependent_result_type)
10308 << FnDecl->getDeclName() << ExpectedResultType;
10309
10310 // Check that the result type is what we expect.
10311 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10312 return SemaRef.Diag(FnDecl->getLocation(),
10313 diag::err_operator_new_delete_invalid_result_type)
10314 << FnDecl->getDeclName() << ExpectedResultType;
10315
10316 // A function template must have at least 2 parameters.
10317 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10318 return SemaRef.Diag(FnDecl->getLocation(),
10319 diag::err_operator_new_delete_template_too_few_parameters)
10320 << FnDecl->getDeclName();
10321
10322 // The function decl must have at least 1 parameter.
10323 if (FnDecl->getNumParams() == 0)
10324 return SemaRef.Diag(FnDecl->getLocation(),
10325 diag::err_operator_new_delete_too_few_parameters)
10326 << FnDecl->getDeclName();
10327
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010328 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010329 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10330 if (FirstParamType->isDependentType())
10331 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10332 << FnDecl->getDeclName() << ExpectedFirstParamType;
10333
10334 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010335 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010336 ExpectedFirstParamType)
10337 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10338 << FnDecl->getDeclName() << ExpectedFirstParamType;
10339
10340 return false;
10341}
10342
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010343static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010344CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010345 // C++ [basic.stc.dynamic.allocation]p1:
10346 // A program is ill-formed if an allocation function is declared in a
10347 // namespace scope other than global scope or declared static in global
10348 // scope.
10349 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10350 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010351
10352 CanQualType SizeTy =
10353 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10354
10355 // C++ [basic.stc.dynamic.allocation]p1:
10356 // The return type shall be void*. The first parameter shall have type
10357 // std::size_t.
10358 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10359 SizeTy,
10360 diag::err_operator_new_dependent_param_type,
10361 diag::err_operator_new_param_type))
10362 return true;
10363
10364 // C++ [basic.stc.dynamic.allocation]p1:
10365 // The first parameter shall not have an associated default argument.
10366 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010367 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010368 diag::err_operator_new_default_arg)
10369 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10370
10371 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010372}
10373
10374static bool
Richard Smith444d3842012-10-20 08:26:51 +000010375CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010376 // C++ [basic.stc.dynamic.deallocation]p1:
10377 // A program is ill-formed if deallocation functions are declared in a
10378 // namespace scope other than global scope or declared static in global
10379 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010380 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10381 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010382
10383 // C++ [basic.stc.dynamic.deallocation]p2:
10384 // Each deallocation function shall return void and its first parameter
10385 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010386 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10387 SemaRef.Context.VoidPtrTy,
10388 diag::err_operator_delete_dependent_param_type,
10389 diag::err_operator_delete_param_type))
10390 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010391
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010392 return false;
10393}
10394
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010395/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10396/// of this overloaded operator is well-formed. If so, returns false;
10397/// otherwise, emits appropriate diagnostics and returns true.
10398bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010399 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010400 "Expected an overloaded operator declaration");
10401
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010402 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10403
Mike Stump1eb44332009-09-09 15:08:12 +000010404 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010405 // The allocation and deallocation functions, operator new,
10406 // operator new[], operator delete and operator delete[], are
10407 // described completely in 3.7.3. The attributes and restrictions
10408 // found in the rest of this subclause do not apply to them unless
10409 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010410 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010411 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010412
Anders Carlssona3ccda52009-12-12 00:26:23 +000010413 if (Op == OO_New || Op == OO_Array_New)
10414 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010415
10416 // C++ [over.oper]p6:
10417 // An operator function shall either be a non-static member
10418 // function or be a non-member function and have at least one
10419 // parameter whose type is a class, a reference to a class, an
10420 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010421 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10422 if (MethodDecl->isStatic())
10423 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010424 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010425 } else {
10426 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010427 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10428 ParamEnd = FnDecl->param_end();
10429 Param != ParamEnd; ++Param) {
10430 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010431 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10432 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010433 ClassOrEnumParam = true;
10434 break;
10435 }
10436 }
10437
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010438 if (!ClassOrEnumParam)
10439 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010440 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010441 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010442 }
10443
10444 // C++ [over.oper]p8:
10445 // An operator function cannot have default arguments (8.3.6),
10446 // except where explicitly stated below.
10447 //
Mike Stump1eb44332009-09-09 15:08:12 +000010448 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010449 // (C++ [over.call]p1).
10450 if (Op != OO_Call) {
10451 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10452 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010453 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010454 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010455 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010456 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010457 }
10458 }
10459
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010460 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10461 { false, false, false }
10462#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10463 , { Unary, Binary, MemberOnly }
10464#include "clang/Basic/OperatorKinds.def"
10465 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010466
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010467 bool CanBeUnaryOperator = OperatorUses[Op][0];
10468 bool CanBeBinaryOperator = OperatorUses[Op][1];
10469 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010470
10471 // C++ [over.oper]p8:
10472 // [...] Operator functions cannot have more or fewer parameters
10473 // than the number required for the corresponding operator, as
10474 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010475 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010476 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010477 if (Op != OO_Call &&
10478 ((NumParams == 1 && !CanBeUnaryOperator) ||
10479 (NumParams == 2 && !CanBeBinaryOperator) ||
10480 (NumParams < 1) || (NumParams > 2))) {
10481 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010482 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010483 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010484 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010485 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010486 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010487 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010488 assert(CanBeBinaryOperator &&
10489 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010490 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010491 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010492
Chris Lattner416e46f2008-11-21 07:57:12 +000010493 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010494 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010495 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010496
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010497 // Overloaded operators other than operator() cannot be variadic.
10498 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010499 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010500 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010501 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010502 }
10503
10504 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010505 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10506 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010507 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010508 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010509 }
10510
10511 // C++ [over.inc]p1:
10512 // The user-defined function called operator++ implements the
10513 // prefix and postfix ++ operator. If this function is a member
10514 // function with no parameters, or a non-member function with one
10515 // parameter of class or enumeration type, it defines the prefix
10516 // increment operator ++ for objects of that type. If the function
10517 // is a member function with one parameter (which shall be of type
10518 // int) or a non-member function with two parameters (the second
10519 // of which shall be of type int), it defines the postfix
10520 // increment operator ++ for objects of that type.
10521 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10522 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10523 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010524 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010525 ParamIsInt = BT->getKind() == BuiltinType::Int;
10526
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010527 if (!ParamIsInt)
10528 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010529 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010530 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010531 }
10532
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010533 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010534}
Chris Lattner5a003a42008-12-17 07:09:26 +000010535
Sean Hunta6c058d2010-01-13 09:01:02 +000010536/// CheckLiteralOperatorDeclaration - Check whether the declaration
10537/// of this literal operator function is well-formed. If so, returns
10538/// false; otherwise, emits appropriate diagnostics and returns true.
10539bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010540 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010541 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10542 << FnDecl->getDeclName();
10543 return true;
10544 }
10545
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010546 if (FnDecl->isExternC()) {
10547 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10548 return true;
10549 }
10550
Sean Hunta6c058d2010-01-13 09:01:02 +000010551 bool Valid = false;
10552
Richard Smith36f5cfe2012-03-09 08:00:36 +000010553 // This might be the definition of a literal operator template.
10554 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10555 // This might be a specialization of a literal operator template.
10556 if (!TpDecl)
10557 TpDecl = FnDecl->getPrimaryTemplate();
10558
Sean Hunt216c2782010-04-07 23:11:06 +000010559 // template <char...> type operator "" name() is the only valid template
10560 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010561 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010562 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010563 // Must have only one template parameter
10564 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10565 if (Params->size() == 1) {
10566 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010567 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010568
Sean Hunt216c2782010-04-07 23:11:06 +000010569 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010570 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10571 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10572 Valid = true;
10573 }
10574 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010575 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010576 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010577 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10578
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010579 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010580
Sean Hunt30019c02010-04-07 22:57:35 +000010581 // unsigned long long int, long double, and any character type are allowed
10582 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010583 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10584 Context.hasSameType(T, Context.LongDoubleTy) ||
10585 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010586 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010587 Context.hasSameType(T, Context.Char16Ty) ||
10588 Context.hasSameType(T, Context.Char32Ty)) {
10589 if (++Param == FnDecl->param_end())
10590 Valid = true;
10591 goto FinishedParams;
10592 }
10593
Sean Hunt30019c02010-04-07 22:57:35 +000010594 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010595 const PointerType *PT = T->getAs<PointerType>();
10596 if (!PT)
10597 goto FinishedParams;
10598 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010599 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010600 goto FinishedParams;
10601 T = T.getUnqualifiedType();
10602
10603 // Move on to the second parameter;
10604 ++Param;
10605
10606 // If there is no second parameter, the first must be a const char *
10607 if (Param == FnDecl->param_end()) {
10608 if (Context.hasSameType(T, Context.CharTy))
10609 Valid = true;
10610 goto FinishedParams;
10611 }
10612
10613 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10614 // are allowed as the first parameter to a two-parameter function
10615 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010616 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010617 Context.hasSameType(T, Context.Char16Ty) ||
10618 Context.hasSameType(T, Context.Char32Ty)))
10619 goto FinishedParams;
10620
10621 // The second and final parameter must be an std::size_t
10622 T = (*Param)->getType().getUnqualifiedType();
10623 if (Context.hasSameType(T, Context.getSizeType()) &&
10624 ++Param == FnDecl->param_end())
10625 Valid = true;
10626 }
10627
10628 // FIXME: This diagnostic is absolutely terrible.
10629FinishedParams:
10630 if (!Valid) {
10631 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10632 << FnDecl->getDeclName();
10633 return true;
10634 }
10635
Richard Smitha9e88b22012-03-09 08:16:22 +000010636 // A parameter-declaration-clause containing a default argument is not
10637 // equivalent to any of the permitted forms.
10638 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10639 ParamEnd = FnDecl->param_end();
10640 Param != ParamEnd; ++Param) {
10641 if ((*Param)->hasDefaultArg()) {
10642 Diag((*Param)->getDefaultArgRange().getBegin(),
10643 diag::err_literal_operator_default_argument)
10644 << (*Param)->getDefaultArgRange();
10645 break;
10646 }
10647 }
10648
Richard Smith2fb4ae32012-03-08 02:39:21 +000010649 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010650 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10651 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010652 // C++11 [usrlit.suffix]p1:
10653 // Literal suffix identifiers that do not start with an underscore
10654 // are reserved for future standardization.
10655 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010656 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010657
Sean Hunta6c058d2010-01-13 09:01:02 +000010658 return false;
10659}
10660
Douglas Gregor074149e2009-01-05 19:45:36 +000010661/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10662/// linkage specification, including the language and (if present)
10663/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10664/// the location of the language string literal, which is provided
10665/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10666/// the '{' brace. Otherwise, this linkage specification does not
10667/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010668Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10669 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010670 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010671 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010672 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010673 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010674 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010675 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010676 Language = LinkageSpecDecl::lang_cxx;
10677 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010678 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010679 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010680 }
Mike Stump1eb44332009-09-09 15:08:12 +000010681
Chris Lattnercc98eac2008-12-17 07:13:27 +000010682 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010683
Douglas Gregor074149e2009-01-05 19:45:36 +000010684 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010685 ExternLoc, LangLoc, Language,
10686 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010687 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010688 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010689 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010690}
10691
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010692/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010693/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10694/// valid, it's the position of the closing '}' brace in a linkage
10695/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010696Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010697 Decl *LinkageSpec,
10698 SourceLocation RBraceLoc) {
10699 if (LinkageSpec) {
10700 if (RBraceLoc.isValid()) {
10701 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10702 LSDecl->setRBraceLoc(RBraceLoc);
10703 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010704 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010705 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010706 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010707}
10708
Michael Han684aa732013-02-22 17:15:32 +000010709Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10710 AttributeList *AttrList,
10711 SourceLocation SemiLoc) {
10712 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10713 // Attribute declarations appertain to empty declaration so we handle
10714 // them here.
10715 if (AttrList)
10716 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010717
Michael Han684aa732013-02-22 17:15:32 +000010718 CurContext->addDecl(ED);
10719 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010720}
10721
Douglas Gregord308e622009-05-18 20:51:54 +000010722/// \brief Perform semantic analysis for the variable declaration that
10723/// occurs within a C++ catch clause, returning the newly-created
10724/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010725VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010726 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010727 SourceLocation StartLoc,
10728 SourceLocation Loc,
10729 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010730 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010731 QualType ExDeclType = TInfo->getType();
10732
Sebastian Redl4b07b292008-12-22 19:15:10 +000010733 // Arrays and functions decay.
10734 if (ExDeclType->isArrayType())
10735 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10736 else if (ExDeclType->isFunctionType())
10737 ExDeclType = Context.getPointerType(ExDeclType);
10738
10739 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10740 // The exception-declaration shall not denote a pointer or reference to an
10741 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010742 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010743 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010744 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010745 Invalid = true;
10746 }
Douglas Gregord308e622009-05-18 20:51:54 +000010747
Sebastian Redl4b07b292008-12-22 19:15:10 +000010748 QualType BaseType = ExDeclType;
10749 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010750 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010751 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010752 BaseType = Ptr->getPointeeType();
10753 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010754 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010755 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010756 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010757 BaseType = Ref->getPointeeType();
10758 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010759 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010760 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010761 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010762 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010763 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010764
Mike Stump1eb44332009-09-09 15:08:12 +000010765 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010766 RequireNonAbstractType(Loc, ExDeclType,
10767 diag::err_abstract_type_in_decl,
10768 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010769 Invalid = true;
10770
John McCall5a180392010-07-24 00:37:23 +000010771 // Only the non-fragile NeXT runtime currently supports C++ catches
10772 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010773 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010774 QualType T = ExDeclType;
10775 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10776 T = RT->getPointeeType();
10777
10778 if (T->isObjCObjectType()) {
10779 Diag(Loc, diag::err_objc_object_catch);
10780 Invalid = true;
10781 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010782 // FIXME: should this be a test for macosx-fragile specifically?
10783 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010784 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010785 }
10786 }
10787
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010788 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010789 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010790 ExDecl->setExceptionVariable(true);
10791
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010792 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010793 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010794 Invalid = true;
10795
Douglas Gregorc41b8782011-07-06 18:14:43 +000010796 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010797 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010798 // Insulate this from anything else we might currently be parsing.
10799 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10800
Douglas Gregor6d182892010-03-05 23:38:39 +000010801 // C++ [except.handle]p16:
10802 // The object declared in an exception-declaration or, if the
10803 // exception-declaration does not specify a name, a temporary (12.2) is
10804 // copy-initialized (8.5) from the exception object. [...]
10805 // The object is destroyed when the handler exits, after the destruction
10806 // of any automatic objects initialized within the handler.
10807 //
10808 // We just pretend to initialize the object with itself, then make sure
10809 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010810 QualType initType = ExDeclType;
10811
10812 InitializedEntity entity =
10813 InitializedEntity::InitializeVariable(ExDecl);
10814 InitializationKind initKind =
10815 InitializationKind::CreateCopy(Loc, SourceLocation());
10816
10817 Expr *opaqueValue =
10818 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010819 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10820 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010821 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010822 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010823 else {
10824 // If the constructor used was non-trivial, set this as the
10825 // "initializer".
10826 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10827 if (!construct->getConstructor()->isTrivial()) {
10828 Expr *init = MaybeCreateExprWithCleanups(construct);
10829 ExDecl->setInit(init);
10830 }
10831
10832 // And make sure it's destructable.
10833 FinalizeVarWithDestructor(ExDecl, recordType);
10834 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010835 }
10836 }
10837
Douglas Gregord308e622009-05-18 20:51:54 +000010838 if (Invalid)
10839 ExDecl->setInvalidDecl();
10840
10841 return ExDecl;
10842}
10843
10844/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10845/// handler.
John McCalld226f652010-08-21 09:40:31 +000010846Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010847 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010848 bool Invalid = D.isInvalidType();
10849
10850 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010851 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10852 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010853 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10854 D.getIdentifierLoc());
10855 Invalid = true;
10856 }
10857
Sebastian Redl4b07b292008-12-22 19:15:10 +000010858 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010859 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010860 LookupOrdinaryName,
10861 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010862 // The scope should be freshly made just for us. There is just no way
10863 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010864 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010865 if (PrevDecl->isTemplateParameter()) {
10866 // Maybe we will complain about the shadowed template parameter.
10867 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010868 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010869 }
10870 }
10871
Chris Lattnereaaebc72009-04-25 08:06:05 +000010872 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010873 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10874 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010875 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010876 }
10877
Douglas Gregor83cb9422010-09-09 17:09:21 +000010878 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010879 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010880 D.getIdentifierLoc(),
10881 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010882 if (Invalid)
10883 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010884
Sebastian Redl4b07b292008-12-22 19:15:10 +000010885 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010886 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010887 PushOnScopeChains(ExDecl, S);
10888 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010889 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010890
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010891 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010892 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010893}
Anders Carlssonfb311762009-03-14 00:25:26 +000010894
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010895Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010896 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010897 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010898 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010899 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010900
Richard Smithe3f470a2012-07-11 22:37:56 +000010901 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10902 return 0;
10903
10904 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10905 AssertMessage, RParenLoc, false);
10906}
10907
10908Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10909 Expr *AssertExpr,
10910 StringLiteral *AssertMessage,
10911 SourceLocation RParenLoc,
10912 bool Failed) {
10913 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10914 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010915 // In a static_assert-declaration, the constant-expression shall be a
10916 // constant expression that can be contextually converted to bool.
10917 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10918 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010919 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010920
Richard Smithdaaefc52011-12-14 23:32:26 +000010921 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010922 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010923 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010924 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010925 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010926
Richard Smithe3f470a2012-07-11 22:37:56 +000010927 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010928 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010929 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010930 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010931 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010932 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010933 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010934 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010935 }
Mike Stump1eb44332009-09-09 15:08:12 +000010936
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010937 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010938 AssertExpr, AssertMessage, RParenLoc,
10939 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010940
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010941 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010942 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010943}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010944
Douglas Gregor1d869352010-04-07 16:53:43 +000010945/// \brief Perform semantic analysis of the given friend type declaration.
10946///
10947/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010948FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010949 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010950 TypeSourceInfo *TSInfo) {
10951 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10952
10953 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010954 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010955
Richard Smith6b130222011-10-18 21:39:00 +000010956 // C++03 [class.friend]p2:
10957 // An elaborated-type-specifier shall be used in a friend declaration
10958 // for a class.*
10959 //
10960 // * The class-key of the elaborated-type-specifier is required.
10961 if (!ActiveTemplateInstantiations.empty()) {
10962 // Do not complain about the form of friend template types during
10963 // template instantiation; we will already have complained when the
10964 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010965 } else {
10966 if (!T->isElaboratedTypeSpecifier()) {
10967 // If we evaluated the type to a record type, suggest putting
10968 // a tag in front.
10969 if (const RecordType *RT = T->getAs<RecordType>()) {
10970 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010971
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010972 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010973
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010974 Diag(TypeRange.getBegin(),
10975 getLangOpts().CPlusPlus11 ?
10976 diag::warn_cxx98_compat_unelaborated_friend_type :
10977 diag::ext_unelaborated_friend_type)
10978 << (unsigned) RD->getTagKind()
10979 << T
10980 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10981 InsertionText);
10982 } else {
10983 Diag(FriendLoc,
10984 getLangOpts().CPlusPlus11 ?
10985 diag::warn_cxx98_compat_nonclass_type_friend :
10986 diag::ext_nonclass_type_friend)
10987 << T
10988 << TypeRange;
10989 }
10990 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010991 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010992 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010993 diag::warn_cxx98_compat_enum_friend :
10994 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010995 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010996 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010997 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010998
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010999 // C++11 [class.friend]p3:
11000 // A friend declaration that does not declare a function shall have one
11001 // of the following forms:
11002 // friend elaborated-type-specifier ;
11003 // friend simple-type-specifier ;
11004 // friend typename-specifier ;
11005 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11006 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11007 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011008
Douglas Gregor06245bf2010-04-07 17:57:12 +000011009 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011010 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011011 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011012 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011013}
11014
John McCall9a34edb2010-10-19 01:40:49 +000011015/// Handle a friend tag declaration where the scope specifier was
11016/// templated.
11017Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11018 unsigned TagSpec, SourceLocation TagLoc,
11019 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011020 IdentifierInfo *Name,
11021 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011022 AttributeList *Attr,
11023 MultiTemplateParamsArg TempParamLists) {
11024 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11025
11026 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011027 bool Invalid = false;
11028
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011029 if (TemplateParameterList *TemplateParams =
11030 MatchTemplateParametersToScopeSpecifier(
11031 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11032 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011033 if (TemplateParams->size() > 0) {
11034 // This is a declaration of a class template.
11035 if (Invalid)
11036 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011037
Eric Christopher4110e132011-07-21 05:34:24 +000011038 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11039 SS, Name, NameLoc, Attr,
11040 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011041 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011042 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011043 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011044 } else {
11045 // The "template<>" header is extraneous.
11046 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11047 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11048 isExplicitSpecialization = true;
11049 }
11050 }
11051
11052 if (Invalid) return 0;
11053
John McCall9a34edb2010-10-19 01:40:49 +000011054 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011055 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011056 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011057 isAllExplicitSpecializations = false;
11058 break;
11059 }
11060 }
11061
11062 // FIXME: don't ignore attributes.
11063
11064 // If it's explicit specializations all the way down, just forget
11065 // about the template header and build an appropriate non-templated
11066 // friend. TODO: for source fidelity, remember the headers.
11067 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011068 if (SS.isEmpty()) {
11069 bool Owned = false;
11070 bool IsDependent = false;
11071 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11072 Attr, AS_public,
11073 /*ModulePrivateLoc=*/SourceLocation(),
11074 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011075 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011076 /*ScopedEnumUsesClassTag=*/false,
11077 /*UnderlyingType=*/TypeResult());
11078 }
11079
Douglas Gregor2494dd02011-03-01 01:34:45 +000011080 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011081 ElaboratedTypeKeyword Keyword
11082 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011083 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011084 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011085 if (T.isNull())
11086 return 0;
11087
11088 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11089 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011090 DependentNameTypeLoc TL =
11091 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011092 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011093 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011094 TL.setNameLoc(NameLoc);
11095 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011096 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011097 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011098 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011099 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011100 }
11101
11102 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011103 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011104 Friend->setAccess(AS_public);
11105 CurContext->addDecl(Friend);
11106 return Friend;
11107 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011108
11109 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11110
11111
John McCall9a34edb2010-10-19 01:40:49 +000011112
11113 // Handle the case of a templated-scope friend class. e.g.
11114 // template <class T> class A<T>::B;
11115 // FIXME: we don't support these right now.
11116 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11117 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11118 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011119 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011120 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011121 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011122 TL.setNameLoc(NameLoc);
11123
11124 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011125 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011126 Friend->setAccess(AS_public);
11127 Friend->setUnsupportedFriend(true);
11128 CurContext->addDecl(Friend);
11129 return Friend;
11130}
11131
11132
John McCalldd4a3b02009-09-16 22:47:08 +000011133/// Handle a friend type declaration. This works in tandem with
11134/// ActOnTag.
11135///
11136/// Notes on friend class templates:
11137///
11138/// We generally treat friend class declarations as if they were
11139/// declaring a class. So, for example, the elaborated type specifier
11140/// in a friend declaration is required to obey the restrictions of a
11141/// class-head (i.e. no typedefs in the scope chain), template
11142/// parameters are required to match up with simple template-ids, &c.
11143/// However, unlike when declaring a template specialization, it's
11144/// okay to refer to a template specialization without an empty
11145/// template parameter declaration, e.g.
11146/// friend class A<T>::B<unsigned>;
11147/// We permit this as a special case; if there are any template
11148/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011149/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011150Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011151 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011152 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011153
11154 assert(DS.isFriendSpecified());
11155 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11156
John McCalldd4a3b02009-09-16 22:47:08 +000011157 // Try to convert the decl specifier to a type. This works for
11158 // friend templates because ActOnTag never produces a ClassTemplateDecl
11159 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011160 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011161 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11162 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011163 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011164 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011165
Douglas Gregor6ccab972010-12-16 01:14:37 +000011166 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11167 return 0;
11168
John McCalldd4a3b02009-09-16 22:47:08 +000011169 // This is definitely an error in C++98. It's probably meant to
11170 // be forbidden in C++0x, too, but the specification is just
11171 // poorly written.
11172 //
11173 // The problem is with declarations like the following:
11174 // template <T> friend A<T>::foo;
11175 // where deciding whether a class C is a friend or not now hinges
11176 // on whether there exists an instantiation of A that causes
11177 // 'foo' to equal C. There are restrictions on class-heads
11178 // (which we declare (by fiat) elaborated friend declarations to
11179 // be) that makes this tractable.
11180 //
11181 // FIXME: handle "template <> friend class A<T>;", which
11182 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011183 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011184 Diag(Loc, diag::err_tagless_friend_type_template)
11185 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011186 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011187 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011188
John McCall02cace72009-08-28 07:59:38 +000011189 // C++98 [class.friend]p1: A friend of a class is a function
11190 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011191 // This is fixed in DR77, which just barely didn't make the C++03
11192 // deadline. It's also a very silly restriction that seriously
11193 // affects inner classes and which nobody else seems to implement;
11194 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011195 //
11196 // But note that we could warn about it: it's always useless to
11197 // friend one of your own members (it's not, however, worthless to
11198 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011199
John McCalldd4a3b02009-09-16 22:47:08 +000011200 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011201 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011202 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011203 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011204 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011205 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011206 DS.getFriendSpecLoc());
11207 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011208 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011209
11210 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011211 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011212
John McCalldd4a3b02009-09-16 22:47:08 +000011213 D->setAccess(AS_public);
11214 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011215
John McCalld226f652010-08-21 09:40:31 +000011216 return D;
John McCall02cace72009-08-28 07:59:38 +000011217}
11218
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011219NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11220 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011221 const DeclSpec &DS = D.getDeclSpec();
11222
11223 assert(DS.isFriendSpecified());
11224 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11225
11226 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011227 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011228
11229 // C++ [class.friend]p1
11230 // A friend of a class is a function or class....
11231 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011232 // It *doesn't* see through dependent types, which is correct
11233 // according to [temp.arg.type]p3:
11234 // If a declaration acquires a function type through a
11235 // type dependent on a template-parameter and this causes
11236 // a declaration that does not use the syntactic form of a
11237 // function declarator to have a function type, the program
11238 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011239 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011240 Diag(Loc, diag::err_unexpected_friend);
11241
11242 // It might be worthwhile to try to recover by creating an
11243 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011244 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011245 }
11246
11247 // C++ [namespace.memdef]p3
11248 // - If a friend declaration in a non-local class first declares a
11249 // class or function, the friend class or function is a member
11250 // of the innermost enclosing namespace.
11251 // - The name of the friend is not found by simple name lookup
11252 // until a matching declaration is provided in that namespace
11253 // scope (either before or after the class declaration granting
11254 // friendship).
11255 // - If a friend function is called, its name may be found by the
11256 // name lookup that considers functions from namespaces and
11257 // classes associated with the types of the function arguments.
11258 // - When looking for a prior declaration of a class or a function
11259 // declared as a friend, scopes outside the innermost enclosing
11260 // namespace scope are not considered.
11261
John McCall337ec3d2010-10-12 23:13:28 +000011262 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011263 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11264 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011265 assert(Name);
11266
Douglas Gregor6ccab972010-12-16 01:14:37 +000011267 // Check for unexpanded parameter packs.
11268 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11269 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11270 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11271 return 0;
11272
John McCall67d1a672009-08-06 02:15:43 +000011273 // The context we found the declaration in, or in which we should
11274 // create the declaration.
11275 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011276 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011277 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011278 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011279
John McCall337ec3d2010-10-12 23:13:28 +000011280 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011281
John McCall337ec3d2010-10-12 23:13:28 +000011282 // There are four cases here.
11283 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011284 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011285 // there as appropriate.
11286 // Recover from invalid scope qualifiers as if they just weren't there.
11287 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011288 // C++0x [namespace.memdef]p3:
11289 // If the name in a friend declaration is neither qualified nor
11290 // a template-id and the declaration is a function or an
11291 // elaborated-type-specifier, the lookup to determine whether
11292 // the entity has been previously declared shall not consider
11293 // any scopes outside the innermost enclosing namespace.
11294 // C++0x [class.friend]p11:
11295 // If a friend declaration appears in a local class and the name
11296 // specified is an unqualified name, a prior declaration is
11297 // looked up without considering scopes that are outside the
11298 // innermost enclosing non-class scope. For a friend function
11299 // declaration, if there is no prior declaration, the program is
11300 // ill-formed.
11301 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011302 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011303
John McCall29ae6e52010-10-13 05:45:15 +000011304 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011305 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011306
Rafael Espindola11dc6342013-04-25 20:12:36 +000011307 // Skip class contexts. If someone can cite chapter and verse
11308 // for this behavior, that would be nice --- it's what GCC and
11309 // EDG do, and it seems like a reasonable intent, but the spec
11310 // really only says that checks for unqualified existing
11311 // declarations should stop at the nearest enclosing namespace,
11312 // not that they should only consider the nearest enclosing
11313 // namespace.
11314 while (DC->isRecord())
11315 DC = DC->getParent();
11316
11317 DeclContext *LookupDC = DC;
11318 while (LookupDC->isTransparentContext())
11319 LookupDC = LookupDC->getParent();
11320
11321 while (true) {
11322 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011323
11324 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011325 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011326 break;
John McCall29ae6e52010-10-13 05:45:15 +000011327
Rafael Espindola11dc6342013-04-25 20:12:36 +000011328 if (!Previous.empty()) {
11329 DC = LookupDC;
11330 break;
John McCall8a407372010-10-14 22:22:28 +000011331 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011332
11333 if (isTemplateId) {
11334 if (isa<TranslationUnitDecl>(LookupDC)) break;
11335 } else {
11336 if (LookupDC->isFileContext()) break;
11337 }
11338 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011339 }
11340
John McCall380aaa42010-10-13 06:22:15 +000011341 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011342
Douglas Gregor883af832011-10-10 01:11:59 +000011343 // C++ [class.friend]p6:
11344 // A function can be defined in a friend declaration of a class if and
11345 // only if the class is a non-local class (9.8), the function name is
11346 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011347 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011348 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11349 }
11350
John McCall337ec3d2010-10-12 23:13:28 +000011351 // - There's a non-dependent scope specifier, in which case we
11352 // compute it and do a previous lookup there for a function
11353 // or function template.
11354 } else if (!SS.getScopeRep()->isDependent()) {
11355 DC = computeDeclContext(SS);
11356 if (!DC) return 0;
11357
11358 if (RequireCompleteDeclContext(SS, DC)) return 0;
11359
11360 LookupQualifiedName(Previous, DC);
11361
11362 // Ignore things found implicitly in the wrong scope.
11363 // TODO: better diagnostics for this case. Suggesting the right
11364 // qualified scope would be nice...
11365 LookupResult::Filter F = Previous.makeFilter();
11366 while (F.hasNext()) {
11367 NamedDecl *D = F.next();
11368 if (!DC->InEnclosingNamespaceSetOf(
11369 D->getDeclContext()->getRedeclContext()))
11370 F.erase();
11371 }
11372 F.done();
11373
11374 if (Previous.empty()) {
11375 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011376 Diag(Loc, diag::err_qualified_friend_not_found)
11377 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011378 return 0;
11379 }
11380
11381 // C++ [class.friend]p1: A friend of a class is a function or
11382 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011383 if (DC->Equals(CurContext))
11384 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011385 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011386 diag::warn_cxx98_compat_friend_is_member :
11387 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011388
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011389 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011390 // C++ [class.friend]p6:
11391 // A function can be defined in a friend declaration of a class if and
11392 // only if the class is a non-local class (9.8), the function name is
11393 // unqualified, and the function has namespace scope.
11394 SemaDiagnosticBuilder DB
11395 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11396
11397 DB << SS.getScopeRep();
11398 if (DC->isFileContext())
11399 DB << FixItHint::CreateRemoval(SS.getRange());
11400 SS.clear();
11401 }
John McCall337ec3d2010-10-12 23:13:28 +000011402
11403 // - There's a scope specifier that does not match any template
11404 // parameter lists, in which case we use some arbitrary context,
11405 // create a method or method template, and wait for instantiation.
11406 // - There's a scope specifier that does match some template
11407 // parameter lists, which we don't handle right now.
11408 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011409 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011410 // C++ [class.friend]p6:
11411 // A function can be defined in a friend declaration of a class if and
11412 // only if the class is a non-local class (9.8), the function name is
11413 // unqualified, and the function has namespace scope.
11414 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11415 << SS.getScopeRep();
11416 }
11417
John McCall337ec3d2010-10-12 23:13:28 +000011418 DC = CurContext;
11419 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011420 }
Douglas Gregor883af832011-10-10 01:11:59 +000011421
John McCall29ae6e52010-10-13 05:45:15 +000011422 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011423 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011424 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11425 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11426 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011427 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011428 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11429 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011430 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011431 }
John McCall67d1a672009-08-06 02:15:43 +000011432 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011433
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011434 // FIXME: This is an egregious hack to cope with cases where the scope stack
11435 // does not contain the declaration context, i.e., in an out-of-line
11436 // definition of a class.
11437 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11438 if (!DCScope) {
11439 FakeDCScope.setEntity(DC);
11440 DCScope = &FakeDCScope;
11441 }
11442
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011443 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011444 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011445 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011446 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011447
Douglas Gregor182ddf02009-09-28 00:08:27 +000011448 assert(ND->getDeclContext() == DC);
11449 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011450
John McCallab88d972009-08-31 22:39:49 +000011451 // Add the function declaration to the appropriate lookup tables,
11452 // adjusting the redeclarations list as necessary. We don't
11453 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011454 //
John McCallab88d972009-08-31 22:39:49 +000011455 // Also update the scope-based lookup if the target context's
11456 // lookup context is in lexical scope.
11457 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011458 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011459 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011460 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011461 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011462 }
John McCall02cace72009-08-28 07:59:38 +000011463
11464 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011465 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011466 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011467 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011468 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011469
John McCall1f2e1a92012-08-10 03:15:35 +000011470 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011471 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011472 } else {
11473 if (DC->isRecord()) CheckFriendAccess(ND);
11474
John McCall6102ca12010-10-16 06:59:13 +000011475 FunctionDecl *FD;
11476 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11477 FD = FTD->getTemplatedDecl();
11478 else
11479 FD = cast<FunctionDecl>(ND);
11480
David Majnemerf6a144f2013-06-25 23:09:30 +000011481 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11482 // default argument expression, that declaration shall be a definition
11483 // and shall be the only declaration of the function or function
11484 // template in the translation unit.
11485 if (functionDeclHasDefaultArgument(FD)) {
11486 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11487 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11488 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11489 } else if (!D.isFunctionDefinition())
11490 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11491 }
11492
John McCall6102ca12010-10-16 06:59:13 +000011493 // Mark templated-scope function declarations as unsupported.
11494 if (FD->getNumTemplateParameterLists())
11495 FrD->setUnsupportedFriend(true);
11496 }
John McCall337ec3d2010-10-12 23:13:28 +000011497
John McCalld226f652010-08-21 09:40:31 +000011498 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011499}
11500
John McCalld226f652010-08-21 09:40:31 +000011501void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11502 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011503
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011504 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011505 if (!Fn) {
11506 Diag(DelLoc, diag::err_deleted_non_function);
11507 return;
11508 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011509
Douglas Gregoref96ee02012-01-14 16:38:05 +000011510 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011511 // Don't consider the implicit declaration we generate for explicit
11512 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011513 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11514 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011515 Diag(DelLoc, diag::err_deleted_decl_not_first);
11516 Diag(Prev->getLocation(), diag::note_previous_declaration);
11517 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011518 // If the declaration wasn't the first, we delete the function anyway for
11519 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011520 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011521 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011522
11523 if (Fn->isDeleted())
11524 return;
11525
11526 // See if we're deleting a function which is already known to override a
11527 // non-deleted virtual function.
11528 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11529 bool IssuedDiagnostic = false;
11530 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11531 E = MD->end_overridden_methods();
11532 I != E; ++I) {
11533 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11534 if (!IssuedDiagnostic) {
11535 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11536 IssuedDiagnostic = true;
11537 }
11538 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11539 }
11540 }
11541 }
11542
Sean Hunt10620eb2011-05-06 20:44:56 +000011543 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011544}
Sebastian Redl13e88542009-04-27 21:33:24 +000011545
Sean Hunte4246a62011-05-12 06:15:49 +000011546void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011547 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011548
11549 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011550 if (MD->getParent()->isDependentType()) {
11551 MD->setDefaulted();
11552 MD->setExplicitlyDefaulted();
11553 return;
11554 }
11555
Sean Hunte4246a62011-05-12 06:15:49 +000011556 CXXSpecialMember Member = getSpecialMember(MD);
11557 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011558 if (!MD->isInvalidDecl())
11559 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000011560 return;
11561 }
11562
11563 MD->setDefaulted();
11564 MD->setExplicitlyDefaulted();
11565
Sean Huntcd10dec2011-05-23 23:14:04 +000011566 // If this definition appears within the record, do the checking when
11567 // the record is complete.
11568 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011569 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011570 // Find the uninstantiated declaration that actually had the '= default'
11571 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011572 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011573
Richard Smith12fef492013-03-27 00:22:47 +000011574 // If the method was defaulted on its first declaration, we will have
11575 // already performed the checking in CheckCompletedCXXClass. Such a
11576 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011577 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011578 return;
11579
Richard Smithb9d0b762012-07-27 04:22:15 +000011580 CheckExplicitlyDefaultedSpecialMember(MD);
11581
Richard Smith1d28caf2012-12-11 01:14:52 +000011582 // The exception specification is needed because we are defining the
11583 // function.
11584 ResolveExceptionSpec(DefaultLoc,
11585 MD->getType()->castAs<FunctionProtoType>());
11586
Sean Hunte4246a62011-05-12 06:15:49 +000011587 switch (Member) {
11588 case CXXDefaultConstructor: {
11589 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011590 if (!CD->isInvalidDecl())
11591 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11592 break;
11593 }
11594
11595 case CXXCopyConstructor: {
11596 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011597 if (!CD->isInvalidDecl())
11598 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011599 break;
11600 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011601
Sean Hunt2b188082011-05-14 05:23:28 +000011602 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011603 if (!MD->isInvalidDecl())
11604 DefineImplicitCopyAssignment(DefaultLoc, MD);
11605 break;
11606 }
11607
Sean Huntcb45a0f2011-05-12 22:46:25 +000011608 case CXXDestructor: {
11609 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011610 if (!DD->isInvalidDecl())
11611 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011612 break;
11613 }
11614
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011615 case CXXMoveConstructor: {
11616 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011617 if (!CD->isInvalidDecl())
11618 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011619 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011620 }
Sean Hunt82713172011-05-25 23:16:36 +000011621
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011622 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011623 if (!MD->isInvalidDecl())
11624 DefineImplicitMoveAssignment(DefaultLoc, MD);
11625 break;
11626 }
11627
11628 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011629 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011630 }
11631 } else {
11632 Diag(DefaultLoc, diag::err_default_special_members);
11633 }
11634}
11635
Sebastian Redl13e88542009-04-27 21:33:24 +000011636static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011637 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011638 Stmt *SubStmt = *CI;
11639 if (!SubStmt)
11640 continue;
11641 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011642 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011643 diag::err_return_in_constructor_handler);
11644 if (!isa<Expr>(SubStmt))
11645 SearchForReturnInStmt(Self, SubStmt);
11646 }
11647}
11648
11649void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11650 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11651 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11652 SearchForReturnInStmt(*this, Handler);
11653 }
11654}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011655
David Blaikie299adab2013-01-18 23:03:15 +000011656bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011657 const CXXMethodDecl *Old) {
11658 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11659 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11660
11661 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11662
11663 // If the calling conventions match, everything is fine
11664 if (NewCC == OldCC)
11665 return false;
11666
11667 // If either of the calling conventions are set to "default", we need to pick
11668 // something more sensible based on the target. This supports code where the
11669 // one method explicitly sets thiscall, and another has no explicit calling
11670 // convention.
11671 CallingConv Default =
11672 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11673 if (NewCC == CC_Default)
11674 NewCC = Default;
11675 if (OldCC == CC_Default)
11676 OldCC = Default;
11677
11678 // If the calling conventions still don't match, then report the error
11679 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011680 Diag(New->getLocation(),
11681 diag::err_conflicting_overriding_cc_attributes)
11682 << New->getDeclName() << New->getType() << Old->getType();
11683 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11684 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011685 }
11686
11687 return false;
11688}
11689
Mike Stump1eb44332009-09-09 15:08:12 +000011690bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011691 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011692 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11693 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011694
Chandler Carruth73857792010-02-15 11:53:20 +000011695 if (Context.hasSameType(NewTy, OldTy) ||
11696 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011697 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011698
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011699 // Check if the return types are covariant
11700 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011701
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011702 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011703 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11704 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011705 NewClassTy = NewPT->getPointeeType();
11706 OldClassTy = OldPT->getPointeeType();
11707 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011708 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11709 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11710 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11711 NewClassTy = NewRT->getPointeeType();
11712 OldClassTy = OldRT->getPointeeType();
11713 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011714 }
11715 }
Mike Stump1eb44332009-09-09 15:08:12 +000011716
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011717 // The return types aren't either both pointers or references to a class type.
11718 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011719 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011720 diag::err_different_return_type_for_overriding_virtual_function)
11721 << New->getDeclName() << NewTy << OldTy;
11722 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011723
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011724 return true;
11725 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011726
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011727 // C++ [class.virtual]p6:
11728 // If the return type of D::f differs from the return type of B::f, the
11729 // class type in the return type of D::f shall be complete at the point of
11730 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011731 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11732 if (!RT->isBeingDefined() &&
11733 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011734 diag::err_covariant_return_incomplete,
11735 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011736 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011737 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011738
Douglas Gregora4923eb2009-11-16 21:35:15 +000011739 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011740 // Check if the new class derives from the old class.
11741 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11742 Diag(New->getLocation(),
11743 diag::err_covariant_return_not_derived)
11744 << New->getDeclName() << NewTy << OldTy;
11745 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11746 return true;
11747 }
Mike Stump1eb44332009-09-09 15:08:12 +000011748
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011749 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011750 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011751 diag::err_covariant_return_inaccessible_base,
11752 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11753 // FIXME: Should this point to the return type?
11754 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011755 // FIXME: this note won't trigger for delayed access control
11756 // diagnostics, and it's impossible to get an undelayed error
11757 // here from access control during the original parse because
11758 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011759 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11760 return true;
11761 }
11762 }
Mike Stump1eb44332009-09-09 15:08:12 +000011763
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011764 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011765 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011766 Diag(New->getLocation(),
11767 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011768 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011769 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11770 return true;
11771 };
Mike Stump1eb44332009-09-09 15:08:12 +000011772
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011773
11774 // The new class type must have the same or less qualifiers as the old type.
11775 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11776 Diag(New->getLocation(),
11777 diag::err_covariant_return_type_class_type_more_qualified)
11778 << New->getDeclName() << NewTy << OldTy;
11779 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11780 return true;
11781 };
Mike Stump1eb44332009-09-09 15:08:12 +000011782
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011783 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011784}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011785
Douglas Gregor4ba31362009-12-01 17:24:26 +000011786/// \brief Mark the given method pure.
11787///
11788/// \param Method the method to be marked pure.
11789///
11790/// \param InitRange the source range that covers the "0" initializer.
11791bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011792 SourceLocation EndLoc = InitRange.getEnd();
11793 if (EndLoc.isValid())
11794 Method->setRangeEnd(EndLoc);
11795
Douglas Gregor4ba31362009-12-01 17:24:26 +000011796 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11797 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011798 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011799 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011800
11801 if (!Method->isInvalidDecl())
11802 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11803 << Method->getDeclName() << InitRange;
11804 return true;
11805}
11806
Douglas Gregor552e2992012-02-21 02:22:07 +000011807/// \brief Determine whether the given declaration is a static data member.
11808static bool isStaticDataMember(Decl *D) {
11809 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11810 if (!Var)
11811 return false;
11812
11813 return Var->isStaticDataMember();
11814}
John McCall731ad842009-12-19 09:28:58 +000011815/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11816/// an initializer for the out-of-line declaration 'Dcl'. The scope
11817/// is a fresh scope pushed for just this purpose.
11818///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011819/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11820/// static data member of class X, names should be looked up in the scope of
11821/// class X.
John McCalld226f652010-08-21 09:40:31 +000011822void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011823 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011824 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011825
John McCall731ad842009-12-19 09:28:58 +000011826 // We should only get called for declarations with scope specifiers, like:
11827 // int foo::bar;
11828 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011829 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011830
11831 // If we are parsing the initializer for a static data member, push a
11832 // new expression evaluation context that is associated with this static
11833 // data member.
11834 if (isStaticDataMember(D))
11835 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011836}
11837
11838/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011839/// initializer for the out-of-line declaration 'D'.
11840void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011841 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011842 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011843
Douglas Gregor552e2992012-02-21 02:22:07 +000011844 if (isStaticDataMember(D))
11845 PopExpressionEvaluationContext();
11846
John McCall731ad842009-12-19 09:28:58 +000011847 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011848 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011849}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011850
11851/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11852/// C++ if/switch/while/for statement.
11853/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011854DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011855 // C++ 6.4p2:
11856 // The declarator shall not specify a function or an array.
11857 // The type-specifier-seq shall not contain typedef and shall not declare a
11858 // new class or enumeration.
11859 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11860 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011861
11862 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011863 if (!Dcl)
11864 return true;
11865
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011866 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11867 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011868 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011869 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011870 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011871
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011872 return Dcl;
11873}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011874
Douglas Gregordfe65432011-07-28 19:11:31 +000011875void Sema::LoadExternalVTableUses() {
11876 if (!ExternalSource)
11877 return;
11878
11879 SmallVector<ExternalVTableUse, 4> VTables;
11880 ExternalSource->ReadUsedVTables(VTables);
11881 SmallVector<VTableUse, 4> NewUses;
11882 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11883 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11884 = VTablesUsed.find(VTables[I].Record);
11885 // Even if a definition wasn't required before, it may be required now.
11886 if (Pos != VTablesUsed.end()) {
11887 if (!Pos->second && VTables[I].DefinitionRequired)
11888 Pos->second = true;
11889 continue;
11890 }
11891
11892 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11893 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11894 }
11895
11896 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11897}
11898
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011899void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11900 bool DefinitionRequired) {
11901 // Ignore any vtable uses in unevaluated operands or for classes that do
11902 // not have a vtable.
11903 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011904 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011905 return;
11906
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011907 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011908 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011909 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11910 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11911 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11912 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011913 // If we already had an entry, check to see if we are promoting this vtable
11914 // to required a definition. If so, we need to reappend to the VTableUses
11915 // list, since we may have already processed the first entry.
11916 if (DefinitionRequired && !Pos.first->second) {
11917 Pos.first->second = true;
11918 } else {
11919 // Otherwise, we can early exit.
11920 return;
11921 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011922 }
11923
11924 // Local classes need to have their virtual members marked
11925 // immediately. For all other classes, we mark their virtual members
11926 // at the end of the translation unit.
11927 if (Class->isLocalClass())
11928 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011929 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011930 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011931}
11932
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011933bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011934 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011935 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011936 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011937
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011938 // Note: The VTableUses vector could grow as a result of marking
11939 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011940 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011941 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011942 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011943 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011944 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011945 if (!Class)
11946 continue;
11947
11948 SourceLocation Loc = VTableUses[I].second;
11949
Richard Smithb9d0b762012-07-27 04:22:15 +000011950 bool DefineVTable = true;
11951
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011952 // If this class has a key function, but that key function is
11953 // defined in another translation unit, we don't need to emit the
11954 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011955 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011956 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011957 switch (KeyFunction->getTemplateSpecializationKind()) {
11958 case TSK_Undeclared:
11959 case TSK_ExplicitSpecialization:
11960 case TSK_ExplicitInstantiationDeclaration:
11961 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011962 DefineVTable = false;
11963 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011964
11965 case TSK_ExplicitInstantiationDefinition:
11966 case TSK_ImplicitInstantiation:
11967 // We will be instantiating the key function.
11968 break;
11969 }
11970 } else if (!KeyFunction) {
11971 // If we have a class with no key function that is the subject
11972 // of an explicit instantiation declaration, suppress the
11973 // vtable; it will live with the explicit instantiation
11974 // definition.
11975 bool IsExplicitInstantiationDeclaration
11976 = Class->getTemplateSpecializationKind()
11977 == TSK_ExplicitInstantiationDeclaration;
11978 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11979 REnd = Class->redecls_end();
11980 R != REnd; ++R) {
11981 TemplateSpecializationKind TSK
11982 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11983 if (TSK == TSK_ExplicitInstantiationDeclaration)
11984 IsExplicitInstantiationDeclaration = true;
11985 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11986 IsExplicitInstantiationDeclaration = false;
11987 break;
11988 }
11989 }
11990
11991 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011992 DefineVTable = false;
11993 }
11994
11995 // The exception specifications for all virtual members may be needed even
11996 // if we are not providing an authoritative form of the vtable in this TU.
11997 // We may choose to emit it available_externally anyway.
11998 if (!DefineVTable) {
11999 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12000 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012001 }
12002
12003 // Mark all of the virtual members of this class as referenced, so
12004 // that we can build a vtable. Then, tell the AST consumer that a
12005 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012006 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012007 MarkVirtualMembersReferenced(Loc, Class);
12008 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12009 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12010
12011 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012012 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012013 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000012014 const FunctionDecl *KeyFunctionDef = 0;
12015 if (!KeyFunction ||
12016 (KeyFunction->hasBody(KeyFunctionDef) &&
12017 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012018 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12019 TSK_ExplicitInstantiationDefinition
12020 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12021 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012022 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012023 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012024 VTableUses.clear();
12025
Douglas Gregor78844032011-04-22 22:25:37 +000012026 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012027}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012028
Richard Smithb9d0b762012-07-27 04:22:15 +000012029void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12030 const CXXRecordDecl *RD) {
12031 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12032 E = RD->method_end(); I != E; ++I)
12033 if ((*I)->isVirtual() && !(*I)->isPure())
12034 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12035}
12036
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012037void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12038 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012039 // Mark all functions which will appear in RD's vtable as used.
12040 CXXFinalOverriderMap FinalOverriders;
12041 RD->getFinalOverriders(FinalOverriders);
12042 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12043 E = FinalOverriders.end();
12044 I != E; ++I) {
12045 for (OverridingMethods::const_iterator OI = I->second.begin(),
12046 OE = I->second.end();
12047 OI != OE; ++OI) {
12048 assert(OI->second.size() > 0 && "no final overrider");
12049 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012050
Richard Smithff817f72012-07-07 06:59:51 +000012051 // C++ [basic.def.odr]p2:
12052 // [...] A virtual member function is used if it is not pure. [...]
12053 if (!Overrider->isPure())
12054 MarkFunctionReferenced(Loc, Overrider);
12055 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012056 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012057
12058 // Only classes that have virtual bases need a VTT.
12059 if (RD->getNumVBases() == 0)
12060 return;
12061
12062 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12063 e = RD->bases_end(); i != e; ++i) {
12064 const CXXRecordDecl *Base =
12065 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012066 if (Base->getNumVBases() == 0)
12067 continue;
12068 MarkVirtualMembersReferenced(Loc, Base);
12069 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012070}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012071
12072/// SetIvarInitializers - This routine builds initialization ASTs for the
12073/// Objective-C implementation whose ivars need be initialized.
12074void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012075 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012076 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012077 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012078 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012079 CollectIvarsToConstructOrDestruct(OID, ivars);
12080 if (ivars.empty())
12081 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012082 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012083 for (unsigned i = 0; i < ivars.size(); i++) {
12084 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012085 if (Field->isInvalidDecl())
12086 continue;
12087
Sean Huntcbb67482011-01-08 20:30:50 +000012088 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012089 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12090 InitializationKind InitKind =
12091 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012092
12093 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12094 ExprResult MemberInit =
12095 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012096 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012097 // Note, MemberInit could actually come back empty if no initialization
12098 // is required (e.g., because it would call a trivial default constructor)
12099 if (!MemberInit.get() || MemberInit.isInvalid())
12100 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012101
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012102 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012103 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12104 SourceLocation(),
12105 MemberInit.takeAs<Expr>(),
12106 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012107 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012108
12109 // Be sure that the destructor is accessible and is marked as referenced.
12110 if (const RecordType *RecordTy
12111 = Context.getBaseElementType(Field->getType())
12112 ->getAs<RecordType>()) {
12113 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012114 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012115 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012116 CheckDestructorAccess(Field->getLocation(), Destructor,
12117 PDiag(diag::err_access_dtor_ivar)
12118 << Context.getBaseElementType(Field->getType()));
12119 }
12120 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012121 }
12122 ObjCImplementation->setIvarInitializers(Context,
12123 AllToInit.data(), AllToInit.size());
12124 }
12125}
Sean Huntfe57eef2011-05-04 05:57:24 +000012126
Sean Huntebcbe1d2011-05-04 23:29:54 +000012127static
12128void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12129 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12130 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12131 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12132 Sema &S) {
12133 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12134 CE = Current.end();
12135 if (Ctor->isInvalidDecl())
12136 return;
12137
Richard Smitha8eaf002012-08-23 06:16:52 +000012138 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12139
12140 // Target may not be determinable yet, for instance if this is a dependent
12141 // call in an uninstantiated template.
12142 if (Target) {
12143 const FunctionDecl *FNTarget = 0;
12144 (void)Target->hasBody(FNTarget);
12145 Target = const_cast<CXXConstructorDecl*>(
12146 cast_or_null<CXXConstructorDecl>(FNTarget));
12147 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012148
12149 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12150 // Avoid dereferencing a null pointer here.
12151 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12152
12153 if (!Current.insert(Canonical))
12154 return;
12155
12156 // We know that beyond here, we aren't chaining into a cycle.
12157 if (!Target || !Target->isDelegatingConstructor() ||
12158 Target->isInvalidDecl() || Valid.count(TCanonical)) {
12159 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12160 Valid.insert(*CI);
12161 Current.clear();
12162 // We've hit a cycle.
12163 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12164 Current.count(TCanonical)) {
12165 // If we haven't diagnosed this cycle yet, do so now.
12166 if (!Invalid.count(TCanonical)) {
12167 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012168 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012169 << Ctor;
12170
Richard Smitha8eaf002012-08-23 06:16:52 +000012171 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012172 if (TCanonical != Canonical)
12173 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12174
12175 CXXConstructorDecl *C = Target;
12176 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012177 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012178 (void)C->getTargetConstructor()->hasBody(FNTarget);
12179 assert(FNTarget && "Ctor cycle through bodiless function");
12180
Richard Smitha8eaf002012-08-23 06:16:52 +000012181 C = const_cast<CXXConstructorDecl*>(
12182 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012183 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12184 }
12185 }
12186
12187 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12188 Invalid.insert(*CI);
12189 Current.clear();
12190 } else {
12191 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12192 }
12193}
12194
12195
Sean Huntfe57eef2011-05-04 05:57:24 +000012196void Sema::CheckDelegatingCtorCycles() {
12197 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12198
Sean Huntebcbe1d2011-05-04 23:29:54 +000012199 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12200 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000012201
Douglas Gregor0129b562011-07-27 21:57:17 +000012202 for (DelegatingCtorDeclsType::iterator
12203 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012204 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012205 I != E; ++I)
12206 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012207
12208 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12209 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012210}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012211
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012212namespace {
12213 /// \brief AST visitor that finds references to the 'this' expression.
12214 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12215 Sema &S;
12216
12217 public:
12218 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12219
12220 bool VisitCXXThisExpr(CXXThisExpr *E) {
12221 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12222 << E->isImplicit();
12223 return false;
12224 }
12225 };
12226}
12227
12228bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12229 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12230 if (!TSInfo)
12231 return false;
12232
12233 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012234 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012235 if (!ProtoTL)
12236 return false;
12237
12238 // C++11 [expr.prim.general]p3:
12239 // [The expression this] shall not appear before the optional
12240 // cv-qualifier-seq and it shall not appear within the declaration of a
12241 // static member function (although its type and value category are defined
12242 // within a static member function as they are within a non-static member
12243 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012244 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012245 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012246 FindCXXThisExpr Finder(*this);
12247
12248 // If the return type came after the cv-qualifier-seq, check it now.
12249 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012250 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012251 return true;
12252
12253 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012254 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12255 return true;
12256
12257 return checkThisInStaticMemberFunctionAttributes(Method);
12258}
12259
12260bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12261 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12262 if (!TSInfo)
12263 return false;
12264
12265 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012266 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012267 if (!ProtoTL)
12268 return false;
12269
David Blaikie39e6ab42013-02-18 22:06:02 +000012270 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012271 FindCXXThisExpr Finder(*this);
12272
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012273 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012274 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012275 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012276 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012277 case EST_DynamicNone:
12278 case EST_MSAny:
12279 case EST_None:
12280 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012281
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012282 case EST_ComputedNoexcept:
12283 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12284 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012285
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012286 case EST_Dynamic:
12287 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012288 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012289 E != EEnd; ++E) {
12290 if (!Finder.TraverseType(*E))
12291 return true;
12292 }
12293 break;
12294 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012295
12296 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012297}
12298
12299bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12300 FindCXXThisExpr Finder(*this);
12301
12302 // Check attributes.
12303 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12304 A != AEnd; ++A) {
12305 // FIXME: This should be emitted by tblgen.
12306 Expr *Arg = 0;
12307 ArrayRef<Expr *> Args;
12308 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12309 Arg = G->getArg();
12310 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12311 Arg = G->getArg();
12312 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12313 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12314 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12315 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12316 else if (ExclusiveLockFunctionAttr *ELF
12317 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12318 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12319 else if (SharedLockFunctionAttr *SLF
12320 = dyn_cast<SharedLockFunctionAttr>(*A))
12321 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12322 else if (ExclusiveTrylockFunctionAttr *ETLF
12323 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12324 Arg = ETLF->getSuccessValue();
12325 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12326 } else if (SharedTrylockFunctionAttr *STLF
12327 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12328 Arg = STLF->getSuccessValue();
12329 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12330 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12331 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12332 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12333 Arg = LR->getArg();
12334 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12335 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12336 else if (ExclusiveLocksRequiredAttr *ELR
12337 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12338 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12339 else if (SharedLocksRequiredAttr *SLR
12340 = dyn_cast<SharedLocksRequiredAttr>(*A))
12341 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12342
12343 if (Arg && !Finder.TraverseStmt(Arg))
12344 return true;
12345
12346 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12347 if (!Finder.TraverseStmt(Args[I]))
12348 return true;
12349 }
12350 }
12351
12352 return false;
12353}
12354
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012355void
12356Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12357 ArrayRef<ParsedType> DynamicExceptions,
12358 ArrayRef<SourceRange> DynamicExceptionRanges,
12359 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012360 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012361 FunctionProtoType::ExtProtoInfo &EPI) {
12362 Exceptions.clear();
12363 EPI.ExceptionSpecType = EST;
12364 if (EST == EST_Dynamic) {
12365 Exceptions.reserve(DynamicExceptions.size());
12366 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12367 // FIXME: Preserve type source info.
12368 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12369
12370 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12371 collectUnexpandedParameterPacks(ET, Unexpanded);
12372 if (!Unexpanded.empty()) {
12373 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12374 UPPC_ExceptionType,
12375 Unexpanded);
12376 continue;
12377 }
12378
12379 // Check that the type is valid for an exception spec, and
12380 // drop it if not.
12381 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12382 Exceptions.push_back(ET);
12383 }
12384 EPI.NumExceptions = Exceptions.size();
12385 EPI.Exceptions = Exceptions.data();
12386 return;
12387 }
12388
12389 if (EST == EST_ComputedNoexcept) {
12390 // If an error occurred, there's no expression here.
12391 if (NoexceptExpr) {
12392 assert((NoexceptExpr->isTypeDependent() ||
12393 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12394 Context.BoolTy) &&
12395 "Parser should have made sure that the expression is boolean");
12396 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12397 EPI.ExceptionSpecType = EST_BasicNoexcept;
12398 return;
12399 }
12400
12401 if (!NoexceptExpr->isValueDependent())
12402 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012403 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012404 /*AllowFold*/ false).take();
12405 EPI.NoexceptExpr = NoexceptExpr;
12406 }
12407 return;
12408 }
12409}
12410
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012411/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12412Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12413 // Implicitly declared functions (e.g. copy constructors) are
12414 // __host__ __device__
12415 if (D->isImplicit())
12416 return CFT_HostDevice;
12417
12418 if (D->hasAttr<CUDAGlobalAttr>())
12419 return CFT_Global;
12420
12421 if (D->hasAttr<CUDADeviceAttr>()) {
12422 if (D->hasAttr<CUDAHostAttr>())
12423 return CFT_HostDevice;
12424 else
12425 return CFT_Device;
12426 }
12427
12428 return CFT_Host;
12429}
12430
12431bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12432 CUDAFunctionTarget CalleeTarget) {
12433 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12434 // Callable from the device only."
12435 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12436 return true;
12437
12438 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12439 // Callable from the host only."
12440 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12441 // Callable from the host only."
12442 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12443 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12444 return true;
12445
12446 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12447 return true;
12448
12449 return false;
12450}
John McCall76da55d2013-04-16 07:28:30 +000012451
12452/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12453///
12454MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12455 SourceLocation DeclStart,
12456 Declarator &D, Expr *BitWidth,
12457 InClassInitStyle InitStyle,
12458 AccessSpecifier AS,
12459 AttributeList *MSPropertyAttr) {
12460 IdentifierInfo *II = D.getIdentifier();
12461 if (!II) {
12462 Diag(DeclStart, diag::err_anonymous_property);
12463 return NULL;
12464 }
12465 SourceLocation Loc = D.getIdentifierLoc();
12466
12467 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12468 QualType T = TInfo->getType();
12469 if (getLangOpts().CPlusPlus) {
12470 CheckExtraCXXDefaultArguments(D);
12471
12472 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12473 UPPC_DataMemberType)) {
12474 D.setInvalidType();
12475 T = Context.IntTy;
12476 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12477 }
12478 }
12479
12480 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12481
12482 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12483 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12484 diag::err_invalid_thread)
12485 << DeclSpec::getSpecifierName(TSCS);
12486
12487 // Check to see if this name was declared as a member previously
12488 NamedDecl *PrevDecl = 0;
12489 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12490 LookupName(Previous, S);
12491 switch (Previous.getResultKind()) {
12492 case LookupResult::Found:
12493 case LookupResult::FoundUnresolvedValue:
12494 PrevDecl = Previous.getAsSingle<NamedDecl>();
12495 break;
12496
12497 case LookupResult::FoundOverloaded:
12498 PrevDecl = Previous.getRepresentativeDecl();
12499 break;
12500
12501 case LookupResult::NotFound:
12502 case LookupResult::NotFoundInCurrentInstantiation:
12503 case LookupResult::Ambiguous:
12504 break;
12505 }
12506
12507 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12508 // Maybe we will complain about the shadowed template parameter.
12509 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12510 // Just pretend that we didn't see the previous declaration.
12511 PrevDecl = 0;
12512 }
12513
12514 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12515 PrevDecl = 0;
12516
12517 SourceLocation TSSL = D.getLocStart();
12518 MSPropertyDecl *NewPD;
12519 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12520 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12521 II, T, TInfo, TSSL,
12522 Data.GetterId, Data.SetterId);
12523 ProcessDeclAttributes(TUScope, NewPD, D);
12524 NewPD->setAccess(AS);
12525
12526 if (NewPD->isInvalidDecl())
12527 Record->setInvalidDecl();
12528
12529 if (D.getDeclSpec().isModulePrivateSpecified())
12530 NewPD->setModulePrivate();
12531
12532 if (NewPD->isInvalidDecl() && PrevDecl) {
12533 // Don't introduce NewFD into scope; there's already something
12534 // with the same name in the same scope.
12535 } else if (II) {
12536 PushOnScopeChains(NewPD, S);
12537 } else
12538 Record->addDecl(NewPD);
12539
12540 return NewPD;
12541}