blob: 94a507449b9e77d320ede8cd5b5b0a24cbf21275 [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);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
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
Craig Topper1a6eac82012-09-21 04:33:26 +0000407/// MergeCXXFunctionDecl - Merge two declarations of the same C++
408/// function, once we already know that they have the same
409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000413 bool Invalid = false;
414
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 // For non-template functions, default arguments can be added in
417 // later declarations of a function in the same
418 // scope. Declarations in different scopes have completely
419 // distinct sets of default arguments. That is, declarations in
420 // inner scopes do not acquire default arguments from
421 // declarations in outer scopes, and vice versa. In a given
422 // function declaration, all parameters subsequent to a
423 // parameter with a default argument shall have default
424 // arguments supplied in this or previous declarations. A
425 // default argument shall not be redefined by a later
426 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000427 //
428 // C++ [dcl.fct.default]p6:
429 // Except for member functions of class templates, the default arguments
430 // in a member function definition that appears outside of the class
431 // definition are added to the set of default arguments provided by the
432 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434 ParmVarDecl *OldParam = Old->getParamDecl(p);
435 ParmVarDecl *NewParam = New->getParamDecl(p);
436
James Molloy9cda03f2012-03-13 08:55:35 +0000437 bool OldParamHasDfl = OldParam->hasDefaultArg();
438 bool NewParamHasDfl = NewParam->hasDefaultArg();
439
440 NamedDecl *ND = Old;
441 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442 // Ignore default parameters of old decl if they are not in
443 // the same scope.
444 OldParamHasDfl = false;
445
446 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000447
Francois Pichet8d051e02011-04-10 03:03:52 +0000448 unsigned DiagDefaultParamID =
449 diag::err_param_default_argument_redefinition;
450
451 // MSVC accepts that default parameters be redefined for member functions
452 // of template class. The new default parameter's value is ignored.
453 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000457 // Merge the old default argument into the new parameter.
458 NewParam->setHasInheritedDefaultArg();
459 if (OldParam->hasUninstantiatedDefaultArg())
460 NewParam->setUninstantiatedDefaultArg(
461 OldParam->getUninstantiatedDefaultArg());
462 else
463 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000465 Invalid = false;
466 }
467 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000468
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470 // hint here. Alternatively, we could walk the type-source information
471 // for NewParam to find the last source location in the type... but it
472 // isn't worth the effort right now. This is the kind of test case that
473 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000474 // int f(int);
475 // void g(int (*fp)(int) = f);
476 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000478 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000479
480 // Look for the function declaration where the default argument was
481 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000482 for (FunctionDecl *Older = Old->getPreviousDecl();
483 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (!Older->getParamDecl(p)->hasDefaultArg())
485 break;
486
487 OldParam = Older->getParamDecl(p);
488 }
489
490 Diag(OldParam->getLocation(), diag::note_previous_definition)
491 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000492 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000493 // Merge the old default argument into the new parameter.
494 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000495 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000496 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000497 if (OldParam->hasUninstantiatedDefaultArg())
498 NewParam->setUninstantiatedDefaultArg(
499 OldParam->getUninstantiatedDefaultArg());
500 else
John McCall3d6c1782010-05-04 01:53:42 +0000501 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000502 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000503 if (New->getDescribedFunctionTemplate()) {
504 // Paragraph 4, quoted above, only applies to non-template functions.
505 Diag(NewParam->getLocation(),
506 diag::err_param_default_argument_template_redecl)
507 << NewParam->getDefaultArgRange();
508 Diag(Old->getLocation(), diag::note_template_prev_declaration)
509 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000510 } else if (New->getTemplateSpecializationKind()
511 != TSK_ImplicitInstantiation &&
512 New->getTemplateSpecializationKind() != TSK_Undeclared) {
513 // C++ [temp.expr.spec]p21:
514 // Default function arguments shall not be specified in a declaration
515 // or a definition for one of the following explicit specializations:
516 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000517 // - the explicit specialization of a member function template;
518 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000519 // template where the class template specialization to which the
520 // member function specialization belongs is implicitly
521 // instantiated.
522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524 << New->getDeclName()
525 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000526 } else if (New->getDeclContext()->isDependentContext()) {
527 // C++ [dcl.fct.default]p6 (DR217):
528 // Default arguments for a member function of a class template shall
529 // be specified on the initial declaration of the member function
530 // within the class template.
531 //
532 // Reading the tea leaves a bit in DR217 and its reference to DR205
533 // leads me to the conclusion that one cannot add default function
534 // arguments for an out-of-line definition of a member function of a
535 // dependent type.
536 int WhichKind = 2;
537 if (CXXRecordDecl *Record
538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539 if (Record->getDescribedClassTemplate())
540 WhichKind = 0;
541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542 WhichKind = 1;
543 else
544 WhichKind = 2;
545 }
546
547 Diag(NewParam->getLocation(),
548 diag::err_param_default_argument_member_template_redecl)
549 << WhichKind
550 << NewParam->getDefaultArgRange();
551 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000552 }
553 }
554
Richard Smithb8abff62012-11-28 03:45:24 +0000555 // DR1344: If a default argument is added outside a class definition and that
556 // default argument makes the function a special member function, the program
557 // is ill-formed. This can only happen for constructors.
558 if (isa<CXXConstructorDecl>(New) &&
559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562 if (NewSM != OldSM) {
563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564 assert(NewParam->hasDefaultArg());
565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566 << NewParam->getDefaultArgRange() << NewSM;
567 Diag(Old->getLocation(), diag::note_previous_declaration);
568 }
569 }
570
Richard Smithff234882012-02-20 23:28:05 +0000571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000572 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000573 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000574 if (New->isConstexpr() != Old->isConstexpr()) {
575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576 << New << New->isConstexpr();
577 Diag(Old->getLocation(), diag::note_previous_declaration);
578 Invalid = true;
579 }
580
Douglas Gregore13ad832010-02-12 07:32:17 +0000581 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000582 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000583
Douglas Gregorcda9c672009-02-16 17:45:42 +0000584 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585}
586
Sebastian Redl60618fa2011-03-12 11:50:43 +0000587/// \brief Merge the exception specifications of two variable declarations.
588///
589/// This is called when there's a redeclaration of a VarDecl. The function
590/// checks if the redeclaration might have an exception specification and
591/// validates compatibility and merges the specs if necessary.
592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000594 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000595 return;
596
597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
598 "Should only be called if types are otherwise the same.");
599
600 QualType NewType = New->getType();
601 QualType OldType = Old->getType();
602
603 // We're only interested in pointers and references to functions, as well
604 // as pointers to member functions.
605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606 NewType = R->getPointeeType();
607 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609 NewType = P->getPointeeType();
610 OldType = OldType->getAs<PointerType>()->getPointeeType();
611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612 NewType = M->getPointeeType();
613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614 }
615
616 if (!NewType->isFunctionProtoType())
617 return;
618
619 // There's lots of special cases for functions. For function pointers, system
620 // libraries are hopefully not as broken so that we don't need these
621 // workarounds.
622 if (CheckEquivalentExceptionSpec(
623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625 New->setInvalidDecl();
626 }
627}
628
Chris Lattner3d1cee32008-04-08 05:04:30 +0000629/// CheckCXXDefaultArguments - Verify that the default arguments for a
630/// function declaration are well-formed according to C++
631/// [dcl.fct.default].
632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633 unsigned NumParams = FD->getNumParams();
634 unsigned p;
635
636 // Find first parameter with a default argument
637 for (p = 0; p < NumParams; ++p) {
638 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000639 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 break;
641 }
642
643 // C++ [dcl.fct.default]p4:
644 // In a given function declaration, all parameters
645 // subsequent to a parameter with a default argument shall
646 // have default arguments supplied in this or previous
647 // declarations. A default argument shall not be redefined
648 // by a later declaration (not even to the same value).
649 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000650 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000652 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000653 if (Param->isInvalidDecl())
654 /* We already complained about this parameter. */;
655 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000656 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000657 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000658 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 else
Mike Stump1eb44332009-09-09 15:08:12 +0000660 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000661 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 LastMissingDefaultArg = p;
664 }
665 }
666
667 if (LastMissingDefaultArg > 0) {
668 // Some default arguments were missing. Clear out all of the
669 // default arguments up to (and including) the last missing
670 // default argument, so that we leave the function parameters
671 // in a semantically valid state.
672 for (p = 0; p <= LastMissingDefaultArg; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000674 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000675 Param->setDefaultArg(0);
676 }
677 }
678 }
679}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000680
Richard Smith9f569cc2011-10-01 02:31:28 +0000681// CheckConstexprParameterTypes - Check whether a function's parameter types
682// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000683// diagnostic and return false.
684static bool CheckConstexprParameterTypes(Sema &SemaRef,
685 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000686 unsigned ArgIndex = 0;
687 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691 SourceLocation ParamLoc = PD->getLocation();
692 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000693 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000694 diag::err_constexpr_non_literal_param,
695 ArgIndex+1, PD->getSourceRange(),
696 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000697 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000698 }
Joao Matos17d35c32012-08-31 22:18:20 +0000699 return true;
700}
701
702/// \brief Get diagnostic %select index for tag kind for
703/// record diagnostic message.
704/// WARNING: Indexes apply to particular diagnostics only!
705///
706/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000708 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000709 case TTK_Struct: return 0;
710 case TTK_Interface: return 1;
711 case TTK_Class: return 2;
712 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000713 }
Joao Matos17d35c32012-08-31 22:18:20 +0000714}
715
716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717// the requirements of a constexpr function definition or a constexpr
718// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000719// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000720//
Richard Smith86c3ae42012-02-13 03:54:03 +0000721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000723 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000725 // C++11 [dcl.constexpr]p4:
726 // The definition of a constexpr constructor shall satisfy the following
727 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000729 const CXXRecordDecl *RD = MD->getParent();
730 if (RD->getNumVBases()) {
731 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732 << isa<CXXConstructorDecl>(NewFD)
733 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735 E = RD->vbases_end(); I != E; ++I)
736 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000737 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000738 return false;
739 }
Richard Smith35340502012-01-13 04:54:00 +0000740 }
741
742 if (!isa<CXXConstructorDecl>(NewFD)) {
743 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000744 // The definition of a constexpr function shall satisfy the following
745 // constraints:
746 // - it shall not be virtual;
747 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000750
Richard Smith86c3ae42012-02-13 03:54:03 +0000751 // If it's not obvious why this function is virtual, find an overridden
752 // function which uses the 'virtual' keyword.
753 const CXXMethodDecl *WrittenVirtual = Method;
754 while (!WrittenVirtual->isVirtualAsWritten())
755 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756 if (WrittenVirtual != Method)
757 Diag(WrittenVirtual->getLocation(),
758 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000759 return false;
760 }
761
762 // - its return type shall be a literal type;
763 QualType RT = NewFD->getResultType();
764 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000765 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000766 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000768 }
769
Richard Smith35340502012-01-13 04:54:00 +0000770 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000772 return false;
773
Richard Smith9f569cc2011-10-01 02:31:28 +0000774 return true;
775}
776
777/// Check the given declaration statement is legal within a constexpr function
778/// body. C++0x [dcl.constexpr]p3,p4.
779///
780/// \return true if the body is OK, false if we have diagnosed a problem.
781static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
782 DeclStmt *DS) {
783 // C++0x [dcl.constexpr]p3 and p4:
784 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
785 // contain only
786 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
787 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
788 switch ((*DclIt)->getKind()) {
789 case Decl::StaticAssert:
790 case Decl::Using:
791 case Decl::UsingShadow:
792 case Decl::UsingDirective:
793 case Decl::UnresolvedUsingTypename:
794 // - static_assert-declarations
795 // - using-declarations,
796 // - using-directives,
797 continue;
798
799 case Decl::Typedef:
800 case Decl::TypeAlias: {
801 // - typedef declarations and alias-declarations that do not define
802 // classes or enumerations,
803 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
804 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
805 // Don't allow variably-modified types in constexpr functions.
806 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
807 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
808 << TL.getSourceRange() << TL.getType()
809 << isa<CXXConstructorDecl>(Dcl);
810 return false;
811 }
812 continue;
813 }
814
815 case Decl::Enum:
816 case Decl::CXXRecord:
817 // As an extension, we allow the declaration (but not the definition) of
818 // classes and enumerations in all declarations, not just in typedef and
819 // alias declarations.
820 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
821 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
822 << isa<CXXConstructorDecl>(Dcl);
823 return false;
824 }
825 continue;
826
827 case Decl::Var:
828 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
829 << isa<CXXConstructorDecl>(Dcl);
830 return false;
831
832 default:
833 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
834 << isa<CXXConstructorDecl>(Dcl);
835 return false;
836 }
837 }
838
839 return true;
840}
841
842/// Check that the given field is initialized within a constexpr constructor.
843///
844/// \param Dcl The constexpr constructor being checked.
845/// \param Field The field being checked. This may be a member of an anonymous
846/// struct or union nested within the class being checked.
847/// \param Inits All declarations, including anonymous struct/union members and
848/// indirect members, for which any initialization was provided.
849/// \param Diagnosed Set to true if an error is produced.
850static void CheckConstexprCtorInitializer(Sema &SemaRef,
851 const FunctionDecl *Dcl,
852 FieldDecl *Field,
853 llvm::SmallSet<Decl*, 16> &Inits,
854 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000855 if (Field->isUnnamedBitfield())
856 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000857
858 if (Field->isAnonymousStructOrUnion() &&
859 Field->getType()->getAsCXXRecordDecl()->isEmpty())
860 return;
861
Richard Smith9f569cc2011-10-01 02:31:28 +0000862 if (!Inits.count(Field)) {
863 if (!Diagnosed) {
864 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
865 Diagnosed = true;
866 }
867 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
868 } else if (Field->isAnonymousStructOrUnion()) {
869 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
870 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
871 I != E; ++I)
872 // If an anonymous union contains an anonymous struct of which any member
873 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000874 if (!RD->isUnion() || Inits.count(*I))
875 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000876 }
877}
878
879/// Check the body for the given constexpr function declaration only contains
880/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
881///
882/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000883bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000884 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000885 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000886 // The definition of a constexpr function shall satisfy the following
887 // constraints: [...]
888 // - its function-body shall be = delete, = default, or a
889 // compound-statement
890 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000891 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000892 // In the definition of a constexpr constructor, [...]
893 // - its function-body shall not be a function-try-block;
894 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
895 << isa<CXXConstructorDecl>(Dcl);
896 return false;
897 }
898
899 // - its function-body shall be [...] a compound-statement that contains only
900 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
901
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000902 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smith9f569cc2011-10-01 02:31:28 +0000903 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
904 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
905 switch ((*BodyIt)->getStmtClass()) {
906 case Stmt::NullStmtClass:
907 // - null statements,
908 continue;
909
910 case Stmt::DeclStmtClass:
911 // - static_assert-declarations
912 // - using-declarations,
913 // - using-directives,
914 // - typedef declarations and alias-declarations that do not define
915 // classes or enumerations,
916 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
917 return false;
918 continue;
919
920 case Stmt::ReturnStmtClass:
921 // - and exactly one return statement;
922 if (isa<CXXConstructorDecl>(Dcl))
923 break;
924
925 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000926 continue;
927
928 default:
929 break;
930 }
931
932 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
933 << isa<CXXConstructorDecl>(Dcl);
934 return false;
935 }
936
937 if (const CXXConstructorDecl *Constructor
938 = dyn_cast<CXXConstructorDecl>(Dcl)) {
939 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000940 // DR1359:
941 // - every non-variant non-static data member and base class sub-object
942 // shall be initialized;
943 // - if the class is a non-empty union, or for each non-empty anonymous
944 // union member of a non-union class, exactly one non-static data member
945 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000946 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000947 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000948 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
949 return false;
950 }
Richard Smith6e433752011-10-10 16:38:04 +0000951 } else if (!Constructor->isDependentContext() &&
952 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000953 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
954
955 // Skip detailed checking if we have enough initializers, and we would
956 // allow at most one initializer per member.
957 bool AnyAnonStructUnionMembers = false;
958 unsigned Fields = 0;
959 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
960 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000961 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000962 AnyAnonStructUnionMembers = true;
963 break;
964 }
965 }
966 if (AnyAnonStructUnionMembers ||
967 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
968 // Check initialization of non-static data members. Base classes are
969 // always initialized so do not need to be checked. Dependent bases
970 // might not have initializers in the member initializer list.
971 llvm::SmallSet<Decl*, 16> Inits;
972 for (CXXConstructorDecl::init_const_iterator
973 I = Constructor->init_begin(), E = Constructor->init_end();
974 I != E; ++I) {
975 if (FieldDecl *FD = (*I)->getMember())
976 Inits.insert(FD);
977 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
978 Inits.insert(ID->chain_begin(), ID->chain_end());
979 }
980
981 bool Diagnosed = false;
982 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
983 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000984 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000985 if (Diagnosed)
986 return false;
987 }
988 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000989 } else {
990 if (ReturnStmts.empty()) {
991 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
992 return false;
993 }
994 if (ReturnStmts.size() > 1) {
995 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
996 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
997 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
998 return false;
999 }
1000 }
1001
Richard Smith5ba73e12012-02-04 00:33:54 +00001002 // C++11 [dcl.constexpr]p5:
1003 // if no function argument values exist such that the function invocation
1004 // substitution would produce a constant expression, the program is
1005 // ill-formed; no diagnostic required.
1006 // C++11 [dcl.constexpr]p3:
1007 // - every constructor call and implicit conversion used in initializing the
1008 // return value shall be one of those allowed in a constant expression.
1009 // C++11 [dcl.constexpr]p4:
1010 // - every constructor involved in initializing non-static data members and
1011 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001012 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001013 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001014 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001015 << isa<CXXConstructorDecl>(Dcl);
1016 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1017 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001018 // Don't return false here: we allow this for compatibility in
1019 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001020 }
1021
Richard Smith9f569cc2011-10-01 02:31:28 +00001022 return true;
1023}
1024
Douglas Gregorb48fe382008-10-31 09:07:45 +00001025/// isCurrentClassName - Determine whether the identifier II is the
1026/// name of the class type currently being defined. In the case of
1027/// nested classes, this will only return true if II is the name of
1028/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001029bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1030 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001031 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001032
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001033 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001034 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001035 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001036 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1037 } else
1038 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1039
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001040 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001041 return &II == CurDecl->getIdentifier();
1042 else
1043 return false;
1044}
1045
Douglas Gregor229d47a2012-11-10 07:24:09 +00001046/// \brief Determine whether the given class is a base class of the given
1047/// class, including looking at dependent bases.
1048static bool findCircularInheritance(const CXXRecordDecl *Class,
1049 const CXXRecordDecl *Current) {
1050 SmallVector<const CXXRecordDecl*, 8> Queue;
1051
1052 Class = Class->getCanonicalDecl();
1053 while (true) {
1054 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1055 E = Current->bases_end();
1056 I != E; ++I) {
1057 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1058 if (!Base)
1059 continue;
1060
1061 Base = Base->getDefinition();
1062 if (!Base)
1063 continue;
1064
1065 if (Base->getCanonicalDecl() == Class)
1066 return true;
1067
1068 Queue.push_back(Base);
1069 }
1070
1071 if (Queue.empty())
1072 return false;
1073
1074 Current = Queue.back();
1075 Queue.pop_back();
1076 }
1077
1078 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001079}
1080
Mike Stump1eb44332009-09-09 15:08:12 +00001081/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001082///
1083/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1084/// and returns NULL otherwise.
1085CXXBaseSpecifier *
1086Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1087 SourceRange SpecifierRange,
1088 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001089 TypeSourceInfo *TInfo,
1090 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001091 QualType BaseType = TInfo->getType();
1092
Douglas Gregor2943aed2009-03-03 04:44:36 +00001093 // C++ [class.union]p1:
1094 // A union shall not have base classes.
1095 if (Class->isUnion()) {
1096 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1097 << SpecifierRange;
1098 return 0;
1099 }
1100
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001101 if (EllipsisLoc.isValid() &&
1102 !TInfo->getType()->containsUnexpandedParameterPack()) {
1103 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1104 << TInfo->getTypeLoc().getSourceRange();
1105 EllipsisLoc = SourceLocation();
1106 }
Douglas Gregord777e282012-11-10 01:18:17 +00001107
1108 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1109
1110 if (BaseType->isDependentType()) {
1111 // Make sure that we don't have circular inheritance among our dependent
1112 // bases. For non-dependent bases, the check for completeness below handles
1113 // this.
1114 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1115 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1116 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001117 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001118 Diag(BaseLoc, diag::err_circular_inheritance)
1119 << BaseType << Context.getTypeDeclType(Class);
1120
1121 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1122 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1123 << BaseType;
1124
1125 return 0;
1126 }
1127 }
1128
Mike Stump1eb44332009-09-09 15:08:12 +00001129 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001130 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001131 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001132 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001133
1134 // Base specifiers must be record types.
1135 if (!BaseType->isRecordType()) {
1136 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1137 return 0;
1138 }
1139
1140 // C++ [class.union]p1:
1141 // A union shall not be used as a base class.
1142 if (BaseType->isUnionType()) {
1143 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1144 return 0;
1145 }
1146
1147 // C++ [class.derived]p2:
1148 // The class-name in a base-specifier shall not be an incompletely
1149 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001150 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001151 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001152 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001153 return 0;
John McCall572fc622010-08-17 07:23:57 +00001154 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001155
Eli Friedman1d954f62009-08-15 21:55:26 +00001156 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001157 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001158 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001159 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001160 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001161 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1162 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001163
Anders Carlsson1d209272011-03-25 14:55:14 +00001164 // C++ [class]p3:
1165 // If a class is marked final and it appears as a base-type-specifier in
1166 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001167 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001168 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1169 << CXXBaseDecl->getDeclName();
1170 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1171 << CXXBaseDecl->getDeclName();
1172 return 0;
1173 }
1174
John McCall572fc622010-08-17 07:23:57 +00001175 if (BaseDecl->isInvalidDecl())
1176 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001177
1178 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001179 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001180 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001181 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001182}
1183
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001184/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1185/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001186/// example:
1187/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001188/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001189BaseResult
John McCalld226f652010-08-21 09:40:31 +00001190Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001191 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001192 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001193 ParsedType basetype, SourceLocation BaseLoc,
1194 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001195 if (!classdecl)
1196 return true;
1197
Douglas Gregor40808ce2009-03-09 23:48:35 +00001198 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001199 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001200 if (!Class)
1201 return true;
1202
Richard Smith05321402013-02-19 23:47:15 +00001203 // We do not support any C++11 attributes on base-specifiers yet.
1204 // Diagnose any attributes we see.
1205 if (!Attributes.empty()) {
1206 for (AttributeList *Attr = Attributes.getList(); Attr;
1207 Attr = Attr->getNext()) {
1208 if (Attr->isInvalid() ||
1209 Attr->getKind() == AttributeList::IgnoredAttribute)
1210 continue;
1211 Diag(Attr->getLoc(),
1212 Attr->getKind() == AttributeList::UnknownAttribute
1213 ? diag::warn_unknown_attribute_ignored
1214 : diag::err_base_specifier_attribute)
1215 << Attr->getName();
1216 }
1217 }
1218
Nick Lewycky56062202010-07-26 16:56:01 +00001219 TypeSourceInfo *TInfo = 0;
1220 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001221
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001222 if (EllipsisLoc.isInvalid() &&
1223 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001224 UPPC_BaseType))
1225 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001226
Douglas Gregor2943aed2009-03-03 04:44:36 +00001227 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001228 Virtual, Access, TInfo,
1229 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001230 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001231 else
1232 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Douglas Gregor2943aed2009-03-03 04:44:36 +00001234 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001235}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001236
Douglas Gregor2943aed2009-03-03 04:44:36 +00001237/// \brief Performs the actual work of attaching the given base class
1238/// specifiers to a C++ class.
1239bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1240 unsigned NumBases) {
1241 if (NumBases == 0)
1242 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001243
1244 // Used to keep track of which base types we have already seen, so
1245 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001246 // that the key is always the unqualified canonical type of the base
1247 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001248 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1249
1250 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001251 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001252 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001253 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001254 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001255 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001256 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001257
1258 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1259 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001260 // C++ [class.mi]p3:
1261 // A class shall not be specified as a direct base class of a
1262 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001263 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001264 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001265 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001266 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001267
1268 // Delete the duplicate base class specifier; we're going to
1269 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001270 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001271
1272 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001273 } else {
1274 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001275 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001276 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001277 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1278 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1279 if (Class->isInterface() &&
1280 (!RD->isInterface() ||
1281 KnownBase->getAccessSpecifier() != AS_public)) {
1282 // The Microsoft extension __interface does not permit bases that
1283 // are not themselves public interfaces.
1284 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1285 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1286 << RD->getSourceRange();
1287 Invalid = true;
1288 }
1289 if (RD->hasAttr<WeakAttr>())
1290 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1291 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001292 }
1293 }
1294
1295 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001296 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001297
1298 // Delete the remaining (good) base class specifiers, since their
1299 // data has been copied into the CXXRecordDecl.
1300 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001301 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001302
1303 return Invalid;
1304}
1305
1306/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1307/// class, after checking whether there are any duplicate base
1308/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001309void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001310 unsigned NumBases) {
1311 if (!ClassDecl || !Bases || !NumBases)
1312 return;
1313
1314 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001315 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001316 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001317}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001318
Douglas Gregora8f32e02009-10-06 17:59:45 +00001319/// \brief Determine whether the type \p Derived is a C++ class that is
1320/// derived from the type \p Base.
1321bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001322 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001323 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001324
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001325 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001326 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001327 return false;
1328
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001329 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001330 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001331 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001332
1333 // If either the base or the derived type is invalid, don't try to
1334 // check whether one is derived from the other.
1335 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1336 return false;
1337
John McCall86ff3082010-02-04 22:26:26 +00001338 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1339 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001340}
1341
1342/// \brief Determine whether the type \p Derived is a C++ class that is
1343/// derived from the type \p Base.
1344bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001345 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001346 return false;
1347
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001348 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001349 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001350 return false;
1351
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001352 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001353 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001354 return false;
1355
Douglas Gregora8f32e02009-10-06 17:59:45 +00001356 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1357}
1358
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001359void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001360 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001361 assert(BasePathArray.empty() && "Base path array must be empty!");
1362 assert(Paths.isRecordingPaths() && "Must record paths!");
1363
1364 const CXXBasePath &Path = Paths.front();
1365
1366 // We first go backward and check if we have a virtual base.
1367 // FIXME: It would be better if CXXBasePath had the base specifier for
1368 // the nearest virtual base.
1369 unsigned Start = 0;
1370 for (unsigned I = Path.size(); I != 0; --I) {
1371 if (Path[I - 1].Base->isVirtual()) {
1372 Start = I - 1;
1373 break;
1374 }
1375 }
1376
1377 // Now add all bases.
1378 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001379 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001380}
1381
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001382/// \brief Determine whether the given base path includes a virtual
1383/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001384bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1385 for (CXXCastPath::const_iterator B = BasePath.begin(),
1386 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001387 B != BEnd; ++B)
1388 if ((*B)->isVirtual())
1389 return true;
1390
1391 return false;
1392}
1393
Douglas Gregora8f32e02009-10-06 17:59:45 +00001394/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1395/// conversion (where Derived and Base are class types) is
1396/// well-formed, meaning that the conversion is unambiguous (and
1397/// that all of the base classes are accessible). Returns true
1398/// and emits a diagnostic if the code is ill-formed, returns false
1399/// otherwise. Loc is the location where this routine should point to
1400/// if there is an error, and Range is the source range to highlight
1401/// if there is an error.
1402bool
1403Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001404 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001405 unsigned AmbigiousBaseConvID,
1406 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001407 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001408 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001409 // First, determine whether the path from Derived to Base is
1410 // ambiguous. This is slightly more expensive than checking whether
1411 // the Derived to Base conversion exists, because here we need to
1412 // explore multiple paths to determine if there is an ambiguity.
1413 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1414 /*DetectVirtual=*/false);
1415 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1416 assert(DerivationOkay &&
1417 "Can only be used with a derived-to-base conversion");
1418 (void)DerivationOkay;
1419
1420 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001421 if (InaccessibleBaseID) {
1422 // Check that the base class can be accessed.
1423 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1424 InaccessibleBaseID)) {
1425 case AR_inaccessible:
1426 return true;
1427 case AR_accessible:
1428 case AR_dependent:
1429 case AR_delayed:
1430 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001431 }
John McCall6b2accb2010-02-10 09:31:12 +00001432 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001433
1434 // Build a base path if necessary.
1435 if (BasePath)
1436 BuildBasePathArray(Paths, *BasePath);
1437 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001438 }
1439
1440 // We know that the derived-to-base conversion is ambiguous, and
1441 // we're going to produce a diagnostic. Perform the derived-to-base
1442 // search just one more time to compute all of the possible paths so
1443 // that we can print them out. This is more expensive than any of
1444 // the previous derived-to-base checks we've done, but at this point
1445 // performance isn't as much of an issue.
1446 Paths.clear();
1447 Paths.setRecordingPaths(true);
1448 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1449 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1450 (void)StillOkay;
1451
1452 // Build up a textual representation of the ambiguous paths, e.g.,
1453 // D -> B -> A, that will be used to illustrate the ambiguous
1454 // conversions in the diagnostic. We only print one of the paths
1455 // to each base class subobject.
1456 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1457
1458 Diag(Loc, AmbigiousBaseConvID)
1459 << Derived << Base << PathDisplayStr << Range << Name;
1460 return true;
1461}
1462
1463bool
1464Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001465 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001466 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001467 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001468 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001469 IgnoreAccess ? 0
1470 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001471 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001472 Loc, Range, DeclarationName(),
1473 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001474}
1475
1476
1477/// @brief Builds a string representing ambiguous paths from a
1478/// specific derived class to different subobjects of the same base
1479/// class.
1480///
1481/// This function builds a string that can be used in error messages
1482/// to show the different paths that one can take through the
1483/// inheritance hierarchy to go from the derived class to different
1484/// subobjects of a base class. The result looks something like this:
1485/// @code
1486/// struct D -> struct B -> struct A
1487/// struct D -> struct C -> struct A
1488/// @endcode
1489std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1490 std::string PathDisplayStr;
1491 std::set<unsigned> DisplayedPaths;
1492 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1493 Path != Paths.end(); ++Path) {
1494 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1495 // We haven't displayed a path to this particular base
1496 // class subobject yet.
1497 PathDisplayStr += "\n ";
1498 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1499 for (CXXBasePath::const_iterator Element = Path->begin();
1500 Element != Path->end(); ++Element)
1501 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1502 }
1503 }
1504
1505 return PathDisplayStr;
1506}
1507
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001508//===----------------------------------------------------------------------===//
1509// C++ class member Handling
1510//===----------------------------------------------------------------------===//
1511
Abramo Bagnara6206d532010-06-05 05:09:32 +00001512/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001513bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1514 SourceLocation ASLoc,
1515 SourceLocation ColonLoc,
1516 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001517 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001518 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001519 ASLoc, ColonLoc);
1520 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001521 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001522}
1523
Richard Smitha4b39652012-08-06 03:25:17 +00001524/// CheckOverrideControl - Check C++11 override control semantics.
1525void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001526 if (D->isInvalidDecl())
1527 return;
1528
Chris Lattner5f9e2722011-07-23 10:55:15 +00001529 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001530
Richard Smitha4b39652012-08-06 03:25:17 +00001531 // Do we know which functions this declaration might be overriding?
1532 bool OverridesAreKnown = !MD ||
1533 (!MD->getParent()->hasAnyDependentBases() &&
1534 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001535
Richard Smitha4b39652012-08-06 03:25:17 +00001536 if (!MD || !MD->isVirtual()) {
1537 if (OverridesAreKnown) {
1538 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1539 Diag(OA->getLocation(),
1540 diag::override_keyword_only_allowed_on_virtual_member_functions)
1541 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1542 D->dropAttr<OverrideAttr>();
1543 }
1544 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1545 Diag(FA->getLocation(),
1546 diag::override_keyword_only_allowed_on_virtual_member_functions)
1547 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1548 D->dropAttr<FinalAttr>();
1549 }
1550 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001551 return;
1552 }
Richard Smitha4b39652012-08-06 03:25:17 +00001553
1554 if (!OverridesAreKnown)
1555 return;
1556
1557 // C++11 [class.virtual]p5:
1558 // If a virtual function is marked with the virt-specifier override and
1559 // does not override a member function of a base class, the program is
1560 // ill-formed.
1561 bool HasOverriddenMethods =
1562 MD->begin_overridden_methods() != MD->end_overridden_methods();
1563 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1564 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1565 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001566}
1567
Richard Smitha4b39652012-08-06 03:25:17 +00001568/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001569/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001570/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001571bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1572 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001573 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001574 return false;
1575
1576 Diag(New->getLocation(), diag::err_final_function_overridden)
1577 << New->getDeclName();
1578 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1579 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001580}
1581
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001582static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001583 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1584 // FIXME: Destruction of ObjC lifetime types has side-effects.
1585 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1586 return !RD->isCompleteDefinition() ||
1587 !RD->hasTrivialDefaultConstructor() ||
1588 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001589 return false;
1590}
1591
John McCall76da55d2013-04-16 07:28:30 +00001592static AttributeList *getMSPropertyAttr(AttributeList *list) {
1593 for (AttributeList* it = list; it != 0; it = it->getNext())
1594 if (it->isDeclspecPropertyAttribute())
1595 return it;
1596 return 0;
1597}
1598
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001599/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1600/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001601/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001602/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1603/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001604NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001605Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001606 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001607 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001608 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001609 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001610 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1611 DeclarationName Name = NameInfo.getName();
1612 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001613
1614 // For anonymous bitfields, the location should point to the type.
1615 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001616 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001617
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001618 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001619
John McCall4bde1e12010-06-04 08:34:12 +00001620 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001621 assert(!DS.isFriendSpecified());
1622
Richard Smith1ab0d902011-06-25 02:28:38 +00001623 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001624
John McCalle402e722012-09-25 07:32:39 +00001625 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1626 // The Microsoft extension __interface only permits public member functions
1627 // and prohibits constructors, destructors, operators, non-public member
1628 // functions, static methods and data members.
1629 unsigned InvalidDecl;
1630 bool ShowDeclName = true;
1631 if (!isFunc)
1632 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1633 else if (AS != AS_public)
1634 InvalidDecl = 2;
1635 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1636 InvalidDecl = 3;
1637 else switch (Name.getNameKind()) {
1638 case DeclarationName::CXXConstructorName:
1639 InvalidDecl = 4;
1640 ShowDeclName = false;
1641 break;
1642
1643 case DeclarationName::CXXDestructorName:
1644 InvalidDecl = 5;
1645 ShowDeclName = false;
1646 break;
1647
1648 case DeclarationName::CXXOperatorName:
1649 case DeclarationName::CXXConversionFunctionName:
1650 InvalidDecl = 6;
1651 break;
1652
1653 default:
1654 InvalidDecl = 0;
1655 break;
1656 }
1657
1658 if (InvalidDecl) {
1659 if (ShowDeclName)
1660 Diag(Loc, diag::err_invalid_member_in_interface)
1661 << (InvalidDecl-1) << Name;
1662 else
1663 Diag(Loc, diag::err_invalid_member_in_interface)
1664 << (InvalidDecl-1) << "";
1665 return 0;
1666 }
1667 }
1668
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001669 // C++ 9.2p6: A member shall not be declared to have automatic storage
1670 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001671 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1672 // data members and cannot be applied to names declared const or static,
1673 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001674 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001675 case DeclSpec::SCS_unspecified:
1676 case DeclSpec::SCS_typedef:
1677 case DeclSpec::SCS_static:
1678 break;
1679 case DeclSpec::SCS_mutable:
1680 if (isFunc) {
1681 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Richard Smithec642442013-04-12 22:46:28 +00001683 // FIXME: It would be nicer if the keyword was ignored only for this
1684 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001685 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001686 }
1687 break;
1688 default:
1689 Diag(DS.getStorageClassSpecLoc(),
1690 diag::err_storageclass_invalid_for_member);
1691 D.getMutableDeclSpec().ClearStorageClassSpecs();
1692 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001693 }
1694
Sebastian Redl669d5d72008-11-14 23:42:31 +00001695 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1696 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001697 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001698
David Blaikie1d87fba2013-01-30 01:22:18 +00001699 if (DS.isConstexprSpecified() && isInstField) {
1700 SemaDiagnosticBuilder B =
1701 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1702 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1703 if (InitStyle == ICIS_NoInit) {
1704 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1705 D.getMutableDeclSpec().ClearConstexprSpec();
1706 const char *PrevSpec;
1707 unsigned DiagID;
1708 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1709 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001710 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001711 assert(!Failed && "Making a constexpr member const shouldn't fail");
1712 } else {
1713 B << 1;
1714 const char *PrevSpec;
1715 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001716 if (D.getMutableDeclSpec().SetStorageClassSpec(
1717 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001718 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001719 "This is the only DeclSpec that should fail to be applied");
1720 B << 1;
1721 } else {
1722 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1723 isInstField = false;
1724 }
1725 }
1726 }
1727
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001728 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001729 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001730 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001731
1732 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001733 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001734 Diag(Loc, diag::err_bad_variable_name)
1735 << Name;
1736 return 0;
1737 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001738
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001739 IdentifierInfo *II = Name.getAsIdentifierInfo();
1740
Douglas Gregorf2503652011-09-21 14:40:46 +00001741 // Member field could not be with "template" keyword.
1742 // So TemplateParameterLists should be empty in this case.
1743 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001744 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001745 if (TemplateParams->size()) {
1746 // There is no such thing as a member field template.
1747 Diag(D.getIdentifierLoc(), diag::err_template_member)
1748 << II
1749 << SourceRange(TemplateParams->getTemplateLoc(),
1750 TemplateParams->getRAngleLoc());
1751 } else {
1752 // There is an extraneous 'template<>' for this member.
1753 Diag(TemplateParams->getTemplateLoc(),
1754 diag::err_template_member_noparams)
1755 << II
1756 << SourceRange(TemplateParams->getTemplateLoc(),
1757 TemplateParams->getRAngleLoc());
1758 }
1759 return 0;
1760 }
1761
Douglas Gregor922fff22010-10-13 22:19:53 +00001762 if (SS.isSet() && !SS.isInvalid()) {
1763 // The user provided a superfluous scope specifier inside a class
1764 // definition:
1765 //
1766 // class X {
1767 // int X::member;
1768 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001769 if (DeclContext *DC = computeDeclContext(SS, false))
1770 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001771 else
1772 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1773 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001774
Douglas Gregor922fff22010-10-13 22:19:53 +00001775 SS.clear();
1776 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001777
John McCall76da55d2013-04-16 07:28:30 +00001778 AttributeList *MSPropertyAttr =
1779 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1780 if (MSPropertyAttr) {
1781 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1782 BitWidth, InitStyle, AS, MSPropertyAttr);
1783 isInstField = false;
1784 } else {
1785 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1786 BitWidth, InitStyle, AS);
1787 }
Chris Lattner6f8ce142009-03-05 23:03:49 +00001788 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001789 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001790 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001791
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001792 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001793 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001794 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001795 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001796
1797 // Non-instance-fields can't have a bitfield.
1798 if (BitWidth) {
1799 if (Member->isInvalidDecl()) {
1800 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001801 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001802 // C++ 9.6p3: A bit-field shall not be a static member.
1803 // "static member 'A' cannot be a bit-field"
1804 Diag(Loc, diag::err_static_not_bitfield)
1805 << Name << BitWidth->getSourceRange();
1806 } else if (isa<TypedefDecl>(Member)) {
1807 // "typedef member 'x' cannot be a bit-field"
1808 Diag(Loc, diag::err_typedef_not_bitfield)
1809 << Name << BitWidth->getSourceRange();
1810 } else {
1811 // A function typedef ("typedef int f(); f a;").
1812 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1813 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001814 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001815 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001816 }
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Chris Lattner8b963ef2009-03-05 23:01:03 +00001818 BitWidth = 0;
1819 Member->setInvalidDecl();
1820 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001821
1822 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Douglas Gregor37b372b2009-08-20 22:52:58 +00001824 // If we have declared a member function template, set the access of the
1825 // templated declaration as well.
1826 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1827 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001828 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001829
Richard Smitha4b39652012-08-06 03:25:17 +00001830 if (VS.isOverrideSpecified())
1831 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1832 if (VS.isFinalSpecified())
1833 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001834
Douglas Gregorf5251602011-03-08 17:10:18 +00001835 if (VS.getLastLocation().isValid()) {
1836 // Update the end location of a method that has a virt-specifiers.
1837 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1838 MD->setRangeEnd(VS.getLastLocation());
1839 }
Richard Smitha4b39652012-08-06 03:25:17 +00001840
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001841 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001842
Douglas Gregor10bd3682008-11-17 22:58:34 +00001843 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001844
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001845 if (isInstField) {
1846 FieldDecl *FD = cast<FieldDecl>(Member);
1847 FieldCollector->Add(FD);
1848
1849 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1850 FD->getLocation())
1851 != DiagnosticsEngine::Ignored) {
1852 // Remember all explicit private FieldDecls that have a name, no side
1853 // effects and are not part of a dependent type declaration.
1854 if (!FD->isImplicit() && FD->getDeclName() &&
1855 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001856 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001857 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001858 !InitializationHasSideEffects(*FD))
1859 UnusedPrivateFields.insert(FD);
1860 }
1861 }
1862
John McCalld226f652010-08-21 09:40:31 +00001863 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001864}
1865
Hans Wennborg471f9852012-09-18 15:58:06 +00001866namespace {
1867 class UninitializedFieldVisitor
1868 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1869 Sema &S;
1870 ValueDecl *VD;
1871 public:
1872 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1873 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001874 S(S) {
1875 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1876 this->VD = IFD->getAnonField();
1877 else
1878 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001879 }
1880
1881 void HandleExpr(Expr *E) {
1882 if (!E) return;
1883
1884 // Expressions like x(x) sometimes lack the surrounding expressions
1885 // but need to be checked anyways.
1886 HandleValue(E);
1887 Visit(E);
1888 }
1889
1890 void HandleValue(Expr *E) {
1891 E = E->IgnoreParens();
1892
1893 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1894 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001895 return;
1896
1897 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1898 // or union.
1899 MemberExpr *FieldME = ME;
1900
Hans Wennborg471f9852012-09-18 15:58:06 +00001901 Expr *Base = E;
1902 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001903 ME = cast<MemberExpr>(Base);
1904
1905 if (isa<VarDecl>(ME->getMemberDecl()))
1906 return;
1907
1908 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1909 if (!FD->isAnonymousStructOrUnion())
1910 FieldME = ME;
1911
Hans Wennborg471f9852012-09-18 15:58:06 +00001912 Base = ME->getBase();
1913 }
1914
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001915 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001916 unsigned diag = VD->getType()->isReferenceType()
1917 ? diag::warn_reference_field_is_uninit
1918 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001919 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001920 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001921 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001922 }
1923
1924 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1925 HandleValue(CO->getTrueExpr());
1926 HandleValue(CO->getFalseExpr());
1927 return;
1928 }
1929
1930 if (BinaryConditionalOperator *BCO =
1931 dyn_cast<BinaryConditionalOperator>(E)) {
1932 HandleValue(BCO->getCommon());
1933 HandleValue(BCO->getFalseExpr());
1934 return;
1935 }
1936
1937 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1938 switch (BO->getOpcode()) {
1939 default:
1940 return;
1941 case(BO_PtrMemD):
1942 case(BO_PtrMemI):
1943 HandleValue(BO->getLHS());
1944 return;
1945 case(BO_Comma):
1946 HandleValue(BO->getRHS());
1947 return;
1948 }
1949 }
1950 }
1951
1952 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1953 if (E->getCastKind() == CK_LValueToRValue)
1954 HandleValue(E->getSubExpr());
1955
1956 Inherited::VisitImplicitCastExpr(E);
1957 }
1958
1959 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1960 Expr *Callee = E->getCallee();
1961 if (isa<MemberExpr>(Callee))
1962 HandleValue(Callee);
1963
1964 Inherited::VisitCXXMemberCallExpr(E);
1965 }
1966 };
1967 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1968 ValueDecl *VD) {
1969 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1970 }
1971} // namespace
1972
Richard Smith7a614d82011-06-11 17:19:42 +00001973/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001974/// in-class initializer for a non-static C++ class member, and after
1975/// instantiating an in-class initializer in a class template. Such actions
1976/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001977void
Richard Smithca523302012-06-10 03:12:00 +00001978Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001979 Expr *InitExpr) {
1980 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001981 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1982 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001983
1984 if (!InitExpr) {
1985 FD->setInvalidDecl();
1986 FD->removeInClassInitializer();
1987 return;
1988 }
1989
Peter Collingbournefef21892011-10-23 18:59:44 +00001990 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1991 FD->setInvalidDecl();
1992 FD->removeInClassInitializer();
1993 return;
1994 }
1995
Hans Wennborg471f9852012-09-18 15:58:06 +00001996 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1997 != DiagnosticsEngine::Ignored) {
1998 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1999 }
2000
Richard Smith7a614d82011-06-11 17:19:42 +00002001 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002002 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00002003 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002004 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00002005 << /*at end of ctor*/1 << InitExpr->getSourceRange();
2006 }
Sebastian Redl33deb352012-02-22 10:50:08 +00002007 Expr **Inits = &InitExpr;
2008 unsigned NumInits = 1;
2009 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002010 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002011 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002012 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00002013 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2014 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00002015 if (Init.isInvalid()) {
2016 FD->setInvalidDecl();
2017 return;
2018 }
Richard Smith7a614d82011-06-11 17:19:42 +00002019 }
2020
Richard Smith41956372013-01-14 22:39:08 +00002021 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002022 // The initialization of each base and member constitutes a
2023 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002024 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002025 if (Init.isInvalid()) {
2026 FD->setInvalidDecl();
2027 return;
2028 }
2029
2030 InitExpr = Init.release();
2031
2032 FD->setInClassInitializer(InitExpr);
2033}
2034
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002035/// \brief Find the direct and/or virtual base specifiers that
2036/// correspond to the given base type, for use in base initialization
2037/// within a constructor.
2038static bool FindBaseInitializer(Sema &SemaRef,
2039 CXXRecordDecl *ClassDecl,
2040 QualType BaseType,
2041 const CXXBaseSpecifier *&DirectBaseSpec,
2042 const CXXBaseSpecifier *&VirtualBaseSpec) {
2043 // First, check for a direct base class.
2044 DirectBaseSpec = 0;
2045 for (CXXRecordDecl::base_class_const_iterator Base
2046 = ClassDecl->bases_begin();
2047 Base != ClassDecl->bases_end(); ++Base) {
2048 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2049 // We found a direct base of this type. That's what we're
2050 // initializing.
2051 DirectBaseSpec = &*Base;
2052 break;
2053 }
2054 }
2055
2056 // Check for a virtual base class.
2057 // FIXME: We might be able to short-circuit this if we know in advance that
2058 // there are no virtual bases.
2059 VirtualBaseSpec = 0;
2060 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2061 // We haven't found a base yet; search the class hierarchy for a
2062 // virtual base class.
2063 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2064 /*DetectVirtual=*/false);
2065 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2066 BaseType, Paths)) {
2067 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2068 Path != Paths.end(); ++Path) {
2069 if (Path->back().Base->isVirtual()) {
2070 VirtualBaseSpec = Path->back().Base;
2071 break;
2072 }
2073 }
2074 }
2075 }
2076
2077 return DirectBaseSpec || VirtualBaseSpec;
2078}
2079
Sebastian Redl6df65482011-09-24 17:48:25 +00002080/// \brief Handle a C++ member initializer using braced-init-list syntax.
2081MemInitResult
2082Sema::ActOnMemInitializer(Decl *ConstructorD,
2083 Scope *S,
2084 CXXScopeSpec &SS,
2085 IdentifierInfo *MemberOrBase,
2086 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002087 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002088 SourceLocation IdLoc,
2089 Expr *InitList,
2090 SourceLocation EllipsisLoc) {
2091 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002092 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002093 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002094}
2095
2096/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002097MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002098Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002099 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002100 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002101 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002102 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002103 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002104 SourceLocation IdLoc,
2105 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002106 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002107 SourceLocation RParenLoc,
2108 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002109 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2110 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002111 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002112 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002113 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002114}
2115
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002116namespace {
2117
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002118// Callback to only accept typo corrections that can be a valid C++ member
2119// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002120class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2121 public:
2122 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2123 : ClassDecl(ClassDecl) {}
2124
2125 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2126 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2127 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2128 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2129 else
2130 return isa<TypeDecl>(ND);
2131 }
2132 return false;
2133 }
2134
2135 private:
2136 CXXRecordDecl *ClassDecl;
2137};
2138
2139}
2140
Sebastian Redl6df65482011-09-24 17:48:25 +00002141/// \brief Handle a C++ member initializer.
2142MemInitResult
2143Sema::BuildMemInitializer(Decl *ConstructorD,
2144 Scope *S,
2145 CXXScopeSpec &SS,
2146 IdentifierInfo *MemberOrBase,
2147 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002148 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002149 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002150 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002151 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002152 if (!ConstructorD)
2153 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002154
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002155 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002156
2157 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002158 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002159 if (!Constructor) {
2160 // The user wrote a constructor initializer on a function that is
2161 // not a C++ constructor. Ignore the error for now, because we may
2162 // have more member initializers coming; we'll diagnose it just
2163 // once in ActOnMemInitializers.
2164 return true;
2165 }
2166
2167 CXXRecordDecl *ClassDecl = Constructor->getParent();
2168
2169 // C++ [class.base.init]p2:
2170 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002171 // constructor's class and, if not found in that scope, are looked
2172 // up in the scope containing the constructor's definition.
2173 // [Note: if the constructor's class contains a member with the
2174 // same name as a direct or virtual base class of the class, a
2175 // mem-initializer-id naming the member or base class and composed
2176 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002177 // mem-initializer-id for the hidden base class may be specified
2178 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002179 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002180 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002181 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002182 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002183 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002184 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002185 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2186 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002187 if (EllipsisLoc.isValid())
2188 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002189 << MemberOrBase
2190 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002191
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002192 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002193 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002194 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002195 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002196 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002197 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002198 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002199
2200 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002201 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002202 } else if (DS.getTypeSpecType() == TST_decltype) {
2203 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002204 } else {
2205 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2206 LookupParsedName(R, S, &SS);
2207
2208 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2209 if (!TyD) {
2210 if (R.isAmbiguous()) return true;
2211
John McCallfd225442010-04-09 19:01:14 +00002212 // We don't want access-control diagnostics here.
2213 R.suppressDiagnostics();
2214
Douglas Gregor7a886e12010-01-19 06:46:48 +00002215 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2216 bool NotUnknownSpecialization = false;
2217 DeclContext *DC = computeDeclContext(SS, false);
2218 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2219 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2220
2221 if (!NotUnknownSpecialization) {
2222 // When the scope specifier can refer to a member of an unknown
2223 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002224 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2225 SS.getWithLocInContext(Context),
2226 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002227 if (BaseType.isNull())
2228 return true;
2229
Douglas Gregor7a886e12010-01-19 06:46:48 +00002230 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002231 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002232 }
2233 }
2234
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002235 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002236 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002237 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002238 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002239 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002240 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002241 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2242 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002243 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002244 // We have found a non-static data member with a similar
2245 // name to what was typed; complain and initialize that
2246 // member.
2247 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2248 << MemberOrBase << true << CorrectedQuotedStr
2249 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2250 Diag(Member->getLocation(), diag::note_previous_decl)
2251 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002252
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002253 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002254 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002255 const CXXBaseSpecifier *DirectBaseSpec;
2256 const CXXBaseSpecifier *VirtualBaseSpec;
2257 if (FindBaseInitializer(*this, ClassDecl,
2258 Context.getTypeDeclType(Type),
2259 DirectBaseSpec, VirtualBaseSpec)) {
2260 // We have found a direct or virtual base class with a
2261 // similar name to what was typed; complain and initialize
2262 // that base class.
2263 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002264 << MemberOrBase << false << CorrectedQuotedStr
2265 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002266
2267 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2268 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002269 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002270 diag::note_base_class_specified_here)
2271 << BaseSpec->getType()
2272 << BaseSpec->getSourceRange();
2273
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002274 TyD = Type;
2275 }
2276 }
2277 }
2278
Douglas Gregor7a886e12010-01-19 06:46:48 +00002279 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002280 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002281 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002282 return true;
2283 }
John McCall2b194412009-12-21 10:41:20 +00002284 }
2285
Douglas Gregor7a886e12010-01-19 06:46:48 +00002286 if (BaseType.isNull()) {
2287 BaseType = Context.getTypeDeclType(TyD);
2288 if (SS.isSet()) {
2289 NestedNameSpecifier *Qualifier =
2290 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002291
Douglas Gregor7a886e12010-01-19 06:46:48 +00002292 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002293 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002294 }
John McCall2b194412009-12-21 10:41:20 +00002295 }
2296 }
Mike Stump1eb44332009-09-09 15:08:12 +00002297
John McCalla93c9342009-12-07 02:54:59 +00002298 if (!TInfo)
2299 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002300
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002301 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002302}
2303
Chandler Carruth81c64772011-09-03 01:14:15 +00002304/// Checks a member initializer expression for cases where reference (or
2305/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002306static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2307 Expr *Init,
2308 SourceLocation IdLoc) {
2309 QualType MemberTy = Member->getType();
2310
2311 // We only handle pointers and references currently.
2312 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2313 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2314 return;
2315
2316 const bool IsPointer = MemberTy->isPointerType();
2317 if (IsPointer) {
2318 if (const UnaryOperator *Op
2319 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2320 // The only case we're worried about with pointers requires taking the
2321 // address.
2322 if (Op->getOpcode() != UO_AddrOf)
2323 return;
2324
2325 Init = Op->getSubExpr();
2326 } else {
2327 // We only handle address-of expression initializers for pointers.
2328 return;
2329 }
2330 }
2331
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002332 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2333 // Taking the address of a temporary will be diagnosed as a hard error.
2334 if (IsPointer)
2335 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002336
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002337 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2338 << Member << Init->getSourceRange();
2339 } else if (const DeclRefExpr *DRE
2340 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2341 // We only warn when referring to a non-reference parameter declaration.
2342 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2343 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002344 return;
2345
2346 S.Diag(Init->getExprLoc(),
2347 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2348 : diag::warn_bind_ref_member_to_parameter)
2349 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002350 } else {
2351 // Other initializers are fine.
2352 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002353 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002354
2355 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2356 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002357}
2358
John McCallf312b1e2010-08-26 23:41:50 +00002359MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002360Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002361 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002362 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2363 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2364 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002365 "Member must be a FieldDecl or IndirectFieldDecl");
2366
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002367 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002368 return true;
2369
Douglas Gregor464b2f02010-11-05 22:21:31 +00002370 if (Member->isInvalidDecl())
2371 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002372
John McCallb4190042009-11-04 23:02:40 +00002373 // Diagnose value-uses of fields to initialize themselves, e.g.
2374 // foo(foo)
2375 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002376 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002377 Expr **Args;
2378 unsigned NumArgs;
2379 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2380 Args = ParenList->getExprs();
2381 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002382 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002383 Args = InitList->getInits();
2384 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002385 } else {
2386 // Template instantiation doesn't reconstruct ParenListExprs for us.
2387 Args = &Init;
2388 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002389 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002390
Richard Trieude5e75c2012-06-14 23:11:34 +00002391 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2392 != DiagnosticsEngine::Ignored)
2393 for (unsigned i = 0; i < NumArgs; ++i)
2394 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002395 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002396 // initializing the i'th field, throw a warning if any of the >= i'th
2397 // fields are used, as they are not yet initialized.
2398 // Right now we are only handling the case where the i'th field uses
2399 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002400 // Also need to take into account that some fields may be initialized by
2401 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002402 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002403
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002404 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002405
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002406 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002407 // Can't check initialization for a member of dependent type or when
2408 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002409 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002410 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002411 bool InitList = false;
2412 if (isa<InitListExpr>(Init)) {
2413 InitList = true;
2414 Args = &Init;
2415 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002416
2417 if (isStdInitializerList(Member->getType(), 0)) {
2418 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2419 << /*at end of ctor*/1 << InitRange;
2420 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002421 }
2422
Chandler Carruth894aed92010-12-06 09:23:57 +00002423 // Initialize the member.
2424 InitializedEntity MemberEntity =
2425 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2426 : InitializedEntity::InitializeMember(IndirectMember, 0);
2427 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002428 InitList ? InitializationKind::CreateDirectList(IdLoc)
2429 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2430 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002431
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002432 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2433 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002434 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002435 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002436 if (MemberInit.isInvalid())
2437 return true;
2438
Richard Smith41956372013-01-14 22:39:08 +00002439 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002440 // The initialization of each base and member constitutes a
2441 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002442 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002443 if (MemberInit.isInvalid())
2444 return true;
2445
Richard Smithc83c2302012-12-19 01:39:02 +00002446 Init = MemberInit.get();
2447 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002448 }
2449
Chandler Carruth894aed92010-12-06 09:23:57 +00002450 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002451 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2452 InitRange.getBegin(), Init,
2453 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002454 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002455 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2456 InitRange.getBegin(), Init,
2457 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002458 }
Eli Friedman59c04372009-07-29 19:44:27 +00002459}
2460
John McCallf312b1e2010-08-26 23:41:50 +00002461MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002462Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002463 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002464 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002465 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002466 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002467 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002468 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002469
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002470 bool InitList = true;
2471 Expr **Args = &Init;
2472 unsigned NumArgs = 1;
2473 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2474 InitList = false;
2475 Args = ParenList->getExprs();
2476 NumArgs = ParenList->getNumExprs();
2477 }
2478
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002479 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002480 // Initialize the object.
2481 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2482 QualType(ClassDecl->getTypeForDecl(), 0));
2483 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002484 InitList ? InitializationKind::CreateDirectList(NameLoc)
2485 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2486 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002487 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2488 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002489 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002490 0);
Sean Hunt41717662011-02-26 19:13:13 +00002491 if (DelegationInit.isInvalid())
2492 return true;
2493
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002494 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2495 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002496
Richard Smith41956372013-01-14 22:39:08 +00002497 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002498 // The initialization of each base and member constitutes a
2499 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002500 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2501 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002502 if (DelegationInit.isInvalid())
2503 return true;
2504
Eli Friedmand21016f2012-05-19 23:35:23 +00002505 // If we are in a dependent context, template instantiation will
2506 // perform this type-checking again. Just save the arguments that we
2507 // received in a ParenListExpr.
2508 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2509 // of the information that we have about the base
2510 // initializer. However, deconstructing the ASTs is a dicey process,
2511 // and this approach is far more likely to get the corner cases right.
2512 if (CurContext->isDependentContext())
2513 DelegationInit = Owned(Init);
2514
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002515 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002516 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002517 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002518}
2519
2520MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002521Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002522 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002523 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002524 SourceLocation BaseLoc
2525 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002526
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002527 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2528 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2529 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2530
2531 // C++ [class.base.init]p2:
2532 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002533 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002534 // of that class, the mem-initializer is ill-formed. A
2535 // mem-initializer-list can initialize a base class using any
2536 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002537 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002538
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002539 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002540 if (EllipsisLoc.isValid()) {
2541 // This is a pack expansion.
2542 if (!BaseType->containsUnexpandedParameterPack()) {
2543 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002544 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002545
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002546 EllipsisLoc = SourceLocation();
2547 }
2548 } else {
2549 // Check for any unexpanded parameter packs.
2550 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2551 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002552
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002553 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002554 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002555 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002556
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002557 // Check for direct and virtual base classes.
2558 const CXXBaseSpecifier *DirectBaseSpec = 0;
2559 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2560 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002561 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2562 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002563 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002564
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002565 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2566 VirtualBaseSpec);
2567
2568 // C++ [base.class.init]p2:
2569 // Unless the mem-initializer-id names a nonstatic data member of the
2570 // constructor's class or a direct or virtual base of that class, the
2571 // mem-initializer is ill-formed.
2572 if (!DirectBaseSpec && !VirtualBaseSpec) {
2573 // If the class has any dependent bases, then it's possible that
2574 // one of those types will resolve to the same type as
2575 // BaseType. Therefore, just treat this as a dependent base
2576 // class initialization. FIXME: Should we try to check the
2577 // initialization anyway? It seems odd.
2578 if (ClassDecl->hasAnyDependentBases())
2579 Dependent = true;
2580 else
2581 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2582 << BaseType << Context.getTypeDeclType(ClassDecl)
2583 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2584 }
2585 }
2586
2587 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002588 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002589
Sebastian Redl6df65482011-09-24 17:48:25 +00002590 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2591 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002592 InitRange.getBegin(), Init,
2593 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002594 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002595
2596 // C++ [base.class.init]p2:
2597 // If a mem-initializer-id is ambiguous because it designates both
2598 // a direct non-virtual base class and an inherited virtual base
2599 // class, the mem-initializer is ill-formed.
2600 if (DirectBaseSpec && VirtualBaseSpec)
2601 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002602 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002603
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002604 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002605 if (!BaseSpec)
2606 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2607
2608 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002609 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002610 Expr **Args = &Init;
2611 unsigned NumArgs = 1;
2612 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002613 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002614 Args = ParenList->getExprs();
2615 NumArgs = ParenList->getNumExprs();
2616 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002617
2618 InitializedEntity BaseEntity =
2619 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2620 InitializationKind Kind =
2621 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2622 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2623 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002624 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2625 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002626 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002627 if (BaseInit.isInvalid())
2628 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002629
Richard Smith41956372013-01-14 22:39:08 +00002630 // C++11 [class.base.init]p7:
2631 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002632 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002633 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002634 if (BaseInit.isInvalid())
2635 return true;
2636
2637 // If we are in a dependent context, template instantiation will
2638 // perform this type-checking again. Just save the arguments that we
2639 // received in a ParenListExpr.
2640 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2641 // of the information that we have about the base
2642 // initializer. However, deconstructing the ASTs is a dicey process,
2643 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002644 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002645 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002646
Sean Huntcbb67482011-01-08 20:30:50 +00002647 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002648 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002649 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002650 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002651 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002652}
2653
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002654// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002655static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2656 if (T.isNull()) T = E->getType();
2657 QualType TargetType = SemaRef.BuildReferenceType(
2658 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002659 SourceLocation ExprLoc = E->getLocStart();
2660 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2661 TargetType, ExprLoc);
2662
2663 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2664 SourceRange(ExprLoc, ExprLoc),
2665 E->getSourceRange()).take();
2666}
2667
Anders Carlssone5ef7402010-04-23 03:10:23 +00002668/// ImplicitInitializerKind - How an implicit base or member initializer should
2669/// initialize its base or member.
2670enum ImplicitInitializerKind {
2671 IIK_Default,
2672 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002673 IIK_Move,
2674 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002675};
2676
Anders Carlssondefefd22010-04-23 02:00:02 +00002677static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002678BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002679 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002680 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002681 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002682 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002683 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002684 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2685 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002686
John McCall60d7b3a2010-08-24 06:29:42 +00002687 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002688
2689 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002690 case IIK_Inherit: {
2691 const CXXRecordDecl *Inherited =
2692 Constructor->getInheritedConstructor()->getParent();
2693 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2694 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2695 // C++11 [class.inhctor]p8:
2696 // Each expression in the expression-list is of the form
2697 // static_cast<T&&>(p), where p is the name of the corresponding
2698 // constructor parameter and T is the declared type of p.
2699 SmallVector<Expr*, 16> Args;
2700 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2701 ParmVarDecl *PD = Constructor->getParamDecl(I);
2702 ExprResult ArgExpr =
2703 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2704 VK_LValue, SourceLocation());
2705 if (ArgExpr.isInvalid())
2706 return true;
2707 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2708 }
2709
2710 InitializationKind InitKind = InitializationKind::CreateDirect(
2711 Constructor->getLocation(), SourceLocation(), SourceLocation());
2712 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2713 Args.data(), Args.size());
2714 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2715 break;
2716 }
2717 }
2718 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002719 case IIK_Default: {
2720 InitializationKind InitKind
2721 = InitializationKind::CreateDefault(Constructor->getLocation());
2722 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002723 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002724 break;
2725 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002726
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002727 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002728 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002729 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002730 ParmVarDecl *Param = Constructor->getParamDecl(0);
2731 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002732
Anders Carlssone5ef7402010-04-23 03:10:23 +00002733 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002734 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002735 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002736 Constructor->getLocation(), ParamType,
2737 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002738
Eli Friedman5f2987c2012-02-02 03:46:19 +00002739 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2740
Anders Carlssonc7957502010-04-24 22:02:54 +00002741 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002742 QualType ArgTy =
2743 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2744 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002745
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002746 if (Moving) {
2747 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2748 }
2749
John McCallf871d0c2010-08-07 06:22:56 +00002750 CXXCastPath BasePath;
2751 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002752 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2753 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002754 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002755 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002756
Anders Carlssone5ef7402010-04-23 03:10:23 +00002757 InitializationKind InitKind
2758 = InitializationKind::CreateDirect(Constructor->getLocation(),
2759 SourceLocation(), SourceLocation());
2760 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2761 &CopyCtorArg, 1);
2762 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002763 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002764 break;
2765 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002766 }
John McCall9ae2f072010-08-23 23:25:46 +00002767
Douglas Gregor53c374f2010-12-07 00:41:46 +00002768 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002769 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002770 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002771
Anders Carlssondefefd22010-04-23 02:00:02 +00002772 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002773 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002774 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2775 SourceLocation()),
2776 BaseSpec->isVirtual(),
2777 SourceLocation(),
2778 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002779 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002780 SourceLocation());
2781
Anders Carlssondefefd22010-04-23 02:00:02 +00002782 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002783}
2784
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002785static bool RefersToRValueRef(Expr *MemRef) {
2786 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2787 return Referenced->getType()->isRValueReferenceType();
2788}
2789
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002790static bool
2791BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002792 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002793 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002794 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002795 if (Field->isInvalidDecl())
2796 return true;
2797
Chandler Carruthf186b542010-06-29 23:50:44 +00002798 SourceLocation Loc = Constructor->getLocation();
2799
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002800 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2801 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002802 ParmVarDecl *Param = Constructor->getParamDecl(0);
2803 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002804
2805 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002806 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2807 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002808
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002809 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002810 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002811 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002812 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002813
Eli Friedman5f2987c2012-02-02 03:46:19 +00002814 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2815
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002816 if (Moving) {
2817 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2818 }
2819
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002820 // Build a reference to this field within the parameter.
2821 CXXScopeSpec SS;
2822 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2823 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002824 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2825 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002826 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002827 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002828 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002829 ParamType, Loc,
2830 /*IsArrow=*/false,
2831 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002832 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002833 /*FirstQualifierInScope=*/0,
2834 MemberLookup,
2835 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002836 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002837 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002838
2839 // C++11 [class.copy]p15:
2840 // - if a member m has rvalue reference type T&&, it is direct-initialized
2841 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002842 if (RefersToRValueRef(CtorArg.get())) {
2843 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002844 }
2845
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002846 // When the field we are copying is an array, create index variables for
2847 // each dimension of the array. We use these index variables to subscript
2848 // the source array, and other clients (e.g., CodeGen) will perform the
2849 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002850 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002851 QualType BaseType = Field->getType();
2852 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002853 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002854 while (const ConstantArrayType *Array
2855 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002856 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002857 // Create the iteration variable for this array index.
2858 IdentifierInfo *IterationVarName = 0;
2859 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002860 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002861 llvm::raw_svector_ostream OS(Str);
2862 OS << "__i" << IndexVariables.size();
2863 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2864 }
2865 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002866 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002867 IterationVarName, SizeType,
2868 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002869 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002870 IndexVariables.push_back(IterationVar);
2871
2872 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002873 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002874 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002875 assert(!IterationVarRef.isInvalid() &&
2876 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002877 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2878 assert(!IterationVarRef.isInvalid() &&
2879 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002880
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002881 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002882 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002883 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002884 Loc);
2885 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002886 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002887
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002888 BaseType = Array->getElementType();
2889 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002890
2891 // The array subscript expression is an lvalue, which is wrong for moving.
2892 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002893 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002894
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002895 // Construct the entity that we will be initializing. For an array, this
2896 // will be first element in the array, which may require several levels
2897 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002898 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002899 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002900 if (Indirect)
2901 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2902 else
2903 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002904 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2905 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2906 0,
2907 Entities.back()));
2908
2909 // Direct-initialize to use the copy constructor.
2910 InitializationKind InitKind =
2911 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2912
Sebastian Redl74e611a2011-09-04 18:14:28 +00002913 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002914 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002915 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002916
John McCall60d7b3a2010-08-24 06:29:42 +00002917 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002918 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002919 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002920 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002921 if (MemberInit.isInvalid())
2922 return true;
2923
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002924 if (Indirect) {
2925 assert(IndexVariables.size() == 0 &&
2926 "Indirect field improperly initialized");
2927 CXXMemberInit
2928 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2929 Loc, Loc,
2930 MemberInit.takeAs<Expr>(),
2931 Loc);
2932 } else
2933 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2934 Loc, MemberInit.takeAs<Expr>(),
2935 Loc,
2936 IndexVariables.data(),
2937 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002938 return false;
2939 }
2940
Richard Smith07b0fdc2013-03-18 21:12:30 +00002941 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
2942 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002943
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002944 QualType FieldBaseElementType =
2945 SemaRef.Context.getBaseElementType(Field->getType());
2946
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002947 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002948 InitializedEntity InitEntity
2949 = Indirect? InitializedEntity::InitializeMember(Indirect)
2950 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002951 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002952 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002953
2954 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002955 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002956 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002957
Douglas Gregor53c374f2010-12-07 00:41:46 +00002958 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002959 if (MemberInit.isInvalid())
2960 return true;
2961
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002962 if (Indirect)
2963 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2964 Indirect, Loc,
2965 Loc,
2966 MemberInit.get(),
2967 Loc);
2968 else
2969 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2970 Field, Loc, Loc,
2971 MemberInit.get(),
2972 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002973 return false;
2974 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002975
Sean Hunt1f2f3842011-05-17 00:19:05 +00002976 if (!Field->getParent()->isUnion()) {
2977 if (FieldBaseElementType->isReferenceType()) {
2978 SemaRef.Diag(Constructor->getLocation(),
2979 diag::err_uninitialized_member_in_ctor)
2980 << (int)Constructor->isImplicit()
2981 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2982 << 0 << Field->getDeclName();
2983 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2984 return true;
2985 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002986
Sean Hunt1f2f3842011-05-17 00:19:05 +00002987 if (FieldBaseElementType.isConstQualified()) {
2988 SemaRef.Diag(Constructor->getLocation(),
2989 diag::err_uninitialized_member_in_ctor)
2990 << (int)Constructor->isImplicit()
2991 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2992 << 1 << Field->getDeclName();
2993 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2994 return true;
2995 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002996 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002997
David Blaikie4e4d0842012-03-11 07:00:24 +00002998 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002999 FieldBaseElementType->isObjCRetainableType() &&
3000 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3001 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003002 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003003 // Default-initialize Objective-C pointers to NULL.
3004 CXXMemberInit
3005 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3006 Loc, Loc,
3007 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3008 Loc);
3009 return false;
3010 }
3011
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003012 // Nothing to initialize.
3013 CXXMemberInit = 0;
3014 return false;
3015}
John McCallf1860e52010-05-20 23:23:51 +00003016
3017namespace {
3018struct BaseAndFieldInfo {
3019 Sema &S;
3020 CXXConstructorDecl *Ctor;
3021 bool AnyErrorsInInits;
3022 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003023 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003024 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003025
3026 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3027 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003028 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3029 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003030 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003031 else if (Generated && Ctor->isMoveConstructor())
3032 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003033 else if (Ctor->getInheritedConstructor())
3034 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003035 else
3036 IIK = IIK_Default;
3037 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003038
3039 bool isImplicitCopyOrMove() const {
3040 switch (IIK) {
3041 case IIK_Copy:
3042 case IIK_Move:
3043 return true;
3044
3045 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003046 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003047 return false;
3048 }
David Blaikie30263482012-01-20 21:50:17 +00003049
3050 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003051 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003052
3053 bool addFieldInitializer(CXXCtorInitializer *Init) {
3054 AllToInit.push_back(Init);
3055
3056 // Check whether this initializer makes the field "used".
3057 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3058 S.UnusedPrivateFields.remove(Init->getAnyMember());
3059
3060 return false;
3061 }
John McCallf1860e52010-05-20 23:23:51 +00003062};
3063}
3064
Richard Smitha4950662011-09-19 13:34:43 +00003065/// \brief Determine whether the given indirect field declaration is somewhere
3066/// within an anonymous union.
3067static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3068 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3069 CEnd = F->chain_end();
3070 C != CEnd; ++C)
3071 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3072 if (Record->isUnion())
3073 return true;
3074
3075 return false;
3076}
3077
Douglas Gregorddb21472011-11-02 23:04:16 +00003078/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3079/// array type.
3080static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3081 if (T->isIncompleteArrayType())
3082 return true;
3083
3084 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3085 if (!ArrayT->getSize())
3086 return true;
3087
3088 T = ArrayT->getElementType();
3089 }
3090
3091 return false;
3092}
3093
Richard Smith7a614d82011-06-11 17:19:42 +00003094static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003095 FieldDecl *Field,
3096 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003097
Chandler Carruthe861c602010-06-30 02:59:29 +00003098 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003099 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3100 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003101
Richard Smith0b8220a2012-08-07 21:30:42 +00003102 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003103 // has a brace-or-equal-initializer, the entity is initialized as specified
3104 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003105 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003106 CXXCtorInitializer *Init;
3107 if (Indirect)
3108 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3109 SourceLocation(),
3110 SourceLocation(), 0,
3111 SourceLocation());
3112 else
3113 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3114 SourceLocation(),
3115 SourceLocation(), 0,
3116 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003117 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003118 }
3119
Richard Smithc115f632011-09-18 11:14:50 +00003120 // Don't build an implicit initializer for union members if none was
3121 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003122 if (Field->getParent()->isUnion() ||
3123 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003124 return false;
3125
Douglas Gregorddb21472011-11-02 23:04:16 +00003126 // Don't initialize incomplete or zero-length arrays.
3127 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3128 return false;
3129
John McCallf1860e52010-05-20 23:23:51 +00003130 // Don't try to build an implicit initializer if there were semantic
3131 // errors in any of the initializers (and therefore we might be
3132 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003133 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003134 return false;
3135
Sean Huntcbb67482011-01-08 20:30:50 +00003136 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003137 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3138 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003139 return true;
John McCallf1860e52010-05-20 23:23:51 +00003140
Richard Smith0b8220a2012-08-07 21:30:42 +00003141 if (!Init)
3142 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003143
Richard Smith0b8220a2012-08-07 21:30:42 +00003144 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003145}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003146
3147bool
3148Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3149 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003150 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003151 Constructor->setNumCtorInitializers(1);
3152 CXXCtorInitializer **initializer =
3153 new (Context) CXXCtorInitializer*[1];
3154 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3155 Constructor->setCtorInitializers(initializer);
3156
Sean Huntb76af9c2011-05-03 23:05:34 +00003157 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003158 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003159 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3160 }
3161
Sean Huntc1598702011-05-05 00:05:47 +00003162 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003163
Sean Hunt059ce0d2011-05-01 07:04:31 +00003164 return false;
3165}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003166
David Blaikie93c86172013-01-17 05:26:25 +00003167bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3168 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003169 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003170 // Just store the initializers as written, they will be checked during
3171 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003172 if (!Initializers.empty()) {
3173 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003174 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003175 new (Context) CXXCtorInitializer*[Initializers.size()];
3176 memcpy(baseOrMemberInitializers, Initializers.data(),
3177 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003178 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003179 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003180
3181 // Let template instantiation know whether we had errors.
3182 if (AnyErrors)
3183 Constructor->setInvalidDecl();
3184
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003185 return false;
3186 }
3187
John McCallf1860e52010-05-20 23:23:51 +00003188 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003189
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003190 // We need to build the initializer AST according to order of construction
3191 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003192 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003193 if (!ClassDecl)
3194 return true;
3195
Eli Friedman80c30da2009-11-09 19:20:36 +00003196 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003197
David Blaikie93c86172013-01-17 05:26:25 +00003198 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003199 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003200
3201 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003202 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003203 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003204 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003205 }
3206
Anders Carlsson711f34a2010-04-21 19:52:01 +00003207 // Keep track of the direct virtual bases.
3208 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3209 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3210 E = ClassDecl->bases_end(); I != E; ++I) {
3211 if (I->isVirtual())
3212 DirectVBases.insert(I);
3213 }
3214
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003215 // Push virtual bases before others.
3216 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3217 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3218
Sean Huntcbb67482011-01-08 20:30:50 +00003219 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003220 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3221 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003222 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003223 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003224 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003225 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003226 VBase, IsInheritedVirtualBase,
3227 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003228 HadError = true;
3229 continue;
3230 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003231
John McCallf1860e52010-05-20 23:23:51 +00003232 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003233 }
3234 }
Mike Stump1eb44332009-09-09 15:08:12 +00003235
John McCallf1860e52010-05-20 23:23:51 +00003236 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003237 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3238 E = ClassDecl->bases_end(); Base != E; ++Base) {
3239 // Virtuals are in the virtual base list and already constructed.
3240 if (Base->isVirtual())
3241 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003242
Sean Huntcbb67482011-01-08 20:30:50 +00003243 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003244 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3245 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003246 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003247 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003248 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003249 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003250 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003251 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003252 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003253 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003254
John McCallf1860e52010-05-20 23:23:51 +00003255 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003256 }
3257 }
Mike Stump1eb44332009-09-09 15:08:12 +00003258
John McCallf1860e52010-05-20 23:23:51 +00003259 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003260 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3261 MemEnd = ClassDecl->decls_end();
3262 Mem != MemEnd; ++Mem) {
3263 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003264 // C++ [class.bit]p2:
3265 // A declaration for a bit-field that omits the identifier declares an
3266 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3267 // initialized.
3268 if (F->isUnnamedBitfield())
3269 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003270
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003271 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003272 // handle anonymous struct/union fields based on their individual
3273 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003274 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003275 continue;
3276
3277 if (CollectFieldInitializer(*this, Info, F))
3278 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003279 continue;
3280 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003281
3282 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003283 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003284 continue;
3285
3286 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3287 if (F->getType()->isIncompleteArrayType()) {
3288 assert(ClassDecl->hasFlexibleArrayMember() &&
3289 "Incomplete array type is not valid");
3290 continue;
3291 }
3292
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003293 // Initialize each field of an anonymous struct individually.
3294 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3295 HadError = true;
3296
3297 continue;
3298 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003299 }
Mike Stump1eb44332009-09-09 15:08:12 +00003300
David Blaikie93c86172013-01-17 05:26:25 +00003301 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003302 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003303 Constructor->setNumCtorInitializers(NumInitializers);
3304 CXXCtorInitializer **baseOrMemberInitializers =
3305 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003306 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003307 NumInitializers * sizeof(CXXCtorInitializer*));
3308 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003309
John McCallef027fe2010-03-16 21:39:52 +00003310 // Constructors implicitly reference the base and member
3311 // destructors.
3312 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3313 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003314 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003315
3316 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003317}
3318
David Blaikieee000bb2013-01-17 08:49:22 +00003319static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003320 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003321 const RecordDecl *RD = RT->getDecl();
3322 if (RD->isAnonymousStructOrUnion()) {
3323 for (RecordDecl::field_iterator Field = RD->field_begin(),
3324 E = RD->field_end(); Field != E; ++Field)
3325 PopulateKeysForFields(*Field, IdealInits);
3326 return;
3327 }
Eli Friedman6347f422009-07-21 19:28:10 +00003328 }
David Blaikieee000bb2013-01-17 08:49:22 +00003329 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003330}
3331
Anders Carlssonea356fb2010-04-02 05:42:15 +00003332static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003333 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003334}
3335
Anders Carlssonea356fb2010-04-02 05:42:15 +00003336static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003337 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003338 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003339 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003340
David Blaikieee000bb2013-01-17 08:49:22 +00003341 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003342}
3343
David Blaikie93c86172013-01-17 05:26:25 +00003344static void DiagnoseBaseOrMemInitializerOrder(
3345 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3346 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003347 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003348 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003349
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003350 // Don't check initializers order unless the warning is enabled at the
3351 // location of at least one initializer.
3352 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003353 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003354 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003355 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3356 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003357 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003358 ShouldCheckOrder = true;
3359 break;
3360 }
3361 }
3362 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003363 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003364
John McCalld6ca8da2010-04-10 07:37:23 +00003365 // Build the list of bases and members in the order that they'll
3366 // actually be initialized. The explicit initializers should be in
3367 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003368 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003369
Anders Carlsson071d6102010-04-02 03:38:04 +00003370 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3371
John McCalld6ca8da2010-04-10 07:37:23 +00003372 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003373 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003374 ClassDecl->vbases_begin(),
3375 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003376 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003377
John McCalld6ca8da2010-04-10 07:37:23 +00003378 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003379 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003380 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003381 if (Base->isVirtual())
3382 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003383 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003384 }
Mike Stump1eb44332009-09-09 15:08:12 +00003385
John McCalld6ca8da2010-04-10 07:37:23 +00003386 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003387 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003388 E = ClassDecl->field_end(); Field != E; ++Field) {
3389 if (Field->isUnnamedBitfield())
3390 continue;
3391
David Blaikieee000bb2013-01-17 08:49:22 +00003392 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003393 }
3394
John McCalld6ca8da2010-04-10 07:37:23 +00003395 unsigned NumIdealInits = IdealInitKeys.size();
3396 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003397
Sean Huntcbb67482011-01-08 20:30:50 +00003398 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003399 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003400 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003401 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003402
3403 // Scan forward to try to find this initializer in the idealized
3404 // initializers list.
3405 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3406 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003407 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003408
3409 // If we didn't find this initializer, it must be because we
3410 // scanned past it on a previous iteration. That can only
3411 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003412 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003413 Sema::SemaDiagnosticBuilder D =
3414 SemaRef.Diag(PrevInit->getSourceLocation(),
3415 diag::warn_initializer_out_of_order);
3416
Francois Pichet00eb3f92010-12-04 09:14:42 +00003417 if (PrevInit->isAnyMemberInitializer())
3418 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003419 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003420 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003421
Francois Pichet00eb3f92010-12-04 09:14:42 +00003422 if (Init->isAnyMemberInitializer())
3423 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003424 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003425 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003426
3427 // Move back to the initializer's location in the ideal list.
3428 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3429 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003430 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003431
3432 assert(IdealIndex != NumIdealInits &&
3433 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003434 }
John McCalld6ca8da2010-04-10 07:37:23 +00003435
3436 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003437 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003438}
3439
John McCall3c3ccdb2010-04-10 09:28:51 +00003440namespace {
3441bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003442 CXXCtorInitializer *Init,
3443 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003444 if (!PrevInit) {
3445 PrevInit = Init;
3446 return false;
3447 }
3448
Douglas Gregordc392c12013-03-25 23:28:23 +00003449 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003450 S.Diag(Init->getSourceLocation(),
3451 diag::err_multiple_mem_initialization)
3452 << Field->getDeclName()
3453 << Init->getSourceRange();
3454 else {
John McCallf4c73712011-01-19 06:33:43 +00003455 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003456 assert(BaseClass && "neither field nor base");
3457 S.Diag(Init->getSourceLocation(),
3458 diag::err_multiple_base_initialization)
3459 << QualType(BaseClass, 0)
3460 << Init->getSourceRange();
3461 }
3462 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3463 << 0 << PrevInit->getSourceRange();
3464
3465 return true;
3466}
3467
Sean Huntcbb67482011-01-08 20:30:50 +00003468typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003469typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3470
3471bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003472 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003473 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003474 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003475 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003476 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003477
3478 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003479 if (Parent->isUnion()) {
3480 UnionEntry &En = Unions[Parent];
3481 if (En.first && En.first != Child) {
3482 S.Diag(Init->getSourceLocation(),
3483 diag::err_multiple_mem_union_initialization)
3484 << Field->getDeclName()
3485 << Init->getSourceRange();
3486 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3487 << 0 << En.second->getSourceRange();
3488 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003489 }
3490 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003491 En.first = Child;
3492 En.second = Init;
3493 }
David Blaikie6fe29652011-11-17 06:01:57 +00003494 if (!Parent->isAnonymousStructOrUnion())
3495 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003496 }
3497
3498 Child = Parent;
3499 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003500 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003501
3502 return false;
3503}
3504}
3505
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003506/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003507void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003508 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003509 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003510 bool AnyErrors) {
3511 if (!ConstructorDecl)
3512 return;
3513
3514 AdjustDeclIfTemplate(ConstructorDecl);
3515
3516 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003517 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003518
3519 if (!Constructor) {
3520 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3521 return;
3522 }
3523
John McCall3c3ccdb2010-04-10 09:28:51 +00003524 // Mapping for the duplicate initializers check.
3525 // For member initializers, this is keyed with a FieldDecl*.
3526 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003527 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003528
3529 // Mapping for the inconsistent anonymous-union initializers check.
3530 RedundantUnionMap MemberUnions;
3531
Anders Carlssonea356fb2010-04-02 05:42:15 +00003532 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003533 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003534 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003535
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003536 // Set the source order index.
3537 Init->setSourceOrder(i);
3538
Francois Pichet00eb3f92010-12-04 09:14:42 +00003539 if (Init->isAnyMemberInitializer()) {
3540 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003541 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3542 CheckRedundantUnionInit(*this, Init, MemberUnions))
3543 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003544 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003545 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3546 if (CheckRedundantInit(*this, Init, Members[Key]))
3547 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003548 } else {
3549 assert(Init->isDelegatingInitializer());
3550 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003551 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003552 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003553 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003554 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003555 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003556 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003557 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003558 // Return immediately as the initializer is set.
3559 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003560 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003561 }
3562
Anders Carlssonea356fb2010-04-02 05:42:15 +00003563 if (HadError)
3564 return;
3565
David Blaikie93c86172013-01-17 05:26:25 +00003566 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003567
David Blaikie93c86172013-01-17 05:26:25 +00003568 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003569}
3570
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003571void
John McCallef027fe2010-03-16 21:39:52 +00003572Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3573 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003574 // Ignore dependent contexts. Also ignore unions, since their members never
3575 // have destructors implicitly called.
3576 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003577 return;
John McCall58e6f342010-03-16 05:22:47 +00003578
3579 // FIXME: all the access-control diagnostics are positioned on the
3580 // field/base declaration. That's probably good; that said, the
3581 // user might reasonably want to know why the destructor is being
3582 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003583
Anders Carlsson9f853df2009-11-17 04:44:12 +00003584 // Non-static data members.
3585 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3586 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003587 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003588 if (Field->isInvalidDecl())
3589 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003590
3591 // Don't destroy incomplete or zero-length arrays.
3592 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3593 continue;
3594
Anders Carlsson9f853df2009-11-17 04:44:12 +00003595 QualType FieldType = Context.getBaseElementType(Field->getType());
3596
3597 const RecordType* RT = FieldType->getAs<RecordType>();
3598 if (!RT)
3599 continue;
3600
3601 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003602 if (FieldClassDecl->isInvalidDecl())
3603 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003604 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003605 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003606 // The destructor for an implicit anonymous union member is never invoked.
3607 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3608 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003609
Douglas Gregordb89f282010-07-01 22:47:18 +00003610 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003611 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003612 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003613 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003614 << Field->getDeclName()
3615 << FieldType);
3616
Eli Friedman5f2987c2012-02-02 03:46:19 +00003617 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003618 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003619 }
3620
John McCall58e6f342010-03-16 05:22:47 +00003621 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3622
Anders Carlsson9f853df2009-11-17 04:44:12 +00003623 // Bases.
3624 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3625 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003626 // Bases are always records in a well-formed non-dependent class.
3627 const RecordType *RT = Base->getType()->getAs<RecordType>();
3628
3629 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003630 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003631 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003632
John McCall58e6f342010-03-16 05:22:47 +00003633 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003634 // If our base class is invalid, we probably can't get its dtor anyway.
3635 if (BaseClassDecl->isInvalidDecl())
3636 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003637 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003638 continue;
John McCall58e6f342010-03-16 05:22:47 +00003639
Douglas Gregordb89f282010-07-01 22:47:18 +00003640 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003641 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003642
3643 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003644 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003645 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003646 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003647 << Base->getSourceRange(),
3648 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003649
Eli Friedman5f2987c2012-02-02 03:46:19 +00003650 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003651 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003652 }
3653
3654 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003655 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3656 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003657
3658 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003659 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003660
3661 // Ignore direct virtual bases.
3662 if (DirectVirtualBases.count(RT))
3663 continue;
3664
John McCall58e6f342010-03-16 05:22:47 +00003665 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003666 // If our base class is invalid, we probably can't get its dtor anyway.
3667 if (BaseClassDecl->isInvalidDecl())
3668 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003669 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003670 continue;
John McCall58e6f342010-03-16 05:22:47 +00003671
Douglas Gregordb89f282010-07-01 22:47:18 +00003672 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003673 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003674 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003675 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003676 << VBase->getType(),
3677 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003678
Eli Friedman5f2987c2012-02-02 03:46:19 +00003679 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003680 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003681 }
3682}
3683
John McCalld226f652010-08-21 09:40:31 +00003684void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003685 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003686 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003687
Mike Stump1eb44332009-09-09 15:08:12 +00003688 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003689 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003690 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003691}
3692
Mike Stump1eb44332009-09-09 15:08:12 +00003693bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003694 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003695 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3696 unsigned DiagID;
3697 AbstractDiagSelID SelID;
3698
3699 public:
3700 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3701 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3702
3703 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003704 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003705 if (SelID == -1)
3706 S.Diag(Loc, DiagID) << T;
3707 else
3708 S.Diag(Loc, DiagID) << SelID << T;
3709 }
3710 } Diagnoser(DiagID, SelID);
3711
3712 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003713}
3714
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003715bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003716 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003717 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003718 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003719
Anders Carlsson11f21a02009-03-23 19:10:31 +00003720 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003721 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003722
Ted Kremenek6217b802009-07-29 21:53:49 +00003723 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003724 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003725 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003726 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003727
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003728 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003729 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003730 }
Mike Stump1eb44332009-09-09 15:08:12 +00003731
Ted Kremenek6217b802009-07-29 21:53:49 +00003732 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003733 if (!RT)
3734 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003735
John McCall86ff3082010-02-04 22:26:26 +00003736 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003737
John McCall94c3b562010-08-18 09:41:07 +00003738 // We can't answer whether something is abstract until it has a
3739 // definition. If it's currently being defined, we'll walk back
3740 // over all the declarations when we have a full definition.
3741 const CXXRecordDecl *Def = RD->getDefinition();
3742 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003743 return false;
3744
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003745 if (!RD->isAbstract())
3746 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003748 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003749 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003750
John McCall94c3b562010-08-18 09:41:07 +00003751 return true;
3752}
3753
3754void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3755 // Check if we've already emitted the list of pure virtual functions
3756 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003757 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003758 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003759
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003760 CXXFinalOverriderMap FinalOverriders;
3761 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003763 // Keep a set of seen pure methods so we won't diagnose the same method
3764 // more than once.
3765 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3766
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003767 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3768 MEnd = FinalOverriders.end();
3769 M != MEnd;
3770 ++M) {
3771 for (OverridingMethods::iterator SO = M->second.begin(),
3772 SOEnd = M->second.end();
3773 SO != SOEnd; ++SO) {
3774 // C++ [class.abstract]p4:
3775 // A class is abstract if it contains or inherits at least one
3776 // pure virtual function for which the final overrider is pure
3777 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003778
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003779 //
3780 if (SO->second.size() != 1)
3781 continue;
3782
3783 if (!SO->second.front().Method->isPure())
3784 continue;
3785
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003786 if (!SeenPureMethods.insert(SO->second.front().Method))
3787 continue;
3788
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003789 Diag(SO->second.front().Method->getLocation(),
3790 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003791 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003792 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003793 }
3794
3795 if (!PureVirtualClassDiagSet)
3796 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3797 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003798}
3799
Anders Carlsson8211eff2009-03-24 01:19:16 +00003800namespace {
John McCall94c3b562010-08-18 09:41:07 +00003801struct AbstractUsageInfo {
3802 Sema &S;
3803 CXXRecordDecl *Record;
3804 CanQualType AbstractType;
3805 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003806
John McCall94c3b562010-08-18 09:41:07 +00003807 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3808 : S(S), Record(Record),
3809 AbstractType(S.Context.getCanonicalType(
3810 S.Context.getTypeDeclType(Record))),
3811 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003812
John McCall94c3b562010-08-18 09:41:07 +00003813 void DiagnoseAbstractType() {
3814 if (Invalid) return;
3815 S.DiagnoseAbstractType(Record);
3816 Invalid = true;
3817 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003818
John McCall94c3b562010-08-18 09:41:07 +00003819 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3820};
3821
3822struct CheckAbstractUsage {
3823 AbstractUsageInfo &Info;
3824 const NamedDecl *Ctx;
3825
3826 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3827 : Info(Info), Ctx(Ctx) {}
3828
3829 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3830 switch (TL.getTypeLocClass()) {
3831#define ABSTRACT_TYPELOC(CLASS, PARENT)
3832#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003833 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003834#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003835 }
John McCall94c3b562010-08-18 09:41:07 +00003836 }
Mike Stump1eb44332009-09-09 15:08:12 +00003837
John McCall94c3b562010-08-18 09:41:07 +00003838 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3839 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3840 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003841 if (!TL.getArg(I))
3842 continue;
3843
John McCall94c3b562010-08-18 09:41:07 +00003844 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3845 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003846 }
John McCall94c3b562010-08-18 09:41:07 +00003847 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003848
John McCall94c3b562010-08-18 09:41:07 +00003849 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3850 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3851 }
Mike Stump1eb44332009-09-09 15:08:12 +00003852
John McCall94c3b562010-08-18 09:41:07 +00003853 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3854 // Visit the type parameters from a permissive context.
3855 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3856 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3857 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3858 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3859 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3860 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003861 }
John McCall94c3b562010-08-18 09:41:07 +00003862 }
Mike Stump1eb44332009-09-09 15:08:12 +00003863
John McCall94c3b562010-08-18 09:41:07 +00003864 // Visit pointee types from a permissive context.
3865#define CheckPolymorphic(Type) \
3866 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3867 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3868 }
3869 CheckPolymorphic(PointerTypeLoc)
3870 CheckPolymorphic(ReferenceTypeLoc)
3871 CheckPolymorphic(MemberPointerTypeLoc)
3872 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003873 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003874
John McCall94c3b562010-08-18 09:41:07 +00003875 /// Handle all the types we haven't given a more specific
3876 /// implementation for above.
3877 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3878 // Every other kind of type that we haven't called out already
3879 // that has an inner type is either (1) sugar or (2) contains that
3880 // inner type in some way as a subobject.
3881 if (TypeLoc Next = TL.getNextTypeLoc())
3882 return Visit(Next, Sel);
3883
3884 // If there's no inner type and we're in a permissive context,
3885 // don't diagnose.
3886 if (Sel == Sema::AbstractNone) return;
3887
3888 // Check whether the type matches the abstract type.
3889 QualType T = TL.getType();
3890 if (T->isArrayType()) {
3891 Sel = Sema::AbstractArrayType;
3892 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003893 }
John McCall94c3b562010-08-18 09:41:07 +00003894 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3895 if (CT != Info.AbstractType) return;
3896
3897 // It matched; do some magic.
3898 if (Sel == Sema::AbstractArrayType) {
3899 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3900 << T << TL.getSourceRange();
3901 } else {
3902 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3903 << Sel << T << TL.getSourceRange();
3904 }
3905 Info.DiagnoseAbstractType();
3906 }
3907};
3908
3909void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3910 Sema::AbstractDiagSelID Sel) {
3911 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3912}
3913
3914}
3915
3916/// Check for invalid uses of an abstract type in a method declaration.
3917static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3918 CXXMethodDecl *MD) {
3919 // No need to do the check on definitions, which require that
3920 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003921 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003922 return;
3923
3924 // For safety's sake, just ignore it if we don't have type source
3925 // information. This should never happen for non-implicit methods,
3926 // but...
3927 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3928 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3929}
3930
3931/// Check for invalid uses of an abstract type within a class definition.
3932static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3933 CXXRecordDecl *RD) {
3934 for (CXXRecordDecl::decl_iterator
3935 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3936 Decl *D = *I;
3937 if (D->isImplicit()) continue;
3938
3939 // Methods and method templates.
3940 if (isa<CXXMethodDecl>(D)) {
3941 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3942 } else if (isa<FunctionTemplateDecl>(D)) {
3943 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3944 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3945
3946 // Fields and static variables.
3947 } else if (isa<FieldDecl>(D)) {
3948 FieldDecl *FD = cast<FieldDecl>(D);
3949 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3950 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3951 } else if (isa<VarDecl>(D)) {
3952 VarDecl *VD = cast<VarDecl>(D);
3953 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3954 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3955
3956 // Nested classes and class templates.
3957 } else if (isa<CXXRecordDecl>(D)) {
3958 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3959 } else if (isa<ClassTemplateDecl>(D)) {
3960 CheckAbstractClassUsage(Info,
3961 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3962 }
3963 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003964}
3965
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003966/// \brief Perform semantic checks on a class definition that has been
3967/// completing, introducing implicitly-declared members, checking for
3968/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003969void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003970 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003971 return;
3972
John McCall94c3b562010-08-18 09:41:07 +00003973 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3974 AbstractUsageInfo Info(*this, Record);
3975 CheckAbstractClassUsage(Info, Record);
3976 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003977
3978 // If this is not an aggregate type and has no user-declared constructor,
3979 // complain about any non-static data members of reference or const scalar
3980 // type, since they will never get initializers.
3981 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003982 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3983 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003984 bool Complained = false;
3985 for (RecordDecl::field_iterator F = Record->field_begin(),
3986 FEnd = Record->field_end();
3987 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003988 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003989 continue;
3990
Douglas Gregor325e5932010-04-15 00:00:53 +00003991 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003992 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003993 if (!Complained) {
3994 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3995 << Record->getTagKind() << Record;
3996 Complained = true;
3997 }
3998
3999 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4000 << F->getType()->isReferenceType()
4001 << F->getDeclName();
4002 }
4003 }
4004 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004005
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004006 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004007 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004008
4009 if (Record->getIdentifier()) {
4010 // C++ [class.mem]p13:
4011 // If T is the name of a class, then each of the following shall have a
4012 // name different from T:
4013 // - every member of every anonymous union that is a member of class T.
4014 //
4015 // C++ [class.mem]p14:
4016 // In addition, if class T has a user-declared constructor (12.1), every
4017 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004018 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4019 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4020 ++I) {
4021 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004022 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4023 isa<IndirectFieldDecl>(D)) {
4024 Diag(D->getLocation(), diag::err_member_name_of_class)
4025 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004026 break;
4027 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004028 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004029 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004030
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004031 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004032 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004033 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004034 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004035 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4036 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4037 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004038
David Blaikieb6b5b972012-09-21 03:21:07 +00004039 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4040 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4041 DiagnoseAbstractType(Record);
4042 }
4043
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004044 if (!Record->isDependentType()) {
4045 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4046 MEnd = Record->method_end();
4047 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004048 // See if a method overloads virtual methods in a base
4049 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004050 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004051 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004052
4053 // Check whether the explicitly-defaulted special members are valid.
4054 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4055 CheckExplicitlyDefaultedSpecialMember(*M);
4056
4057 // For an explicitly defaulted or deleted special member, we defer
4058 // determining triviality until the class is complete. That time is now!
4059 if (!M->isImplicit() && !M->isUserProvided()) {
4060 CXXSpecialMember CSM = getSpecialMember(*M);
4061 if (CSM != CXXInvalid) {
4062 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4063
4064 // Inform the class that we've finished declaring this member.
4065 Record->finishedDefaultedOrDeletedMember(*M);
4066 }
4067 }
4068 }
4069 }
4070
4071 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4072 // function that is not a constructor declares that member function to be
4073 // const. [...] The class of which that function is a member shall be
4074 // a literal type.
4075 //
4076 // If the class has virtual bases, any constexpr members will already have
4077 // been diagnosed by the checks performed on the member declaration, so
4078 // suppress this (less useful) diagnostic.
4079 //
4080 // We delay this until we know whether an explicitly-defaulted (or deleted)
4081 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004082 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004083 !Record->isLiteral() && !Record->getNumVBases()) {
4084 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4085 MEnd = Record->method_end();
4086 M != MEnd; ++M) {
4087 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4088 switch (Record->getTemplateSpecializationKind()) {
4089 case TSK_ImplicitInstantiation:
4090 case TSK_ExplicitInstantiationDeclaration:
4091 case TSK_ExplicitInstantiationDefinition:
4092 // If a template instantiates to a non-literal type, but its members
4093 // instantiate to constexpr functions, the template is technically
4094 // ill-formed, but we allow it for sanity.
4095 continue;
4096
4097 case TSK_Undeclared:
4098 case TSK_ExplicitSpecialization:
4099 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4100 diag::err_constexpr_method_non_literal);
4101 break;
4102 }
4103
4104 // Only produce one error per class.
4105 break;
4106 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004107 }
4108 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004109
Richard Smith07b0fdc2013-03-18 21:12:30 +00004110 // Declare inheriting constructors. We do this eagerly here because:
4111 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004112 // constructors from different classes.
4113 // - The lazy declaration of the other implicit constructors is so as to not
4114 // waste space and performance on classes that are not meant to be
4115 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004116 // have inheriting constructors.
4117 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004118}
4119
Richard Smith7756afa2012-06-10 05:43:50 +00004120/// Is the special member function which would be selected to perform the
4121/// specified operation on the specified class type a constexpr constructor?
4122static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4123 Sema::CXXSpecialMember CSM,
4124 bool ConstArg) {
4125 Sema::SpecialMemberOverloadResult *SMOR =
4126 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4127 false, false, false, false);
4128 if (!SMOR || !SMOR->getMethod())
4129 // A constructor we wouldn't select can't be "involved in initializing"
4130 // anything.
4131 return true;
4132 return SMOR->getMethod()->isConstexpr();
4133}
4134
4135/// Determine whether the specified special member function would be constexpr
4136/// if it were implicitly defined.
4137static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4138 Sema::CXXSpecialMember CSM,
4139 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004140 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004141 return false;
4142
4143 // C++11 [dcl.constexpr]p4:
4144 // In the definition of a constexpr constructor [...]
4145 switch (CSM) {
4146 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004147 // Since default constructor lookup is essentially trivial (and cannot
4148 // involve, for instance, template instantiation), we compute whether a
4149 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4150 //
4151 // This is important for performance; we need to know whether the default
4152 // constructor is constexpr to determine whether the type is a literal type.
4153 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4154
Richard Smith7756afa2012-06-10 05:43:50 +00004155 case Sema::CXXCopyConstructor:
4156 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004157 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004158 break;
4159
4160 case Sema::CXXCopyAssignment:
4161 case Sema::CXXMoveAssignment:
4162 case Sema::CXXDestructor:
4163 case Sema::CXXInvalid:
4164 return false;
4165 }
4166
4167 // -- if the class is a non-empty union, or for each non-empty anonymous
4168 // union member of a non-union class, exactly one non-static data member
4169 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004170 //
4171 // If we squint, this is guaranteed, since exactly one non-static data member
4172 // will be initialized (if the constructor isn't deleted), we just don't know
4173 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004174 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004175 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004176
4177 // -- the class shall not have any virtual base classes;
4178 if (ClassDecl->getNumVBases())
4179 return false;
4180
4181 // -- every constructor involved in initializing [...] base class
4182 // sub-objects shall be a constexpr constructor;
4183 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4184 BEnd = ClassDecl->bases_end();
4185 B != BEnd; ++B) {
4186 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4187 if (!BaseType) continue;
4188
4189 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4190 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4191 return false;
4192 }
4193
4194 // -- every constructor involved in initializing non-static data members
4195 // [...] shall be a constexpr constructor;
4196 // -- every non-static data member and base class sub-object shall be
4197 // initialized
4198 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4199 FEnd = ClassDecl->field_end();
4200 F != FEnd; ++F) {
4201 if (F->isInvalidDecl())
4202 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004203 if (const RecordType *RecordTy =
4204 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004205 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4206 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4207 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004208 }
4209 }
4210
4211 // All OK, it's constexpr!
4212 return true;
4213}
4214
Richard Smithb9d0b762012-07-27 04:22:15 +00004215static Sema::ImplicitExceptionSpecification
4216computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4217 switch (S.getSpecialMember(MD)) {
4218 case Sema::CXXDefaultConstructor:
4219 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4220 case Sema::CXXCopyConstructor:
4221 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4222 case Sema::CXXCopyAssignment:
4223 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4224 case Sema::CXXMoveConstructor:
4225 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4226 case Sema::CXXMoveAssignment:
4227 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4228 case Sema::CXXDestructor:
4229 return S.ComputeDefaultedDtorExceptionSpec(MD);
4230 case Sema::CXXInvalid:
4231 break;
4232 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004233 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4234 "only special members have implicit exception specs");
4235 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004236}
4237
Richard Smithdd25e802012-07-30 23:48:14 +00004238static void
4239updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4240 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4241 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4242 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004243 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4244 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004245}
4246
Richard Smithb9d0b762012-07-27 04:22:15 +00004247void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4248 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4249 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4250 return;
4251
Richard Smithdd25e802012-07-30 23:48:14 +00004252 // Evaluate the exception specification.
4253 ImplicitExceptionSpecification ExceptSpec =
4254 computeImplicitExceptionSpec(*this, Loc, MD);
4255
4256 // Update the type of the special member to use it.
4257 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4258
4259 // A user-provided destructor can be defined outside the class. When that
4260 // happens, be sure to update the exception specification on both
4261 // declarations.
4262 const FunctionProtoType *CanonicalFPT =
4263 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4264 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4265 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4266 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004267}
4268
Richard Smith3003e1d2012-05-15 04:39:51 +00004269void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4270 CXXRecordDecl *RD = MD->getParent();
4271 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004272
Richard Smith3003e1d2012-05-15 04:39:51 +00004273 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4274 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004275
4276 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004277 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004278 bool First = MD == MD->getCanonicalDecl();
4279
4280 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004281
4282 // C++11 [dcl.fct.def.default]p1:
4283 // A function that is explicitly defaulted shall
4284 // -- be a special member function (checked elsewhere),
4285 // -- have the same type (except for ref-qualifiers, and except that a
4286 // copy operation can take a non-const reference) as an implicit
4287 // declaration, and
4288 // -- not have default arguments.
4289 unsigned ExpectedParams = 1;
4290 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4291 ExpectedParams = 0;
4292 if (MD->getNumParams() != ExpectedParams) {
4293 // This also checks for default arguments: a copy or move constructor with a
4294 // default argument is classified as a default constructor, and assignment
4295 // operations and destructors can't have default arguments.
4296 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4297 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004298 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004299 } else if (MD->isVariadic()) {
4300 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4301 << CSM << MD->getSourceRange();
4302 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004303 }
4304
Richard Smith3003e1d2012-05-15 04:39:51 +00004305 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004306
Richard Smith7756afa2012-06-10 05:43:50 +00004307 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004308 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004309 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004310 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004311 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004312
Richard Smith3003e1d2012-05-15 04:39:51 +00004313 QualType ReturnType = Context.VoidTy;
4314 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4315 // Check for return type matching.
4316 ReturnType = Type->getResultType();
4317 QualType ExpectedReturnType =
4318 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4319 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4320 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4321 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4322 HadError = true;
4323 }
4324
4325 // A defaulted special member cannot have cv-qualifiers.
4326 if (Type->getTypeQuals()) {
4327 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4328 << (CSM == CXXMoveAssignment);
4329 HadError = true;
4330 }
4331 }
4332
4333 // Check for parameter type matching.
4334 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004335 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004336 if (ExpectedParams && ArgType->isReferenceType()) {
4337 // Argument must be reference to possibly-const T.
4338 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004339 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004340
4341 if (ReferentType.isVolatileQualified()) {
4342 Diag(MD->getLocation(),
4343 diag::err_defaulted_special_member_volatile_param) << CSM;
4344 HadError = true;
4345 }
4346
Richard Smith7756afa2012-06-10 05:43:50 +00004347 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004348 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4349 Diag(MD->getLocation(),
4350 diag::err_defaulted_special_member_copy_const_param)
4351 << (CSM == CXXCopyAssignment);
4352 // FIXME: Explain why this special member can't be const.
4353 } else {
4354 Diag(MD->getLocation(),
4355 diag::err_defaulted_special_member_move_const_param)
4356 << (CSM == CXXMoveAssignment);
4357 }
4358 HadError = true;
4359 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004360 } else if (ExpectedParams) {
4361 // A copy assignment operator can take its argument by value, but a
4362 // defaulted one cannot.
4363 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004364 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004365 HadError = true;
4366 }
Sean Huntbe631222011-05-17 20:44:43 +00004367
Richard Smith61802452011-12-22 02:22:31 +00004368 // C++11 [dcl.fct.def.default]p2:
4369 // An explicitly-defaulted function may be declared constexpr only if it
4370 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004371 // Do not apply this rule to members of class templates, since core issue 1358
4372 // makes such functions always instantiate to constexpr functions. For
4373 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004374 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4375 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004376 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4377 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4378 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004379 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004380 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004381 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004382
Richard Smith61802452011-12-22 02:22:31 +00004383 // and may have an explicit exception-specification only if it is compatible
4384 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004385 if (Type->hasExceptionSpec()) {
4386 // Delay the check if this is the first declaration of the special member,
4387 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004388 if (First) {
4389 // If the exception specification needs to be instantiated, do so now,
4390 // before we clobber it with an EST_Unevaluated specification below.
4391 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4392 InstantiateExceptionSpec(MD->getLocStart(), MD);
4393 Type = MD->getType()->getAs<FunctionProtoType>();
4394 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004395 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004396 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004397 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4398 }
Richard Smith61802452011-12-22 02:22:31 +00004399
4400 // If a function is explicitly defaulted on its first declaration,
4401 if (First) {
4402 // -- it is implicitly considered to be constexpr if the implicit
4403 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004404 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004405
Richard Smith3003e1d2012-05-15 04:39:51 +00004406 // -- it is implicitly considered to have the same exception-specification
4407 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004408 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4409 EPI.ExceptionSpecType = EST_Unevaluated;
4410 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004411 MD->setType(Context.getFunctionType(ReturnType,
4412 ArrayRef<QualType>(&ArgType,
4413 ExpectedParams),
4414 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004415 }
4416
Richard Smith3003e1d2012-05-15 04:39:51 +00004417 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004418 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004419 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004420 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004421 // C++11 [dcl.fct.def.default]p4:
4422 // [For a] user-provided explicitly-defaulted function [...] if such a
4423 // function is implicitly defined as deleted, the program is ill-formed.
4424 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4425 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004426 }
4427 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004428
Richard Smith3003e1d2012-05-15 04:39:51 +00004429 if (HadError)
4430 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004431}
4432
Richard Smith1d28caf2012-12-11 01:14:52 +00004433/// Check whether the exception specification provided for an
4434/// explicitly-defaulted special member matches the exception specification
4435/// that would have been generated for an implicit special member, per
4436/// C++11 [dcl.fct.def.default]p2.
4437void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4438 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4439 // Compute the implicit exception specification.
4440 FunctionProtoType::ExtProtoInfo EPI;
4441 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4442 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Jordan Rosebea522f2013-03-08 21:51:21 +00004443 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004444
4445 // Ensure that it matches.
4446 CheckEquivalentExceptionSpec(
4447 PDiag(diag::err_incorrect_defaulted_exception_spec)
4448 << getSpecialMember(MD), PDiag(),
4449 ImplicitType, SourceLocation(),
4450 SpecifiedType, MD->getLocation());
4451}
4452
4453void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4454 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4455 I != N; ++I)
4456 CheckExplicitlyDefaultedMemberExceptionSpec(
4457 DelayedDefaultedMemberExceptionSpecs[I].first,
4458 DelayedDefaultedMemberExceptionSpecs[I].second);
4459
4460 DelayedDefaultedMemberExceptionSpecs.clear();
4461}
4462
Richard Smith7d5088a2012-02-18 02:02:13 +00004463namespace {
4464struct SpecialMemberDeletionInfo {
4465 Sema &S;
4466 CXXMethodDecl *MD;
4467 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004468 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004469
4470 // Properties of the special member, computed for convenience.
4471 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4472 SourceLocation Loc;
4473
4474 bool AllFieldsAreConst;
4475
4476 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004477 Sema::CXXSpecialMember CSM, bool Diagnose)
4478 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004479 IsConstructor(false), IsAssignment(false), IsMove(false),
4480 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4481 AllFieldsAreConst(true) {
4482 switch (CSM) {
4483 case Sema::CXXDefaultConstructor:
4484 case Sema::CXXCopyConstructor:
4485 IsConstructor = true;
4486 break;
4487 case Sema::CXXMoveConstructor:
4488 IsConstructor = true;
4489 IsMove = true;
4490 break;
4491 case Sema::CXXCopyAssignment:
4492 IsAssignment = true;
4493 break;
4494 case Sema::CXXMoveAssignment:
4495 IsAssignment = true;
4496 IsMove = true;
4497 break;
4498 case Sema::CXXDestructor:
4499 break;
4500 case Sema::CXXInvalid:
4501 llvm_unreachable("invalid special member kind");
4502 }
4503
4504 if (MD->getNumParams()) {
4505 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4506 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4507 }
4508 }
4509
4510 bool inUnion() const { return MD->getParent()->isUnion(); }
4511
4512 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004513 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4514 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004515 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004516 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4517 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4518 Quals = 0;
4519 return S.LookupSpecialMember(Class, CSM,
4520 ConstArg || (Quals & Qualifiers::Const),
4521 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004522 MD->getRefQualifier() == RQ_RValue,
4523 TQ & Qualifiers::Const,
4524 TQ & Qualifiers::Volatile);
4525 }
4526
Richard Smith6c4c36c2012-03-30 20:53:28 +00004527 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004528
Richard Smith6c4c36c2012-03-30 20:53:28 +00004529 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004530 bool shouldDeleteForField(FieldDecl *FD);
4531 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004532
Richard Smith517bb842012-07-18 03:51:16 +00004533 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4534 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004535 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4536 Sema::SpecialMemberOverloadResult *SMOR,
4537 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004538
4539 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004540};
4541}
4542
John McCall12d8d802012-04-09 20:53:23 +00004543/// Is the given special member inaccessible when used on the given
4544/// sub-object.
4545bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4546 CXXMethodDecl *target) {
4547 /// If we're operating on a base class, the object type is the
4548 /// type of this special member.
4549 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004550 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004551 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4552 objectTy = S.Context.getTypeDeclType(MD->getParent());
4553 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4554
4555 // If we're operating on a field, the object type is the type of the field.
4556 } else {
4557 objectTy = S.Context.getTypeDeclType(target->getParent());
4558 }
4559
4560 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4561}
4562
Richard Smith6c4c36c2012-03-30 20:53:28 +00004563/// Check whether we should delete a special member due to the implicit
4564/// definition containing a call to a special member of a subobject.
4565bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4566 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4567 bool IsDtorCallInCtor) {
4568 CXXMethodDecl *Decl = SMOR->getMethod();
4569 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4570
4571 int DiagKind = -1;
4572
4573 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4574 DiagKind = !Decl ? 0 : 1;
4575 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4576 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004577 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004578 DiagKind = 3;
4579 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4580 !Decl->isTrivial()) {
4581 // A member of a union must have a trivial corresponding special member.
4582 // As a weird special case, a destructor call from a union's constructor
4583 // must be accessible and non-deleted, but need not be trivial. Such a
4584 // destructor is never actually called, but is semantically checked as
4585 // if it were.
4586 DiagKind = 4;
4587 }
4588
4589 if (DiagKind == -1)
4590 return false;
4591
4592 if (Diagnose) {
4593 if (Field) {
4594 S.Diag(Field->getLocation(),
4595 diag::note_deleted_special_member_class_subobject)
4596 << CSM << MD->getParent() << /*IsField*/true
4597 << Field << DiagKind << IsDtorCallInCtor;
4598 } else {
4599 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4600 S.Diag(Base->getLocStart(),
4601 diag::note_deleted_special_member_class_subobject)
4602 << CSM << MD->getParent() << /*IsField*/false
4603 << Base->getType() << DiagKind << IsDtorCallInCtor;
4604 }
4605
4606 if (DiagKind == 1)
4607 S.NoteDeletedFunction(Decl);
4608 // FIXME: Explain inaccessibility if DiagKind == 3.
4609 }
4610
4611 return true;
4612}
4613
Richard Smith9a561d52012-02-26 09:11:52 +00004614/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004615/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004616bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004617 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004618 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004619
4620 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004621 // -- any direct or virtual base class, or non-static data member with no
4622 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004623 // either M has no default constructor or overload resolution as applied
4624 // to M's default constructor results in an ambiguity or in a function
4625 // that is deleted or inaccessible
4626 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4627 // -- a direct or virtual base class B that cannot be copied/moved because
4628 // overload resolution, as applied to B's corresponding special member,
4629 // results in an ambiguity or a function that is deleted or inaccessible
4630 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004631 // C++11 [class.dtor]p5:
4632 // -- any direct or virtual base class [...] has a type with a destructor
4633 // that is deleted or inaccessible
4634 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004635 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004636 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004637 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004638
Richard Smith6c4c36c2012-03-30 20:53:28 +00004639 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4640 // -- any direct or virtual base class or non-static data member has a
4641 // type with a destructor that is deleted or inaccessible
4642 if (IsConstructor) {
4643 Sema::SpecialMemberOverloadResult *SMOR =
4644 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4645 false, false, false, false, false);
4646 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4647 return true;
4648 }
4649
Richard Smith9a561d52012-02-26 09:11:52 +00004650 return false;
4651}
4652
4653/// Check whether we should delete a special member function due to the class
4654/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004655bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004656 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004657 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004658}
4659
4660/// Check whether we should delete a special member function due to the class
4661/// having a particular non-static data member.
4662bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4663 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4664 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4665
4666 if (CSM == Sema::CXXDefaultConstructor) {
4667 // For a default constructor, all references must be initialized in-class
4668 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004669 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4670 if (Diagnose)
4671 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4672 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004673 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004674 }
Richard Smith79363f52012-02-27 06:07:25 +00004675 // C++11 [class.ctor]p5: any non-variant non-static data member of
4676 // const-qualified type (or array thereof) with no
4677 // brace-or-equal-initializer does not have a user-provided default
4678 // constructor.
4679 if (!inUnion() && FieldType.isConstQualified() &&
4680 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004681 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4682 if (Diagnose)
4683 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004684 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004685 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004686 }
4687
4688 if (inUnion() && !FieldType.isConstQualified())
4689 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004690 } else if (CSM == Sema::CXXCopyConstructor) {
4691 // For a copy constructor, data members must not be of rvalue reference
4692 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004693 if (FieldType->isRValueReferenceType()) {
4694 if (Diagnose)
4695 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4696 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004697 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004698 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004699 } else if (IsAssignment) {
4700 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004701 if (FieldType->isReferenceType()) {
4702 if (Diagnose)
4703 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4704 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004705 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004706 }
4707 if (!FieldRecord && FieldType.isConstQualified()) {
4708 // C++11 [class.copy]p23:
4709 // -- a non-static data member of const non-class type (or array thereof)
4710 if (Diagnose)
4711 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004712 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004713 return true;
4714 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004715 }
4716
4717 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004718 // Some additional restrictions exist on the variant members.
4719 if (!inUnion() && FieldRecord->isUnion() &&
4720 FieldRecord->isAnonymousStructOrUnion()) {
4721 bool AllVariantFieldsAreConst = true;
4722
Richard Smithdf8dc862012-03-29 19:00:10 +00004723 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004724 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4725 UE = FieldRecord->field_end();
4726 UI != UE; ++UI) {
4727 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004728
4729 if (!UnionFieldType.isConstQualified())
4730 AllVariantFieldsAreConst = false;
4731
Richard Smith9a561d52012-02-26 09:11:52 +00004732 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4733 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004734 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4735 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004736 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004737 }
4738
4739 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004740 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004741 FieldRecord->field_begin() != FieldRecord->field_end()) {
4742 if (Diagnose)
4743 S.Diag(FieldRecord->getLocation(),
4744 diag::note_deleted_default_ctor_all_const)
4745 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004746 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004747 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004748
Richard Smithdf8dc862012-03-29 19:00:10 +00004749 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004750 // This is technically non-conformant, but sanity demands it.
4751 return false;
4752 }
4753
Richard Smith517bb842012-07-18 03:51:16 +00004754 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4755 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004756 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004757 }
4758
4759 return false;
4760}
4761
4762/// C++11 [class.ctor] p5:
4763/// A defaulted default constructor for a class X is defined as deleted if
4764/// X is a union and all of its variant members are of const-qualified type.
4765bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004766 // This is a silly definition, because it gives an empty union a deleted
4767 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004768 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4769 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4770 if (Diagnose)
4771 S.Diag(MD->getParent()->getLocation(),
4772 diag::note_deleted_default_ctor_all_const)
4773 << MD->getParent() << /*not anonymous union*/0;
4774 return true;
4775 }
4776 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004777}
4778
4779/// Determine whether a defaulted special member function should be defined as
4780/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4781/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004782bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4783 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004784 if (MD->isInvalidDecl())
4785 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004786 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004787 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004788 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004789 return false;
4790
Richard Smith7d5088a2012-02-18 02:02:13 +00004791 // C++11 [expr.lambda.prim]p19:
4792 // The closure type associated with a lambda-expression has a
4793 // deleted (8.4.3) default constructor and a deleted copy
4794 // assignment operator.
4795 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004796 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4797 if (Diagnose)
4798 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004799 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004800 }
4801
Richard Smith5bdaac52012-04-02 20:59:25 +00004802 // For an anonymous struct or union, the copy and assignment special members
4803 // will never be used, so skip the check. For an anonymous union declared at
4804 // namespace scope, the constructor and destructor are used.
4805 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4806 RD->isAnonymousStructOrUnion())
4807 return false;
4808
Richard Smith6c4c36c2012-03-30 20:53:28 +00004809 // C++11 [class.copy]p7, p18:
4810 // If the class definition declares a move constructor or move assignment
4811 // operator, an implicitly declared copy constructor or copy assignment
4812 // operator is defined as deleted.
4813 if (MD->isImplicit() &&
4814 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4815 CXXMethodDecl *UserDeclaredMove = 0;
4816
4817 // In Microsoft mode, a user-declared move only causes the deletion of the
4818 // corresponding copy operation, not both copy operations.
4819 if (RD->hasUserDeclaredMoveConstructor() &&
4820 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4821 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004822
4823 // Find any user-declared move constructor.
4824 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4825 E = RD->ctor_end(); I != E; ++I) {
4826 if (I->isMoveConstructor()) {
4827 UserDeclaredMove = *I;
4828 break;
4829 }
4830 }
Richard Smith1c931be2012-04-02 18:40:40 +00004831 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004832 } else if (RD->hasUserDeclaredMoveAssignment() &&
4833 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4834 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004835
4836 // Find any user-declared move assignment operator.
4837 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4838 E = RD->method_end(); I != E; ++I) {
4839 if (I->isMoveAssignmentOperator()) {
4840 UserDeclaredMove = *I;
4841 break;
4842 }
4843 }
Richard Smith1c931be2012-04-02 18:40:40 +00004844 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004845 }
4846
4847 if (UserDeclaredMove) {
4848 Diag(UserDeclaredMove->getLocation(),
4849 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004850 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004851 << UserDeclaredMove->isMoveAssignmentOperator();
4852 return true;
4853 }
4854 }
Sean Hunte16da072011-10-10 06:18:57 +00004855
Richard Smith5bdaac52012-04-02 20:59:25 +00004856 // Do access control from the special member function
4857 ContextRAII MethodContext(*this, MD);
4858
Richard Smith9a561d52012-02-26 09:11:52 +00004859 // C++11 [class.dtor]p5:
4860 // -- for a virtual destructor, lookup of the non-array deallocation function
4861 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004862 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004863 FunctionDecl *OperatorDelete = 0;
4864 DeclarationName Name =
4865 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4866 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004867 OperatorDelete, false)) {
4868 if (Diagnose)
4869 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004870 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004871 }
Richard Smith9a561d52012-02-26 09:11:52 +00004872 }
4873
Richard Smith6c4c36c2012-03-30 20:53:28 +00004874 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004875
Sean Huntcdee3fe2011-05-11 22:34:38 +00004876 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004877 BE = RD->bases_end(); BI != BE; ++BI)
4878 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004879 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004880 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004881
4882 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004883 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004884 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004885 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004886
4887 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004888 FE = RD->field_end(); FI != FE; ++FI)
4889 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004890 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004891 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004892
Richard Smith7d5088a2012-02-18 02:02:13 +00004893 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004894 return true;
4895
4896 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004897}
4898
Richard Smithac713512012-12-08 02:53:02 +00004899/// Perform lookup for a special member of the specified kind, and determine
4900/// whether it is trivial. If the triviality can be determined without the
4901/// lookup, skip it. This is intended for use when determining whether a
4902/// special member of a containing object is trivial, and thus does not ever
4903/// perform overload resolution for default constructors.
4904///
4905/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4906/// member that was most likely to be intended to be trivial, if any.
4907static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4908 Sema::CXXSpecialMember CSM, unsigned Quals,
4909 CXXMethodDecl **Selected) {
4910 if (Selected)
4911 *Selected = 0;
4912
4913 switch (CSM) {
4914 case Sema::CXXInvalid:
4915 llvm_unreachable("not a special member");
4916
4917 case Sema::CXXDefaultConstructor:
4918 // C++11 [class.ctor]p5:
4919 // A default constructor is trivial if:
4920 // - all the [direct subobjects] have trivial default constructors
4921 //
4922 // Note, no overload resolution is performed in this case.
4923 if (RD->hasTrivialDefaultConstructor())
4924 return true;
4925
4926 if (Selected) {
4927 // If there's a default constructor which could have been trivial, dig it
4928 // out. Otherwise, if there's any user-provided default constructor, point
4929 // to that as an example of why there's not a trivial one.
4930 CXXConstructorDecl *DefCtor = 0;
4931 if (RD->needsImplicitDefaultConstructor())
4932 S.DeclareImplicitDefaultConstructor(RD);
4933 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4934 CE = RD->ctor_end(); CI != CE; ++CI) {
4935 if (!CI->isDefaultConstructor())
4936 continue;
4937 DefCtor = *CI;
4938 if (!DefCtor->isUserProvided())
4939 break;
4940 }
4941
4942 *Selected = DefCtor;
4943 }
4944
4945 return false;
4946
4947 case Sema::CXXDestructor:
4948 // C++11 [class.dtor]p5:
4949 // A destructor is trivial if:
4950 // - all the direct [subobjects] have trivial destructors
4951 if (RD->hasTrivialDestructor())
4952 return true;
4953
4954 if (Selected) {
4955 if (RD->needsImplicitDestructor())
4956 S.DeclareImplicitDestructor(RD);
4957 *Selected = RD->getDestructor();
4958 }
4959
4960 return false;
4961
4962 case Sema::CXXCopyConstructor:
4963 // C++11 [class.copy]p12:
4964 // A copy constructor is trivial if:
4965 // - the constructor selected to copy each direct [subobject] is trivial
4966 if (RD->hasTrivialCopyConstructor()) {
4967 if (Quals == Qualifiers::Const)
4968 // We must either select the trivial copy constructor or reach an
4969 // ambiguity; no need to actually perform overload resolution.
4970 return true;
4971 } else if (!Selected) {
4972 return false;
4973 }
4974 // In C++98, we are not supposed to perform overload resolution here, but we
4975 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4976 // cases like B as having a non-trivial copy constructor:
4977 // struct A { template<typename T> A(T&); };
4978 // struct B { mutable A a; };
4979 goto NeedOverloadResolution;
4980
4981 case Sema::CXXCopyAssignment:
4982 // C++11 [class.copy]p25:
4983 // A copy assignment operator is trivial if:
4984 // - the assignment operator selected to copy each direct [subobject] is
4985 // trivial
4986 if (RD->hasTrivialCopyAssignment()) {
4987 if (Quals == Qualifiers::Const)
4988 return true;
4989 } else if (!Selected) {
4990 return false;
4991 }
4992 // In C++98, we are not supposed to perform overload resolution here, but we
4993 // treat that as a language defect.
4994 goto NeedOverloadResolution;
4995
4996 case Sema::CXXMoveConstructor:
4997 case Sema::CXXMoveAssignment:
4998 NeedOverloadResolution:
4999 Sema::SpecialMemberOverloadResult *SMOR =
5000 S.LookupSpecialMember(RD, CSM,
5001 Quals & Qualifiers::Const,
5002 Quals & Qualifiers::Volatile,
5003 /*RValueThis*/false, /*ConstThis*/false,
5004 /*VolatileThis*/false);
5005
5006 // The standard doesn't describe how to behave if the lookup is ambiguous.
5007 // We treat it as not making the member non-trivial, just like the standard
5008 // mandates for the default constructor. This should rarely matter, because
5009 // the member will also be deleted.
5010 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5011 return true;
5012
5013 if (!SMOR->getMethod()) {
5014 assert(SMOR->getKind() ==
5015 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5016 return false;
5017 }
5018
5019 // We deliberately don't check if we found a deleted special member. We're
5020 // not supposed to!
5021 if (Selected)
5022 *Selected = SMOR->getMethod();
5023 return SMOR->getMethod()->isTrivial();
5024 }
5025
5026 llvm_unreachable("unknown special method kind");
5027}
5028
Benjamin Kramera574c892013-02-15 12:30:38 +00005029static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005030 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5031 CI != CE; ++CI)
5032 if (!CI->isImplicit())
5033 return *CI;
5034
5035 // Look for constructor templates.
5036 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5037 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5038 if (CXXConstructorDecl *CD =
5039 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5040 return CD;
5041 }
5042
5043 return 0;
5044}
5045
5046/// The kind of subobject we are checking for triviality. The values of this
5047/// enumeration are used in diagnostics.
5048enum TrivialSubobjectKind {
5049 /// The subobject is a base class.
5050 TSK_BaseClass,
5051 /// The subobject is a non-static data member.
5052 TSK_Field,
5053 /// The object is actually the complete object.
5054 TSK_CompleteObject
5055};
5056
5057/// Check whether the special member selected for a given type would be trivial.
5058static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5059 QualType SubType,
5060 Sema::CXXSpecialMember CSM,
5061 TrivialSubobjectKind Kind,
5062 bool Diagnose) {
5063 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5064 if (!SubRD)
5065 return true;
5066
5067 CXXMethodDecl *Selected;
5068 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5069 Diagnose ? &Selected : 0))
5070 return true;
5071
5072 if (Diagnose) {
5073 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5074 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5075 << Kind << SubType.getUnqualifiedType();
5076 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5077 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5078 } else if (!Selected)
5079 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5080 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5081 else if (Selected->isUserProvided()) {
5082 if (Kind == TSK_CompleteObject)
5083 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5084 << Kind << SubType.getUnqualifiedType() << CSM;
5085 else {
5086 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5087 << Kind << SubType.getUnqualifiedType() << CSM;
5088 S.Diag(Selected->getLocation(), diag::note_declared_at);
5089 }
5090 } else {
5091 if (Kind != TSK_CompleteObject)
5092 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5093 << Kind << SubType.getUnqualifiedType() << CSM;
5094
5095 // Explain why the defaulted or deleted special member isn't trivial.
5096 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5097 }
5098 }
5099
5100 return false;
5101}
5102
5103/// Check whether the members of a class type allow a special member to be
5104/// trivial.
5105static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5106 Sema::CXXSpecialMember CSM,
5107 bool ConstArg, bool Diagnose) {
5108 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5109 FE = RD->field_end(); FI != FE; ++FI) {
5110 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5111 continue;
5112
5113 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5114
5115 // Pretend anonymous struct or union members are members of this class.
5116 if (FI->isAnonymousStructOrUnion()) {
5117 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5118 CSM, ConstArg, Diagnose))
5119 return false;
5120 continue;
5121 }
5122
5123 // C++11 [class.ctor]p5:
5124 // A default constructor is trivial if [...]
5125 // -- no non-static data member of its class has a
5126 // brace-or-equal-initializer
5127 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5128 if (Diagnose)
5129 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5130 return false;
5131 }
5132
5133 // Objective C ARC 4.3.5:
5134 // [...] nontrivally ownership-qualified types are [...] not trivially
5135 // default constructible, copy constructible, move constructible, copy
5136 // assignable, move assignable, or destructible [...]
5137 if (S.getLangOpts().ObjCAutoRefCount &&
5138 FieldType.hasNonTrivialObjCLifetime()) {
5139 if (Diagnose)
5140 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5141 << RD << FieldType.getObjCLifetime();
5142 return false;
5143 }
5144
5145 if (ConstArg && !FI->isMutable())
5146 FieldType.addConst();
5147 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5148 TSK_Field, Diagnose))
5149 return false;
5150 }
5151
5152 return true;
5153}
5154
5155/// Diagnose why the specified class does not have a trivial special member of
5156/// the given kind.
5157void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5158 QualType Ty = Context.getRecordType(RD);
5159 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5160 Ty.addConst();
5161
5162 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5163 TSK_CompleteObject, /*Diagnose*/true);
5164}
5165
5166/// Determine whether a defaulted or deleted special member function is trivial,
5167/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5168/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5169bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5170 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005171 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5172
5173 CXXRecordDecl *RD = MD->getParent();
5174
5175 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005176
5177 // C++11 [class.copy]p12, p25:
5178 // A [special member] is trivial if its declared parameter type is the same
5179 // as if it had been implicitly declared [...]
5180 switch (CSM) {
5181 case CXXDefaultConstructor:
5182 case CXXDestructor:
5183 // Trivial default constructors and destructors cannot have parameters.
5184 break;
5185
5186 case CXXCopyConstructor:
5187 case CXXCopyAssignment: {
5188 // Trivial copy operations always have const, non-volatile parameter types.
5189 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005190 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005191 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5192 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5193 if (Diagnose)
5194 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5195 << Param0->getSourceRange() << Param0->getType()
5196 << Context.getLValueReferenceType(
5197 Context.getRecordType(RD).withConst());
5198 return false;
5199 }
5200 break;
5201 }
5202
5203 case CXXMoveConstructor:
5204 case CXXMoveAssignment: {
5205 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005206 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005207 const RValueReferenceType *RT =
5208 Param0->getType()->getAs<RValueReferenceType>();
5209 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5210 if (Diagnose)
5211 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5212 << Param0->getSourceRange() << Param0->getType()
5213 << Context.getRValueReferenceType(Context.getRecordType(RD));
5214 return false;
5215 }
5216 break;
5217 }
5218
5219 case CXXInvalid:
5220 llvm_unreachable("not a special member");
5221 }
5222
5223 // FIXME: We require that the parameter-declaration-clause is equivalent to
5224 // that of an implicit declaration, not just that the declared parameter type
5225 // matches, in order to prevent absuridities like a function simultaneously
5226 // being a trivial copy constructor and a non-trivial default constructor.
5227 // This issue has not yet been assigned a core issue number.
5228 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5229 if (Diagnose)
5230 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5231 diag::note_nontrivial_default_arg)
5232 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5233 return false;
5234 }
5235 if (MD->isVariadic()) {
5236 if (Diagnose)
5237 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5238 return false;
5239 }
5240
5241 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5242 // A copy/move [constructor or assignment operator] is trivial if
5243 // -- the [member] selected to copy/move each direct base class subobject
5244 // is trivial
5245 //
5246 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5247 // A [default constructor or destructor] is trivial if
5248 // -- all the direct base classes have trivial [default constructors or
5249 // destructors]
5250 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5251 BE = RD->bases_end(); BI != BE; ++BI)
5252 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5253 ConstArg ? BI->getType().withConst()
5254 : BI->getType(),
5255 CSM, TSK_BaseClass, Diagnose))
5256 return false;
5257
5258 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5259 // A copy/move [constructor or assignment operator] for a class X is
5260 // trivial if
5261 // -- for each non-static data member of X that is of class type (or array
5262 // thereof), the constructor selected to copy/move that member is
5263 // trivial
5264 //
5265 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5266 // A [default constructor or destructor] is trivial if
5267 // -- for all of the non-static data members of its class that are of class
5268 // type (or array thereof), each such class has a trivial [default
5269 // constructor or destructor]
5270 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5271 return false;
5272
5273 // C++11 [class.dtor]p5:
5274 // A destructor is trivial if [...]
5275 // -- the destructor is not virtual
5276 if (CSM == CXXDestructor && MD->isVirtual()) {
5277 if (Diagnose)
5278 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5279 return false;
5280 }
5281
5282 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5283 // A [special member] for class X is trivial if [...]
5284 // -- class X has no virtual functions and no virtual base classes
5285 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5286 if (!Diagnose)
5287 return false;
5288
5289 if (RD->getNumVBases()) {
5290 // Check for virtual bases. We already know that the corresponding
5291 // member in all bases is trivial, so vbases must all be direct.
5292 CXXBaseSpecifier &BS = *RD->vbases_begin();
5293 assert(BS.isVirtual());
5294 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5295 return false;
5296 }
5297
5298 // Must have a virtual method.
5299 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5300 ME = RD->method_end(); MI != ME; ++MI) {
5301 if (MI->isVirtual()) {
5302 SourceLocation MLoc = MI->getLocStart();
5303 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5304 return false;
5305 }
5306 }
5307
5308 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5309 }
5310
5311 // Looks like it's trivial!
5312 return true;
5313}
5314
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005315/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005316namespace {
5317 struct FindHiddenVirtualMethodData {
5318 Sema *S;
5319 CXXMethodDecl *Method;
5320 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005321 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005322 };
5323}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005324
David Blaikie5f750682012-10-19 00:53:08 +00005325/// \brief Check whether any most overriden method from MD in Methods
5326static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5327 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5328 if (MD->size_overridden_methods() == 0)
5329 return Methods.count(MD->getCanonicalDecl());
5330 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5331 E = MD->end_overridden_methods();
5332 I != E; ++I)
5333 if (CheckMostOverridenMethods(*I, Methods))
5334 return true;
5335 return false;
5336}
5337
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005338/// \brief Member lookup function that determines whether a given C++
5339/// method overloads virtual methods in a base class without overriding any,
5340/// to be used with CXXRecordDecl::lookupInBases().
5341static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5342 CXXBasePath &Path,
5343 void *UserData) {
5344 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5345
5346 FindHiddenVirtualMethodData &Data
5347 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5348
5349 DeclarationName Name = Data.Method->getDeclName();
5350 assert(Name.getNameKind() == DeclarationName::Identifier);
5351
5352 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005353 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005354 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005355 !Path.Decls.empty();
5356 Path.Decls = Path.Decls.slice(1)) {
5357 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005358 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005359 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005360 foundSameNameMethod = true;
5361 // Interested only in hidden virtual methods.
5362 if (!MD->isVirtual())
5363 continue;
5364 // If the method we are checking overrides a method from its base
5365 // don't warn about the other overloaded methods.
5366 if (!Data.S->IsOverload(Data.Method, MD, false))
5367 return true;
5368 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005369 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005370 overloadedMethods.push_back(MD);
5371 }
5372 }
5373
5374 if (foundSameNameMethod)
5375 Data.OverloadedMethods.append(overloadedMethods.begin(),
5376 overloadedMethods.end());
5377 return foundSameNameMethod;
5378}
5379
David Blaikie5f750682012-10-19 00:53:08 +00005380/// \brief Add the most overriden methods from MD to Methods
5381static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5382 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5383 if (MD->size_overridden_methods() == 0)
5384 Methods.insert(MD->getCanonicalDecl());
5385 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5386 E = MD->end_overridden_methods();
5387 I != E; ++I)
5388 AddMostOverridenMethods(*I, Methods);
5389}
5390
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005391/// \brief See if a method overloads virtual methods in a base class without
5392/// overriding any.
5393void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5394 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005395 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005396 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005397 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005398 return;
5399
5400 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5401 /*bool RecordPaths=*/false,
5402 /*bool DetectVirtual=*/false);
5403 FindHiddenVirtualMethodData Data;
5404 Data.Method = MD;
5405 Data.S = this;
5406
5407 // Keep the base methods that were overriden or introduced in the subclass
5408 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005409 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5410 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5411 NamedDecl *ND = *I;
5412 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005413 ND = shad->getTargetDecl();
5414 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5415 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005416 }
5417
5418 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5419 !Data.OverloadedMethods.empty()) {
5420 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5421 << MD << (Data.OverloadedMethods.size() > 1);
5422
5423 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5424 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005425 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005426 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005427 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5428 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005429 }
5430 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005431}
5432
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005433void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005434 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005435 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005436 SourceLocation RBrac,
5437 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005438 if (!TagDecl)
5439 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005440
Douglas Gregor42af25f2009-05-11 19:58:34 +00005441 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005442
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005443 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5444 if (l->getKind() != AttributeList::AT_Visibility)
5445 continue;
5446 l->setInvalid();
5447 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5448 l->getName();
5449 }
5450
David Blaikie77b6de02011-09-22 02:58:26 +00005451 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005452 // strict aliasing violation!
5453 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005454 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005455
Douglas Gregor23c94db2010-07-02 17:43:08 +00005456 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005457 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005458}
5459
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005460/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5461/// special functions, such as the default constructor, copy
5462/// constructor, or destructor, to the given C++ class (C++
5463/// [special]p1). This routine can only be executed just before the
5464/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005465void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005466 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005467 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005468
Richard Smithbc2a35d2012-12-08 08:32:28 +00005469 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005470 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005471
Richard Smithbc2a35d2012-12-08 08:32:28 +00005472 // If the properties or semantics of the copy constructor couldn't be
5473 // determined while the class was being declared, force a declaration
5474 // of it now.
5475 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5476 DeclareImplicitCopyConstructor(ClassDecl);
5477 }
5478
Richard Smith80ad52f2013-01-02 11:42:31 +00005479 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005480 ++ASTContext::NumImplicitMoveConstructors;
5481
Richard Smithbc2a35d2012-12-08 08:32:28 +00005482 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5483 DeclareImplicitMoveConstructor(ClassDecl);
5484 }
5485
Douglas Gregora376d102010-07-02 21:50:04 +00005486 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5487 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005488
5489 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005490 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005491 // it shows up in the right place in the vtable and that we diagnose
5492 // problems with the implicit exception specification.
5493 if (ClassDecl->isDynamicClass() ||
5494 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005495 DeclareImplicitCopyAssignment(ClassDecl);
5496 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005497
Richard Smith80ad52f2013-01-02 11:42:31 +00005498 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005499 ++ASTContext::NumImplicitMoveAssignmentOperators;
5500
5501 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005502 if (ClassDecl->isDynamicClass() ||
5503 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005504 DeclareImplicitMoveAssignment(ClassDecl);
5505 }
5506
Douglas Gregor4923aa22010-07-02 20:37:36 +00005507 if (!ClassDecl->hasUserDeclaredDestructor()) {
5508 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005509
5510 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005511 // have to declare the destructor immediately. This ensures that, e.g., it
5512 // shows up in the right place in the vtable and that we diagnose problems
5513 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005514 if (ClassDecl->isDynamicClass() ||
5515 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005516 DeclareImplicitDestructor(ClassDecl);
5517 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005518}
5519
Francois Pichet8387e2a2011-04-22 22:18:13 +00005520void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5521 if (!D)
5522 return;
5523
5524 int NumParamList = D->getNumTemplateParameterLists();
5525 for (int i = 0; i < NumParamList; i++) {
5526 TemplateParameterList* Params = D->getTemplateParameterList(i);
5527 for (TemplateParameterList::iterator Param = Params->begin(),
5528 ParamEnd = Params->end();
5529 Param != ParamEnd; ++Param) {
5530 NamedDecl *Named = cast<NamedDecl>(*Param);
5531 if (Named->getDeclName()) {
5532 S->AddDecl(Named);
5533 IdResolver.AddDecl(Named);
5534 }
5535 }
5536 }
5537}
5538
John McCalld226f652010-08-21 09:40:31 +00005539void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005540 if (!D)
5541 return;
5542
5543 TemplateParameterList *Params = 0;
5544 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5545 Params = Template->getTemplateParameters();
5546 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5547 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5548 Params = PartialSpec->getTemplateParameters();
5549 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005550 return;
5551
Douglas Gregor6569d682009-05-27 23:11:45 +00005552 for (TemplateParameterList::iterator Param = Params->begin(),
5553 ParamEnd = Params->end();
5554 Param != ParamEnd; ++Param) {
5555 NamedDecl *Named = cast<NamedDecl>(*Param);
5556 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005557 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005558 IdResolver.AddDecl(Named);
5559 }
5560 }
5561}
5562
John McCalld226f652010-08-21 09:40:31 +00005563void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005564 if (!RecordD) return;
5565 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005566 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005567 PushDeclContext(S, Record);
5568}
5569
John McCalld226f652010-08-21 09:40:31 +00005570void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005571 if (!RecordD) return;
5572 PopDeclContext();
5573}
5574
Douglas Gregor72b505b2008-12-16 21:30:33 +00005575/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5576/// parsing a top-level (non-nested) C++ class, and we are now
5577/// parsing those parts of the given Method declaration that could
5578/// not be parsed earlier (C++ [class.mem]p2), such as default
5579/// arguments. This action should enter the scope of the given
5580/// Method declaration as if we had just parsed the qualified method
5581/// name. However, it should not bring the parameters into scope;
5582/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005583void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005584}
5585
5586/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5587/// C++ method declaration. We're (re-)introducing the given
5588/// function parameter into scope for use in parsing later parts of
5589/// the method declaration. For example, we could see an
5590/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005591void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005592 if (!ParamD)
5593 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005594
John McCalld226f652010-08-21 09:40:31 +00005595 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005596
5597 // If this parameter has an unparsed default argument, clear it out
5598 // to make way for the parsed default argument.
5599 if (Param->hasUnparsedDefaultArg())
5600 Param->setDefaultArg(0);
5601
John McCalld226f652010-08-21 09:40:31 +00005602 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005603 if (Param->getDeclName())
5604 IdResolver.AddDecl(Param);
5605}
5606
5607/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5608/// processing the delayed method declaration for Method. The method
5609/// declaration is now considered finished. There may be a separate
5610/// ActOnStartOfFunctionDef action later (not necessarily
5611/// immediately!) for this method, if it was also defined inside the
5612/// class body.
John McCalld226f652010-08-21 09:40:31 +00005613void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005614 if (!MethodD)
5615 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005616
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005617 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005618
John McCalld226f652010-08-21 09:40:31 +00005619 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005620
5621 // Now that we have our default arguments, check the constructor
5622 // again. It could produce additional diagnostics or affect whether
5623 // the class has implicitly-declared destructors, among other
5624 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005625 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5626 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005627
5628 // Check the default arguments, which we may have added.
5629 if (!Method->isInvalidDecl())
5630 CheckCXXDefaultArguments(Method);
5631}
5632
Douglas Gregor42a552f2008-11-05 20:51:48 +00005633/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005634/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005635/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005636/// emit diagnostics and set the invalid bit to true. In any case, the type
5637/// will be updated to reflect a well-formed type for the constructor and
5638/// returned.
5639QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005640 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005641 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005642
5643 // C++ [class.ctor]p3:
5644 // A constructor shall not be virtual (10.3) or static (9.4). A
5645 // constructor can be invoked for a const, volatile or const
5646 // volatile object. A constructor shall not be declared const,
5647 // volatile, or const volatile (9.3.2).
5648 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005649 if (!D.isInvalidType())
5650 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5651 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5652 << SourceRange(D.getIdentifierLoc());
5653 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005654 }
John McCalld931b082010-08-26 03:08:43 +00005655 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005656 if (!D.isInvalidType())
5657 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5658 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5659 << SourceRange(D.getIdentifierLoc());
5660 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005661 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005662 }
Mike Stump1eb44332009-09-09 15:08:12 +00005663
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005664 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005665 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005666 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005667 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5668 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005669 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005670 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5671 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005672 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005673 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5674 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005675 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005676 }
Mike Stump1eb44332009-09-09 15:08:12 +00005677
Douglas Gregorc938c162011-01-26 05:01:58 +00005678 // C++0x [class.ctor]p4:
5679 // A constructor shall not be declared with a ref-qualifier.
5680 if (FTI.hasRefQualifier()) {
5681 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5682 << FTI.RefQualifierIsLValueRef
5683 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5684 D.setInvalidType();
5685 }
5686
Douglas Gregor42a552f2008-11-05 20:51:48 +00005687 // Rebuild the function type "R" without any type qualifiers (in
5688 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005689 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005690 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005691 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5692 return R;
5693
5694 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5695 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005696 EPI.RefQualifier = RQ_None;
5697
Richard Smith07b0fdc2013-03-18 21:12:30 +00005698 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005699}
5700
Douglas Gregor72b505b2008-12-16 21:30:33 +00005701/// CheckConstructor - Checks a fully-formed constructor for
5702/// well-formedness, issuing any diagnostics required. Returns true if
5703/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005704void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005705 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005706 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5707 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005708 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005709
5710 // C++ [class.copy]p3:
5711 // A declaration of a constructor for a class X is ill-formed if
5712 // its first parameter is of type (optionally cv-qualified) X and
5713 // either there are no other parameters or else all other
5714 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005715 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005716 ((Constructor->getNumParams() == 1) ||
5717 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005718 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5719 Constructor->getTemplateSpecializationKind()
5720 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005721 QualType ParamType = Constructor->getParamDecl(0)->getType();
5722 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5723 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005724 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005725 const char *ConstRef
5726 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5727 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005728 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005729 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005730
5731 // FIXME: Rather that making the constructor invalid, we should endeavor
5732 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005733 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005734 }
5735 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005736}
5737
John McCall15442822010-08-04 01:04:25 +00005738/// CheckDestructor - Checks a fully-formed destructor definition for
5739/// well-formedness, issuing any diagnostics required. Returns true
5740/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005741bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005742 CXXRecordDecl *RD = Destructor->getParent();
5743
5744 if (Destructor->isVirtual()) {
5745 SourceLocation Loc;
5746
5747 if (!Destructor->isImplicit())
5748 Loc = Destructor->getLocation();
5749 else
5750 Loc = RD->getLocation();
5751
5752 // If we have a virtual destructor, look up the deallocation function
5753 FunctionDecl *OperatorDelete = 0;
5754 DeclarationName Name =
5755 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005756 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005757 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005758
Eli Friedman5f2987c2012-02-02 03:46:19 +00005759 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005760
5761 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005762 }
Anders Carlsson37909802009-11-30 21:24:50 +00005763
5764 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005765}
5766
Mike Stump1eb44332009-09-09 15:08:12 +00005767static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005768FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5769 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5770 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005771 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005772}
5773
Douglas Gregor42a552f2008-11-05 20:51:48 +00005774/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5775/// the well-formednes of the destructor declarator @p D with type @p
5776/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005777/// emit diagnostics and set the declarator to invalid. Even if this happens,
5778/// will be updated to reflect a well-formed type for the destructor and
5779/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005780QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005781 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005782 // C++ [class.dtor]p1:
5783 // [...] A typedef-name that names a class is a class-name
5784 // (7.1.3); however, a typedef-name that names a class shall not
5785 // be used as the identifier in the declarator for a destructor
5786 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005787 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005788 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005789 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005790 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005791 else if (const TemplateSpecializationType *TST =
5792 DeclaratorType->getAs<TemplateSpecializationType>())
5793 if (TST->isTypeAlias())
5794 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5795 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005796
5797 // C++ [class.dtor]p2:
5798 // A destructor is used to destroy objects of its class type. A
5799 // destructor takes no parameters, and no return type can be
5800 // specified for it (not even void). The address of a destructor
5801 // shall not be taken. A destructor shall not be static. A
5802 // destructor can be invoked for a const, volatile or const
5803 // volatile object. A destructor shall not be declared const,
5804 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005805 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005806 if (!D.isInvalidType())
5807 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5808 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005809 << SourceRange(D.getIdentifierLoc())
5810 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5811
John McCalld931b082010-08-26 03:08:43 +00005812 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005813 }
Chris Lattner65401802009-04-25 08:28:21 +00005814 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005815 // Destructors don't have return types, but the parser will
5816 // happily parse something like:
5817 //
5818 // class X {
5819 // float ~X();
5820 // };
5821 //
5822 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005823 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5824 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5825 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005826 }
Mike Stump1eb44332009-09-09 15:08:12 +00005827
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005828 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005829 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005830 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005831 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5832 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005833 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005834 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5835 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005836 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005837 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5838 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005839 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005840 }
5841
Douglas Gregorc938c162011-01-26 05:01:58 +00005842 // C++0x [class.dtor]p2:
5843 // A destructor shall not be declared with a ref-qualifier.
5844 if (FTI.hasRefQualifier()) {
5845 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5846 << FTI.RefQualifierIsLValueRef
5847 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5848 D.setInvalidType();
5849 }
5850
Douglas Gregor42a552f2008-11-05 20:51:48 +00005851 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005852 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005853 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5854
5855 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005856 FTI.freeArgs();
5857 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005858 }
5859
Mike Stump1eb44332009-09-09 15:08:12 +00005860 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005861 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005862 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005863 D.setInvalidType();
5864 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005865
5866 // Rebuild the function type "R" without any type qualifiers or
5867 // parameters (in case any of the errors above fired) and with
5868 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005869 // types.
John McCalle23cf432010-12-14 08:05:40 +00005870 if (!D.isInvalidType())
5871 return R;
5872
Douglas Gregord92ec472010-07-01 05:10:53 +00005873 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005874 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5875 EPI.Variadic = false;
5876 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005877 EPI.RefQualifier = RQ_None;
Jordan Rosebea522f2013-03-08 21:51:21 +00005878 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005879}
5880
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005881/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5882/// well-formednes of the conversion function declarator @p D with
5883/// type @p R. If there are any errors in the declarator, this routine
5884/// will emit diagnostics and return true. Otherwise, it will return
5885/// false. Either way, the type @p R will be updated to reflect a
5886/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005887void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005888 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005889 // C++ [class.conv.fct]p1:
5890 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005891 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005892 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005893 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005894 if (!D.isInvalidType())
5895 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5896 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5897 << SourceRange(D.getIdentifierLoc());
5898 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005899 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005900 }
John McCalla3f81372010-04-13 00:04:31 +00005901
5902 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5903
Chris Lattner6e475012009-04-25 08:35:12 +00005904 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005905 // Conversion functions don't have return types, but the parser will
5906 // happily parse something like:
5907 //
5908 // class X {
5909 // float operator bool();
5910 // };
5911 //
5912 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005913 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5914 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5915 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005916 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005917 }
5918
John McCalla3f81372010-04-13 00:04:31 +00005919 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5920
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005921 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005922 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005923 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5924
5925 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005926 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005927 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005928 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005929 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005930 D.setInvalidType();
5931 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005932
John McCalla3f81372010-04-13 00:04:31 +00005933 // Diagnose "&operator bool()" and other such nonsense. This
5934 // is actually a gcc extension which we don't support.
5935 if (Proto->getResultType() != ConvType) {
5936 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5937 << Proto->getResultType();
5938 D.setInvalidType();
5939 ConvType = Proto->getResultType();
5940 }
5941
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005942 // C++ [class.conv.fct]p4:
5943 // The conversion-type-id shall not represent a function type nor
5944 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005945 if (ConvType->isArrayType()) {
5946 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5947 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005948 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005949 } else if (ConvType->isFunctionType()) {
5950 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5951 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005952 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005953 }
5954
5955 // Rebuild the function type "R" without any parameters (in case any
5956 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005957 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005958 if (D.isInvalidType())
Jordan Rosebea522f2013-03-08 21:51:21 +00005959 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
5960 Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005961
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005962 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005963 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005964 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005965 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005966 diag::warn_cxx98_compat_explicit_conversion_functions :
5967 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005968 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005969}
5970
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005971/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5972/// the declaration of the given C++ conversion function. This routine
5973/// is responsible for recording the conversion function in the C++
5974/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005975Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005976 assert(Conversion && "Expected to receive a conversion function declaration");
5977
Douglas Gregor9d350972008-12-12 08:25:50 +00005978 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005979
5980 // Make sure we aren't redeclaring the conversion function.
5981 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005982
5983 // C++ [class.conv.fct]p1:
5984 // [...] A conversion function is never used to convert a
5985 // (possibly cv-qualified) object to the (possibly cv-qualified)
5986 // same object type (or a reference to it), to a (possibly
5987 // cv-qualified) base class of that type (or a reference to it),
5988 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005989 // FIXME: Suppress this warning if the conversion function ends up being a
5990 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005991 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005992 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005993 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005994 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005995 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5996 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005997 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005998 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005999 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6000 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006001 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006002 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006003 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006004 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006005 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006006 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006007 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006008 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006009 }
6010
Douglas Gregore80622f2010-09-29 04:25:11 +00006011 if (FunctionTemplateDecl *ConversionTemplate
6012 = Conversion->getDescribedFunctionTemplate())
6013 return ConversionTemplate;
6014
John McCalld226f652010-08-21 09:40:31 +00006015 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006016}
6017
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006018//===----------------------------------------------------------------------===//
6019// Namespace Handling
6020//===----------------------------------------------------------------------===//
6021
Richard Smithd1a55a62012-10-04 22:13:39 +00006022/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6023/// reopened.
6024static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6025 SourceLocation Loc,
6026 IdentifierInfo *II, bool *IsInline,
6027 NamespaceDecl *PrevNS) {
6028 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006029
Richard Smithc969e6a2012-10-05 01:46:25 +00006030 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6031 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6032 // inline namespaces, with the intention of bringing names into namespace std.
6033 //
6034 // We support this just well enough to get that case working; this is not
6035 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006036 if (*IsInline && II && II->getName().startswith("__atomic") &&
6037 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006038 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006039 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6040 NS = NS->getPreviousDecl())
6041 NS->setInline(*IsInline);
6042 // Patch up the lookup table for the containing namespace. This isn't really
6043 // correct, but it's good enough for this particular case.
6044 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6045 E = PrevNS->decls_end(); I != E; ++I)
6046 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6047 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6048 return;
6049 }
6050
6051 if (PrevNS->isInline())
6052 // The user probably just forgot the 'inline', so suggest that it
6053 // be added back.
6054 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6055 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6056 else
6057 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6058 << IsInline;
6059
6060 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6061 *IsInline = PrevNS->isInline();
6062}
John McCallea318642010-08-26 09:15:37 +00006063
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006064/// ActOnStartNamespaceDef - This is called at the start of a namespace
6065/// definition.
John McCalld226f652010-08-21 09:40:31 +00006066Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006067 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006068 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006069 SourceLocation IdentLoc,
6070 IdentifierInfo *II,
6071 SourceLocation LBrace,
6072 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006073 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6074 // For anonymous namespace, take the location of the left brace.
6075 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006076 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006077 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006078 bool IsStd = false;
6079 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006080 Scope *DeclRegionScope = NamespcScope->getParent();
6081
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006082 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006083 if (II) {
6084 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006085 // The identifier in an original-namespace-definition shall not
6086 // have been previously defined in the declarative region in
6087 // which the original-namespace-definition appears. The
6088 // identifier in an original-namespace-definition is the name of
6089 // the namespace. Subsequently in that declarative region, it is
6090 // treated as an original-namespace-name.
6091 //
6092 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006093 // look through using directives, just look for any ordinary names.
6094
6095 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006096 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6097 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006098 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006099 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6100 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6101 ++I) {
6102 if ((*I)->getIdentifierNamespace() & IDNS) {
6103 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006104 break;
6105 }
6106 }
6107
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006108 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6109
6110 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006111 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006112 if (IsInline != PrevNS->isInline())
6113 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6114 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006115 } else if (PrevDecl) {
6116 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006117 Diag(Loc, diag::err_redefinition_different_kind)
6118 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006119 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006120 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006121 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006122 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006123 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006124 // This is the first "real" definition of the namespace "std", so update
6125 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006126 PrevNS = getStdNamespace();
6127 IsStd = true;
6128 AddToKnown = !IsInline;
6129 } else {
6130 // We've seen this namespace for the first time.
6131 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006132 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006133 } else {
John McCall9aeed322009-10-01 00:25:31 +00006134 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006135
6136 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006137 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006138 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006139 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006140 } else {
6141 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006142 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006143 }
6144
Richard Smithd1a55a62012-10-04 22:13:39 +00006145 if (PrevNS && IsInline != PrevNS->isInline())
6146 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6147 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006148 }
6149
6150 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6151 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006152 if (IsInvalid)
6153 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006154
6155 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006156
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006157 // FIXME: Should we be merging attributes?
6158 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006159 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006160
6161 if (IsStd)
6162 StdNamespace = Namespc;
6163 if (AddToKnown)
6164 KnownNamespaces[Namespc] = false;
6165
6166 if (II) {
6167 PushOnScopeChains(Namespc, DeclRegionScope);
6168 } else {
6169 // Link the anonymous namespace into its parent.
6170 DeclContext *Parent = CurContext->getRedeclContext();
6171 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6172 TU->setAnonymousNamespace(Namespc);
6173 } else {
6174 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006175 }
John McCall9aeed322009-10-01 00:25:31 +00006176
Douglas Gregora4181472010-03-24 00:46:35 +00006177 CurContext->addDecl(Namespc);
6178
John McCall9aeed322009-10-01 00:25:31 +00006179 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6180 // behaves as if it were replaced by
6181 // namespace unique { /* empty body */ }
6182 // using namespace unique;
6183 // namespace unique { namespace-body }
6184 // where all occurrences of 'unique' in a translation unit are
6185 // replaced by the same identifier and this identifier differs
6186 // from all other identifiers in the entire program.
6187
6188 // We just create the namespace with an empty name and then add an
6189 // implicit using declaration, just like the standard suggests.
6190 //
6191 // CodeGen enforces the "universally unique" aspect by giving all
6192 // declarations semantically contained within an anonymous
6193 // namespace internal linkage.
6194
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006195 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006196 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006197 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006198 /* 'using' */ LBrace,
6199 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006200 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006201 /* identifier */ SourceLocation(),
6202 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006203 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006204 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006205 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006206 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006207 }
6208
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006209 ActOnDocumentableDecl(Namespc);
6210
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006211 // Although we could have an invalid decl (i.e. the namespace name is a
6212 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006213 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6214 // for the namespace has the declarations that showed up in that particular
6215 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006216 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006217 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006218}
6219
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006220/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6221/// is a namespace alias, returns the namespace it points to.
6222static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6223 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6224 return AD->getNamespace();
6225 return dyn_cast_or_null<NamespaceDecl>(D);
6226}
6227
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006228/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6229/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006230void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006231 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6232 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006233 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006234 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006235 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006236 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006237}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006238
John McCall384aff82010-08-25 07:42:41 +00006239CXXRecordDecl *Sema::getStdBadAlloc() const {
6240 return cast_or_null<CXXRecordDecl>(
6241 StdBadAlloc.get(Context.getExternalSource()));
6242}
6243
6244NamespaceDecl *Sema::getStdNamespace() const {
6245 return cast_or_null<NamespaceDecl>(
6246 StdNamespace.get(Context.getExternalSource()));
6247}
6248
Douglas Gregor66992202010-06-29 17:53:46 +00006249/// \brief Retrieve the special "std" namespace, which may require us to
6250/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006251NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006252 if (!StdNamespace) {
6253 // The "std" namespace has not yet been defined, so build one implicitly.
6254 StdNamespace = NamespaceDecl::Create(Context,
6255 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006256 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006257 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006258 &PP.getIdentifierTable().get("std"),
6259 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006260 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006261 }
6262
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006263 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006264}
6265
Sebastian Redl395e04d2012-01-17 22:49:33 +00006266bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006267 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006268 "Looking for std::initializer_list outside of C++.");
6269
6270 // We're looking for implicit instantiations of
6271 // template <typename E> class std::initializer_list.
6272
6273 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6274 return false;
6275
Sebastian Redl84760e32012-01-17 22:49:58 +00006276 ClassTemplateDecl *Template = 0;
6277 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006278
Sebastian Redl84760e32012-01-17 22:49:58 +00006279 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006280
Sebastian Redl84760e32012-01-17 22:49:58 +00006281 ClassTemplateSpecializationDecl *Specialization =
6282 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6283 if (!Specialization)
6284 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006285
Sebastian Redl84760e32012-01-17 22:49:58 +00006286 Template = Specialization->getSpecializedTemplate();
6287 Arguments = Specialization->getTemplateArgs().data();
6288 } else if (const TemplateSpecializationType *TST =
6289 Ty->getAs<TemplateSpecializationType>()) {
6290 Template = dyn_cast_or_null<ClassTemplateDecl>(
6291 TST->getTemplateName().getAsTemplateDecl());
6292 Arguments = TST->getArgs();
6293 }
6294 if (!Template)
6295 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006296
6297 if (!StdInitializerList) {
6298 // Haven't recognized std::initializer_list yet, maybe this is it.
6299 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6300 if (TemplateClass->getIdentifier() !=
6301 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006302 !getStdNamespace()->InEnclosingNamespaceSetOf(
6303 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006304 return false;
6305 // This is a template called std::initializer_list, but is it the right
6306 // template?
6307 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006308 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006309 return false;
6310 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6311 return false;
6312
6313 // It's the right template.
6314 StdInitializerList = Template;
6315 }
6316
6317 if (Template != StdInitializerList)
6318 return false;
6319
6320 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006321 if (Element)
6322 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006323 return true;
6324}
6325
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006326static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6327 NamespaceDecl *Std = S.getStdNamespace();
6328 if (!Std) {
6329 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6330 return 0;
6331 }
6332
6333 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6334 Loc, Sema::LookupOrdinaryName);
6335 if (!S.LookupQualifiedName(Result, Std)) {
6336 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6337 return 0;
6338 }
6339 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6340 if (!Template) {
6341 Result.suppressDiagnostics();
6342 // We found something weird. Complain about the first thing we found.
6343 NamedDecl *Found = *Result.begin();
6344 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6345 return 0;
6346 }
6347
6348 // We found some template called std::initializer_list. Now verify that it's
6349 // correct.
6350 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006351 if (Params->getMinRequiredArguments() != 1 ||
6352 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006353 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6354 return 0;
6355 }
6356
6357 return Template;
6358}
6359
6360QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6361 if (!StdInitializerList) {
6362 StdInitializerList = LookupStdInitializerList(*this, Loc);
6363 if (!StdInitializerList)
6364 return QualType();
6365 }
6366
6367 TemplateArgumentListInfo Args(Loc, Loc);
6368 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6369 Context.getTrivialTypeSourceInfo(Element,
6370 Loc)));
6371 return Context.getCanonicalType(
6372 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6373}
6374
Sebastian Redl98d36062012-01-17 22:50:14 +00006375bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6376 // C++ [dcl.init.list]p2:
6377 // A constructor is an initializer-list constructor if its first parameter
6378 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6379 // std::initializer_list<E> for some type E, and either there are no other
6380 // parameters or else all other parameters have default arguments.
6381 if (Ctor->getNumParams() < 1 ||
6382 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6383 return false;
6384
6385 QualType ArgType = Ctor->getParamDecl(0)->getType();
6386 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6387 ArgType = RT->getPointeeType().getUnqualifiedType();
6388
6389 return isStdInitializerList(ArgType, 0);
6390}
6391
Douglas Gregor9172aa62011-03-26 22:25:30 +00006392/// \brief Determine whether a using statement is in a context where it will be
6393/// apply in all contexts.
6394static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6395 switch (CurContext->getDeclKind()) {
6396 case Decl::TranslationUnit:
6397 return true;
6398 case Decl::LinkageSpec:
6399 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6400 default:
6401 return false;
6402 }
6403}
6404
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006405namespace {
6406
6407// Callback to only accept typo corrections that are namespaces.
6408class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6409 public:
6410 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6411 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6412 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6413 }
6414 return false;
6415 }
6416};
6417
6418}
6419
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006420static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6421 CXXScopeSpec &SS,
6422 SourceLocation IdentLoc,
6423 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006424 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006425 R.clear();
6426 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006427 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006428 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006429 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6430 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006431 if (DeclContext *DC = S.computeDeclContext(SS, false))
6432 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6433 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006434 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6435 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006436 else
6437 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6438 << Ident << CorrectedQuotedStr
6439 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006440
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006441 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6442 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006443
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006444 R.addDecl(Corrected.getCorrectionDecl());
6445 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006446 }
6447 return false;
6448}
6449
John McCalld226f652010-08-21 09:40:31 +00006450Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006451 SourceLocation UsingLoc,
6452 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006453 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006454 SourceLocation IdentLoc,
6455 IdentifierInfo *NamespcName,
6456 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006457 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6458 assert(NamespcName && "Invalid NamespcName.");
6459 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006460
6461 // This can only happen along a recovery path.
6462 while (S->getFlags() & Scope::TemplateParamScope)
6463 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006464 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006465
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006466 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006467 NestedNameSpecifier *Qualifier = 0;
6468 if (SS.isSet())
6469 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6470
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006471 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006472 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6473 LookupParsedName(R, S, &SS);
6474 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006475 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006476
Douglas Gregor66992202010-06-29 17:53:46 +00006477 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006478 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006479 // Allow "using namespace std;" or "using namespace ::std;" even if
6480 // "std" hasn't been defined yet, for GCC compatibility.
6481 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6482 NamespcName->isStr("std")) {
6483 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006484 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006485 R.resolveKind();
6486 }
6487 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006488 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006489 }
6490
John McCallf36e02d2009-10-09 21:13:30 +00006491 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006492 NamedDecl *Named = R.getFoundDecl();
6493 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6494 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006495 // C++ [namespace.udir]p1:
6496 // A using-directive specifies that the names in the nominated
6497 // namespace can be used in the scope in which the
6498 // using-directive appears after the using-directive. During
6499 // unqualified name lookup (3.4.1), the names appear as if they
6500 // were declared in the nearest enclosing namespace which
6501 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006502 // namespace. [Note: in this context, "contains" means "contains
6503 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006504
6505 // Find enclosing context containing both using-directive and
6506 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006507 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006508 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6509 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6510 CommonAncestor = CommonAncestor->getParent();
6511
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006512 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006513 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006514 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006515
Douglas Gregor9172aa62011-03-26 22:25:30 +00006516 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006517 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006518 Diag(IdentLoc, diag::warn_using_directive_in_header);
6519 }
6520
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006521 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006522 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006523 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006524 }
6525
Richard Smith6b3d3e52013-02-20 19:22:51 +00006526 if (UDir)
6527 ProcessDeclAttributeList(S, UDir, AttrList);
6528
John McCalld226f652010-08-21 09:40:31 +00006529 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006530}
6531
6532void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006533 // If the scope has an associated entity and the using directive is at
6534 // namespace or translation unit scope, add the UsingDirectiveDecl into
6535 // its lookup structure so qualified name lookup can find it.
6536 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6537 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006538 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006539 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006540 // Otherwise, it is at block sope. The using-directives will affect lookup
6541 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006542 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006543}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006544
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006545
John McCalld226f652010-08-21 09:40:31 +00006546Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006547 AccessSpecifier AS,
6548 bool HasUsingKeyword,
6549 SourceLocation UsingLoc,
6550 CXXScopeSpec &SS,
6551 UnqualifiedId &Name,
6552 AttributeList *AttrList,
6553 bool IsTypeName,
6554 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006555 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006556
Douglas Gregor12c118a2009-11-04 16:30:06 +00006557 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006558 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006559 case UnqualifiedId::IK_Identifier:
6560 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006561 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006562 case UnqualifiedId::IK_ConversionFunctionId:
6563 break;
6564
6565 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006566 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006567 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006568 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006569 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006570 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006571 diag::err_using_decl_constructor)
6572 << SS.getRange();
6573
Richard Smith80ad52f2013-01-02 11:42:31 +00006574 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006575
John McCalld226f652010-08-21 09:40:31 +00006576 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006577
6578 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006579 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006580 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006581 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006582
6583 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006584 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006585 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006586 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006587 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006588
6589 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6590 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006591 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006592 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006593
Richard Smith07b0fdc2013-03-18 21:12:30 +00006594 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006595 // TODO: store that the declaration was written without 'using' and
6596 // talk about access decls instead of using decls in the
6597 // diagnostics.
6598 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006599 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006600
6601 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006602 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006603 }
6604
Douglas Gregor56c04582010-12-16 00:46:58 +00006605 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6606 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6607 return 0;
6608
John McCall9488ea12009-11-17 05:59:44 +00006609 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006610 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006611 /* IsInstantiation */ false,
6612 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006613 if (UD)
6614 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006615
John McCalld226f652010-08-21 09:40:31 +00006616 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006617}
6618
Douglas Gregor09acc982010-07-07 23:08:52 +00006619/// \brief Determine whether a using declaration considers the given
6620/// declarations as "equivalent", e.g., if they are redeclarations of
6621/// the same entity or are both typedefs of the same type.
6622static bool
6623IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6624 bool &SuppressRedeclaration) {
6625 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6626 SuppressRedeclaration = false;
6627 return true;
6628 }
6629
Richard Smith162e1c12011-04-15 14:24:37 +00006630 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6631 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006632 SuppressRedeclaration = true;
6633 return Context.hasSameType(TD1->getUnderlyingType(),
6634 TD2->getUnderlyingType());
6635 }
6636
6637 return false;
6638}
6639
6640
John McCall9f54ad42009-12-10 09:41:52 +00006641/// Determines whether to create a using shadow decl for a particular
6642/// decl, given the set of decls existing prior to this using lookup.
6643bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6644 const LookupResult &Previous) {
6645 // Diagnose finding a decl which is not from a base class of the
6646 // current class. We do this now because there are cases where this
6647 // function will silently decide not to build a shadow decl, which
6648 // will pre-empt further diagnostics.
6649 //
6650 // We don't need to do this in C++0x because we do the check once on
6651 // the qualifier.
6652 //
6653 // FIXME: diagnose the following if we care enough:
6654 // struct A { int foo; };
6655 // struct B : A { using A::foo; };
6656 // template <class T> struct C : A {};
6657 // template <class T> struct D : C<T> { using B::foo; } // <---
6658 // This is invalid (during instantiation) in C++03 because B::foo
6659 // resolves to the using decl in B, which is not a base class of D<T>.
6660 // We can't diagnose it immediately because C<T> is an unknown
6661 // specialization. The UsingShadowDecl in D<T> then points directly
6662 // to A::foo, which will look well-formed when we instantiate.
6663 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006664 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006665 DeclContext *OrigDC = Orig->getDeclContext();
6666
6667 // Handle enums and anonymous structs.
6668 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6669 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6670 while (OrigRec->isAnonymousStructOrUnion())
6671 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6672
6673 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6674 if (OrigDC == CurContext) {
6675 Diag(Using->getLocation(),
6676 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006677 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006678 Diag(Orig->getLocation(), diag::note_using_decl_target);
6679 return true;
6680 }
6681
Douglas Gregordc355712011-02-25 00:36:19 +00006682 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006683 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006684 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006685 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006686 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006687 Diag(Orig->getLocation(), diag::note_using_decl_target);
6688 return true;
6689 }
6690 }
6691
6692 if (Previous.empty()) return false;
6693
6694 NamedDecl *Target = Orig;
6695 if (isa<UsingShadowDecl>(Target))
6696 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6697
John McCalld7533ec2009-12-11 02:33:26 +00006698 // If the target happens to be one of the previous declarations, we
6699 // don't have a conflict.
6700 //
6701 // FIXME: but we might be increasing its access, in which case we
6702 // should redeclare it.
6703 NamedDecl *NonTag = 0, *Tag = 0;
6704 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6705 I != E; ++I) {
6706 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006707 bool Result;
6708 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6709 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006710
6711 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6712 }
6713
John McCall9f54ad42009-12-10 09:41:52 +00006714 if (Target->isFunctionOrFunctionTemplate()) {
6715 FunctionDecl *FD;
6716 if (isa<FunctionTemplateDecl>(Target))
6717 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6718 else
6719 FD = cast<FunctionDecl>(Target);
6720
6721 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006722 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006723 case Ovl_Overload:
6724 return false;
6725
6726 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006727 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006728 break;
6729
6730 // We found a decl with the exact signature.
6731 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006732 // If we're in a record, we want to hide the target, so we
6733 // return true (without a diagnostic) to tell the caller not to
6734 // build a shadow decl.
6735 if (CurContext->isRecord())
6736 return true;
6737
6738 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006739 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006740 break;
6741 }
6742
6743 Diag(Target->getLocation(), diag::note_using_decl_target);
6744 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6745 return true;
6746 }
6747
6748 // Target is not a function.
6749
John McCall9f54ad42009-12-10 09:41:52 +00006750 if (isa<TagDecl>(Target)) {
6751 // No conflict between a tag and a non-tag.
6752 if (!Tag) return false;
6753
John McCall41ce66f2009-12-10 19:51:03 +00006754 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006755 Diag(Target->getLocation(), diag::note_using_decl_target);
6756 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6757 return true;
6758 }
6759
6760 // No conflict between a tag and a non-tag.
6761 if (!NonTag) return false;
6762
John McCall41ce66f2009-12-10 19:51:03 +00006763 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006764 Diag(Target->getLocation(), diag::note_using_decl_target);
6765 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6766 return true;
6767}
6768
John McCall9488ea12009-11-17 05:59:44 +00006769/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006770UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006771 UsingDecl *UD,
6772 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006773
6774 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006775 NamedDecl *Target = Orig;
6776 if (isa<UsingShadowDecl>(Target)) {
6777 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6778 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006779 }
6780
6781 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006782 = UsingShadowDecl::Create(Context, CurContext,
6783 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006784 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006785
6786 Shadow->setAccess(UD->getAccess());
6787 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6788 Shadow->setInvalidDecl();
6789
John McCall9488ea12009-11-17 05:59:44 +00006790 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006791 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006792 else
John McCall604e7f12009-12-08 07:46:18 +00006793 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006794
John McCall604e7f12009-12-08 07:46:18 +00006795
John McCall9f54ad42009-12-10 09:41:52 +00006796 return Shadow;
6797}
John McCall604e7f12009-12-08 07:46:18 +00006798
John McCall9f54ad42009-12-10 09:41:52 +00006799/// Hides a using shadow declaration. This is required by the current
6800/// using-decl implementation when a resolvable using declaration in a
6801/// class is followed by a declaration which would hide or override
6802/// one or more of the using decl's targets; for example:
6803///
6804/// struct Base { void foo(int); };
6805/// struct Derived : Base {
6806/// using Base::foo;
6807/// void foo(int);
6808/// };
6809///
6810/// The governing language is C++03 [namespace.udecl]p12:
6811///
6812/// When a using-declaration brings names from a base class into a
6813/// derived class scope, member functions in the derived class
6814/// override and/or hide member functions with the same name and
6815/// parameter types in a base class (rather than conflicting).
6816///
6817/// There are two ways to implement this:
6818/// (1) optimistically create shadow decls when they're not hidden
6819/// by existing declarations, or
6820/// (2) don't create any shadow decls (or at least don't make them
6821/// visible) until we've fully parsed/instantiated the class.
6822/// The problem with (1) is that we might have to retroactively remove
6823/// a shadow decl, which requires several O(n) operations because the
6824/// decl structures are (very reasonably) not designed for removal.
6825/// (2) avoids this but is very fiddly and phase-dependent.
6826void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006827 if (Shadow->getDeclName().getNameKind() ==
6828 DeclarationName::CXXConversionFunctionName)
6829 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6830
John McCall9f54ad42009-12-10 09:41:52 +00006831 // Remove it from the DeclContext...
6832 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006833
John McCall9f54ad42009-12-10 09:41:52 +00006834 // ...and the scope, if applicable...
6835 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006836 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006837 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006838 }
6839
John McCall9f54ad42009-12-10 09:41:52 +00006840 // ...and the using decl.
6841 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6842
6843 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006844 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006845}
6846
John McCall7ba107a2009-11-18 02:36:19 +00006847/// Builds a using declaration.
6848///
6849/// \param IsInstantiation - Whether this call arises from an
6850/// instantiation of an unresolved using declaration. We treat
6851/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006852NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6853 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006854 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006855 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006856 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006857 bool IsInstantiation,
6858 bool IsTypeName,
6859 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006860 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006861 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006862 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006863
Anders Carlsson550b14b2009-08-28 05:49:21 +00006864 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006865
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006866 if (SS.isEmpty()) {
6867 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006868 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006869 }
Mike Stump1eb44332009-09-09 15:08:12 +00006870
John McCall9f54ad42009-12-10 09:41:52 +00006871 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006872 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006873 ForRedeclaration);
6874 Previous.setHideTags(false);
6875 if (S) {
6876 LookupName(Previous, S);
6877
6878 // It is really dumb that we have to do this.
6879 LookupResult::Filter F = Previous.makeFilter();
6880 while (F.hasNext()) {
6881 NamedDecl *D = F.next();
6882 if (!isDeclInScope(D, CurContext, S))
6883 F.erase();
6884 }
6885 F.done();
6886 } else {
6887 assert(IsInstantiation && "no scope in non-instantiation");
6888 assert(CurContext->isRecord() && "scope not record in instantiation");
6889 LookupQualifiedName(Previous, CurContext);
6890 }
6891
John McCall9f54ad42009-12-10 09:41:52 +00006892 // Check for invalid redeclarations.
6893 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6894 return 0;
6895
6896 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006897 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6898 return 0;
6899
John McCallaf8e6ed2009-11-12 03:15:40 +00006900 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006901 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006902 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006903 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006904 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006905 // FIXME: not all declaration name kinds are legal here
6906 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6907 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006908 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006909 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006910 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006911 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6912 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006913 }
John McCalled976492009-12-04 22:46:56 +00006914 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006915 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6916 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006917 }
John McCalled976492009-12-04 22:46:56 +00006918 D->setAccess(AS);
6919 CurContext->addDecl(D);
6920
6921 if (!LookupContext) return D;
6922 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006923
John McCall77bb1aa2010-05-01 00:40:08 +00006924 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006925 UD->setInvalidDecl();
6926 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006927 }
6928
Richard Smithc5a89a12012-04-02 01:30:27 +00006929 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006930 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006931 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006932 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006933 return UD;
6934 }
6935
6936 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006937
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006938 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006939
John McCall604e7f12009-12-08 07:46:18 +00006940 // Unlike most lookups, we don't always want to hide tag
6941 // declarations: tag names are visible through the using declaration
6942 // even if hidden by ordinary names, *except* in a dependent context
6943 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006944 if (!IsInstantiation)
6945 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006946
John McCallb9abd8722012-04-07 03:04:20 +00006947 // For the purposes of this lookup, we have a base object type
6948 // equal to that of the current context.
6949 if (CurContext->isRecord()) {
6950 R.setBaseObjectType(
6951 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6952 }
6953
John McCalla24dc2e2009-11-17 02:14:36 +00006954 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006955
John McCallf36e02d2009-10-09 21:13:30 +00006956 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006957 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006958 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006959 UD->setInvalidDecl();
6960 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006961 }
6962
John McCalled976492009-12-04 22:46:56 +00006963 if (R.isAmbiguous()) {
6964 UD->setInvalidDecl();
6965 return UD;
6966 }
Mike Stump1eb44332009-09-09 15:08:12 +00006967
John McCall7ba107a2009-11-18 02:36:19 +00006968 if (IsTypeName) {
6969 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006970 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006971 Diag(IdentLoc, diag::err_using_typename_non_type);
6972 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6973 Diag((*I)->getUnderlyingDecl()->getLocation(),
6974 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006975 UD->setInvalidDecl();
6976 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006977 }
6978 } else {
6979 // If we asked for a non-typename and we got a type, error out,
6980 // but only if this is an instantiation of an unresolved using
6981 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006982 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006983 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6984 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006985 UD->setInvalidDecl();
6986 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006987 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006988 }
6989
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006990 // C++0x N2914 [namespace.udecl]p6:
6991 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006992 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006993 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6994 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006995 UD->setInvalidDecl();
6996 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006997 }
Mike Stump1eb44332009-09-09 15:08:12 +00006998
John McCall9f54ad42009-12-10 09:41:52 +00006999 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7000 if (!CheckUsingShadowDecl(UD, *I, Previous))
7001 BuildUsingShadowDecl(S, UD, *I);
7002 }
John McCall9488ea12009-11-17 05:59:44 +00007003
7004 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007005}
7006
Sebastian Redlf677ea32011-02-05 19:23:19 +00007007/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007008bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7009 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007010
Douglas Gregordc355712011-02-25 00:36:19 +00007011 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007012 assert(SourceType &&
7013 "Using decl naming constructor doesn't have type in scope spec.");
7014 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7015
7016 // Check whether the named type is a direct base class.
7017 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7018 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7019 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7020 BaseIt != BaseE; ++BaseIt) {
7021 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7022 if (CanonicalSourceType == BaseType)
7023 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007024 if (BaseIt->getType()->isDependentType())
7025 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007026 }
7027
7028 if (BaseIt == BaseE) {
7029 // Did not find SourceType in the bases.
7030 Diag(UD->getUsingLocation(),
7031 diag::err_using_decl_constructor_not_in_direct_base)
7032 << UD->getNameInfo().getSourceRange()
7033 << QualType(SourceType, 0) << TargetClass;
7034 return true;
7035 }
7036
Richard Smithc5a89a12012-04-02 01:30:27 +00007037 if (!CurContext->isDependentContext())
7038 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007039
7040 return false;
7041}
7042
John McCall9f54ad42009-12-10 09:41:52 +00007043/// Checks that the given using declaration is not an invalid
7044/// redeclaration. Note that this is checking only for the using decl
7045/// itself, not for any ill-formedness among the UsingShadowDecls.
7046bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7047 bool isTypeName,
7048 const CXXScopeSpec &SS,
7049 SourceLocation NameLoc,
7050 const LookupResult &Prev) {
7051 // C++03 [namespace.udecl]p8:
7052 // C++0x [namespace.udecl]p10:
7053 // A using-declaration is a declaration and can therefore be used
7054 // repeatedly where (and only where) multiple declarations are
7055 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007056 //
John McCall8a726212010-11-29 18:01:58 +00007057 // That's in non-member contexts.
7058 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007059 return false;
7060
7061 NestedNameSpecifier *Qual
7062 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7063
7064 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7065 NamedDecl *D = *I;
7066
7067 bool DTypename;
7068 NestedNameSpecifier *DQual;
7069 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7070 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007071 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007072 } else if (UnresolvedUsingValueDecl *UD
7073 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7074 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007075 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007076 } else if (UnresolvedUsingTypenameDecl *UD
7077 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7078 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007079 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007080 } else continue;
7081
7082 // using decls differ if one says 'typename' and the other doesn't.
7083 // FIXME: non-dependent using decls?
7084 if (isTypeName != DTypename) continue;
7085
7086 // using decls differ if they name different scopes (but note that
7087 // template instantiation can cause this check to trigger when it
7088 // didn't before instantiation).
7089 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7090 Context.getCanonicalNestedNameSpecifier(DQual))
7091 continue;
7092
7093 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007094 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007095 return true;
7096 }
7097
7098 return false;
7099}
7100
John McCall604e7f12009-12-08 07:46:18 +00007101
John McCalled976492009-12-04 22:46:56 +00007102/// Checks that the given nested-name qualifier used in a using decl
7103/// in the current context is appropriately related to the current
7104/// scope. If an error is found, diagnoses it and returns true.
7105bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7106 const CXXScopeSpec &SS,
7107 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007108 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007109
John McCall604e7f12009-12-08 07:46:18 +00007110 if (!CurContext->isRecord()) {
7111 // C++03 [namespace.udecl]p3:
7112 // C++0x [namespace.udecl]p8:
7113 // A using-declaration for a class member shall be a member-declaration.
7114
7115 // If we weren't able to compute a valid scope, it must be a
7116 // dependent class scope.
7117 if (!NamedContext || NamedContext->isRecord()) {
7118 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7119 << SS.getRange();
7120 return true;
7121 }
7122
7123 // Otherwise, everything is known to be fine.
7124 return false;
7125 }
7126
7127 // The current scope is a record.
7128
7129 // If the named context is dependent, we can't decide much.
7130 if (!NamedContext) {
7131 // FIXME: in C++0x, we can diagnose if we can prove that the
7132 // nested-name-specifier does not refer to a base class, which is
7133 // still possible in some cases.
7134
7135 // Otherwise we have to conservatively report that things might be
7136 // okay.
7137 return false;
7138 }
7139
7140 if (!NamedContext->isRecord()) {
7141 // Ideally this would point at the last name in the specifier,
7142 // but we don't have that level of source info.
7143 Diag(SS.getRange().getBegin(),
7144 diag::err_using_decl_nested_name_specifier_is_not_class)
7145 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7146 return true;
7147 }
7148
Douglas Gregor6fb07292010-12-21 07:41:49 +00007149 if (!NamedContext->isDependentContext() &&
7150 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7151 return true;
7152
Richard Smith80ad52f2013-01-02 11:42:31 +00007153 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007154 // C++0x [namespace.udecl]p3:
7155 // In a using-declaration used as a member-declaration, the
7156 // nested-name-specifier shall name a base class of the class
7157 // being defined.
7158
7159 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7160 cast<CXXRecordDecl>(NamedContext))) {
7161 if (CurContext == NamedContext) {
7162 Diag(NameLoc,
7163 diag::err_using_decl_nested_name_specifier_is_current_class)
7164 << SS.getRange();
7165 return true;
7166 }
7167
7168 Diag(SS.getRange().getBegin(),
7169 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7170 << (NestedNameSpecifier*) SS.getScopeRep()
7171 << cast<CXXRecordDecl>(CurContext)
7172 << SS.getRange();
7173 return true;
7174 }
7175
7176 return false;
7177 }
7178
7179 // C++03 [namespace.udecl]p4:
7180 // A using-declaration used as a member-declaration shall refer
7181 // to a member of a base class of the class being defined [etc.].
7182
7183 // Salient point: SS doesn't have to name a base class as long as
7184 // lookup only finds members from base classes. Therefore we can
7185 // diagnose here only if we can prove that that can't happen,
7186 // i.e. if the class hierarchies provably don't intersect.
7187
7188 // TODO: it would be nice if "definitely valid" results were cached
7189 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7190 // need to be repeated.
7191
7192 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007193 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007194
7195 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7196 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7197 Data->Bases.insert(Base);
7198 return true;
7199 }
7200
7201 bool hasDependentBases(const CXXRecordDecl *Class) {
7202 return !Class->forallBases(collect, this);
7203 }
7204
7205 /// Returns true if the base is dependent or is one of the
7206 /// accumulated base classes.
7207 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7208 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7209 return !Data->Bases.count(Base);
7210 }
7211
7212 bool mightShareBases(const CXXRecordDecl *Class) {
7213 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7214 }
7215 };
7216
7217 UserData Data;
7218
7219 // Returns false if we find a dependent base.
7220 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7221 return false;
7222
7223 // Returns false if the class has a dependent base or if it or one
7224 // of its bases is present in the base set of the current context.
7225 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7226 return false;
7227
7228 Diag(SS.getRange().getBegin(),
7229 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7230 << (NestedNameSpecifier*) SS.getScopeRep()
7231 << cast<CXXRecordDecl>(CurContext)
7232 << SS.getRange();
7233
7234 return true;
John McCalled976492009-12-04 22:46:56 +00007235}
7236
Richard Smith162e1c12011-04-15 14:24:37 +00007237Decl *Sema::ActOnAliasDeclaration(Scope *S,
7238 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007239 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007240 SourceLocation UsingLoc,
7241 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007242 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007243 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007244 // Skip up to the relevant declaration scope.
7245 while (S->getFlags() & Scope::TemplateParamScope)
7246 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007247 assert((S->getFlags() & Scope::DeclScope) &&
7248 "got alias-declaration outside of declaration scope");
7249
7250 if (Type.isInvalid())
7251 return 0;
7252
7253 bool Invalid = false;
7254 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7255 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007256 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007257
7258 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7259 return 0;
7260
7261 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007262 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007263 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007264 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7265 TInfo->getTypeLoc().getBeginLoc());
7266 }
Richard Smith162e1c12011-04-15 14:24:37 +00007267
7268 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7269 LookupName(Previous, S);
7270
7271 // Warn about shadowing the name of a template parameter.
7272 if (Previous.isSingleResult() &&
7273 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007274 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007275 Previous.clear();
7276 }
7277
7278 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7279 "name in alias declaration must be an identifier");
7280 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7281 Name.StartLocation,
7282 Name.Identifier, TInfo);
7283
7284 NewTD->setAccess(AS);
7285
7286 if (Invalid)
7287 NewTD->setInvalidDecl();
7288
Richard Smith6b3d3e52013-02-20 19:22:51 +00007289 ProcessDeclAttributeList(S, NewTD, AttrList);
7290
Richard Smith3e4c6c42011-05-05 21:57:07 +00007291 CheckTypedefForVariablyModifiedType(S, NewTD);
7292 Invalid |= NewTD->isInvalidDecl();
7293
Richard Smith162e1c12011-04-15 14:24:37 +00007294 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007295
7296 NamedDecl *NewND;
7297 if (TemplateParamLists.size()) {
7298 TypeAliasTemplateDecl *OldDecl = 0;
7299 TemplateParameterList *OldTemplateParams = 0;
7300
7301 if (TemplateParamLists.size() != 1) {
7302 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007303 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7304 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007305 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007306 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007307
7308 // Only consider previous declarations in the same scope.
7309 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7310 /*ExplicitInstantiationOrSpecialization*/false);
7311 if (!Previous.empty()) {
7312 Redeclaration = true;
7313
7314 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7315 if (!OldDecl && !Invalid) {
7316 Diag(UsingLoc, diag::err_redefinition_different_kind)
7317 << Name.Identifier;
7318
7319 NamedDecl *OldD = Previous.getRepresentativeDecl();
7320 if (OldD->getLocation().isValid())
7321 Diag(OldD->getLocation(), diag::note_previous_definition);
7322
7323 Invalid = true;
7324 }
7325
7326 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7327 if (TemplateParameterListsAreEqual(TemplateParams,
7328 OldDecl->getTemplateParameters(),
7329 /*Complain=*/true,
7330 TPL_TemplateMatch))
7331 OldTemplateParams = OldDecl->getTemplateParameters();
7332 else
7333 Invalid = true;
7334
7335 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7336 if (!Invalid &&
7337 !Context.hasSameType(OldTD->getUnderlyingType(),
7338 NewTD->getUnderlyingType())) {
7339 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7340 // but we can't reasonably accept it.
7341 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7342 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7343 if (OldTD->getLocation().isValid())
7344 Diag(OldTD->getLocation(), diag::note_previous_definition);
7345 Invalid = true;
7346 }
7347 }
7348 }
7349
7350 // Merge any previous default template arguments into our parameters,
7351 // and check the parameter list.
7352 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7353 TPC_TypeAliasTemplate))
7354 return 0;
7355
7356 TypeAliasTemplateDecl *NewDecl =
7357 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7358 Name.Identifier, TemplateParams,
7359 NewTD);
7360
7361 NewDecl->setAccess(AS);
7362
7363 if (Invalid)
7364 NewDecl->setInvalidDecl();
7365 else if (OldDecl)
7366 NewDecl->setPreviousDeclaration(OldDecl);
7367
7368 NewND = NewDecl;
7369 } else {
7370 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7371 NewND = NewTD;
7372 }
Richard Smith162e1c12011-04-15 14:24:37 +00007373
7374 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007375 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007376
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007377 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007378 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007379}
7380
John McCalld226f652010-08-21 09:40:31 +00007381Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007382 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007383 SourceLocation AliasLoc,
7384 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007385 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007386 SourceLocation IdentLoc,
7387 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007388
Anders Carlsson81c85c42009-03-28 23:53:49 +00007389 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007390 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7391 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007392
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007393 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007394 NamedDecl *PrevDecl
7395 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7396 ForRedeclaration);
7397 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7398 PrevDecl = 0;
7399
7400 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007401 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007402 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007403 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007404 // FIXME: At some point, we'll want to create the (redundant)
7405 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007406 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007407 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007408 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007409 }
Mike Stump1eb44332009-09-09 15:08:12 +00007410
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007411 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7412 diag::err_redefinition_different_kind;
7413 Diag(AliasLoc, DiagID) << Alias;
7414 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007415 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007416 }
7417
John McCalla24dc2e2009-11-17 02:14:36 +00007418 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007419 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007420
John McCallf36e02d2009-10-09 21:13:30 +00007421 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007422 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007423 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007424 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007425 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007426 }
Mike Stump1eb44332009-09-09 15:08:12 +00007427
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007428 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007429 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007430 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007431 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007432
John McCall3dbd3d52010-02-16 06:53:13 +00007433 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007434 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007435}
7436
Sean Hunt001cad92011-05-10 00:49:42 +00007437Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007438Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7439 CXXMethodDecl *MD) {
7440 CXXRecordDecl *ClassDecl = MD->getParent();
7441
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007442 // C++ [except.spec]p14:
7443 // An implicitly declared special member function (Clause 12) shall have an
7444 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007445 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007446 if (ClassDecl->isInvalidDecl())
7447 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007448
Sebastian Redl60618fa2011-03-12 11:50:43 +00007449 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007450 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7451 BEnd = ClassDecl->bases_end();
7452 B != BEnd; ++B) {
7453 if (B->isVirtual()) // Handled below.
7454 continue;
7455
Douglas Gregor18274032010-07-03 00:47:00 +00007456 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7457 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007458 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7459 // If this is a deleted function, add it anyway. This might be conformant
7460 // with the standard. This might not. I'm not sure. It might not matter.
7461 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007462 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007463 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007464 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007465
7466 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007467 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7468 BEnd = ClassDecl->vbases_end();
7469 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007470 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7471 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007472 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7473 // If this is a deleted function, add it anyway. This might be conformant
7474 // with the standard. This might not. I'm not sure. It might not matter.
7475 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007476 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007477 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007478 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007479
7480 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007481 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7482 FEnd = ClassDecl->field_end();
7483 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007484 if (F->hasInClassInitializer()) {
7485 if (Expr *E = F->getInClassInitializer())
7486 ExceptSpec.CalledExpr(E);
7487 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007488 // DR1351:
7489 // If the brace-or-equal-initializer of a non-static data member
7490 // invokes a defaulted default constructor of its class or of an
7491 // enclosing class in a potentially evaluated subexpression, the
7492 // program is ill-formed.
7493 //
7494 // This resolution is unworkable: the exception specification of the
7495 // default constructor can be needed in an unevaluated context, in
7496 // particular, in the operand of a noexcept-expression, and we can be
7497 // unable to compute an exception specification for an enclosed class.
7498 //
7499 // We do not allow an in-class initializer to require the evaluation
7500 // of the exception specification for any in-class initializer whose
7501 // definition is not lexically complete.
7502 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007503 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007504 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007505 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7506 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7507 // If this is a deleted function, add it anyway. This might be conformant
7508 // with the standard. This might not. I'm not sure. It might not matter.
7509 // In particular, the problem is that this function never gets called. It
7510 // might just be ill-formed because this function attempts to refer to
7511 // a deleted function here.
7512 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007513 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007514 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007515 }
John McCalle23cf432010-12-14 08:05:40 +00007516
Sean Hunt001cad92011-05-10 00:49:42 +00007517 return ExceptSpec;
7518}
7519
Richard Smith07b0fdc2013-03-18 21:12:30 +00007520Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007521Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7522 CXXRecordDecl *ClassDecl = CD->getParent();
7523
7524 // C++ [except.spec]p14:
7525 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007526 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007527 if (ClassDecl->isInvalidDecl())
7528 return ExceptSpec;
7529
7530 // Inherited constructor.
7531 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7532 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7533 // FIXME: Copying or moving the parameters could add extra exceptions to the
7534 // set, as could the default arguments for the inherited constructor. This
7535 // will be addressed when we implement the resolution of core issue 1351.
7536 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7537
7538 // Direct base-class constructors.
7539 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7540 BEnd = ClassDecl->bases_end();
7541 B != BEnd; ++B) {
7542 if (B->isVirtual()) // Handled below.
7543 continue;
7544
7545 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7546 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7547 if (BaseClassDecl == InheritedDecl)
7548 continue;
7549 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7550 if (Constructor)
7551 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7552 }
7553 }
7554
7555 // Virtual base-class constructors.
7556 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7557 BEnd = ClassDecl->vbases_end();
7558 B != BEnd; ++B) {
7559 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7560 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7561 if (BaseClassDecl == InheritedDecl)
7562 continue;
7563 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7564 if (Constructor)
7565 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7566 }
7567 }
7568
7569 // Field constructors.
7570 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7571 FEnd = ClassDecl->field_end();
7572 F != FEnd; ++F) {
7573 if (F->hasInClassInitializer()) {
7574 if (Expr *E = F->getInClassInitializer())
7575 ExceptSpec.CalledExpr(E);
7576 else if (!F->isInvalidDecl())
7577 Diag(CD->getLocation(),
7578 diag::err_in_class_initializer_references_def_ctor) << CD;
7579 } else if (const RecordType *RecordTy
7580 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7581 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7582 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7583 if (Constructor)
7584 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7585 }
7586 }
7587
Richard Smith07b0fdc2013-03-18 21:12:30 +00007588 return ExceptSpec;
7589}
7590
Richard Smithafb49182012-11-29 01:34:07 +00007591namespace {
7592/// RAII object to register a special member as being currently declared.
7593struct DeclaringSpecialMember {
7594 Sema &S;
7595 Sema::SpecialMemberDecl D;
7596 bool WasAlreadyBeingDeclared;
7597
7598 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7599 : S(S), D(RD, CSM) {
7600 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7601 if (WasAlreadyBeingDeclared)
7602 // This almost never happens, but if it does, ensure that our cache
7603 // doesn't contain a stale result.
7604 S.SpecialMemberCache.clear();
7605
7606 // FIXME: Register a note to be produced if we encounter an error while
7607 // declaring the special member.
7608 }
7609 ~DeclaringSpecialMember() {
7610 if (!WasAlreadyBeingDeclared)
7611 S.SpecialMembersBeingDeclared.erase(D);
7612 }
7613
7614 /// \brief Are we already trying to declare this special member?
7615 bool isAlreadyBeingDeclared() const {
7616 return WasAlreadyBeingDeclared;
7617 }
7618};
7619}
7620
Sean Hunt001cad92011-05-10 00:49:42 +00007621CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7622 CXXRecordDecl *ClassDecl) {
7623 // C++ [class.ctor]p5:
7624 // A default constructor for a class X is a constructor of class X
7625 // that can be called without an argument. If there is no
7626 // user-declared constructor for class X, a default constructor is
7627 // implicitly declared. An implicitly-declared default constructor
7628 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007629 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007630 "Should not build implicit default constructor!");
7631
Richard Smithafb49182012-11-29 01:34:07 +00007632 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7633 if (DSM.isAlreadyBeingDeclared())
7634 return 0;
7635
Richard Smith7756afa2012-06-10 05:43:50 +00007636 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7637 CXXDefaultConstructor,
7638 false);
7639
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007640 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007641 CanQualType ClassType
7642 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007643 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007644 DeclarationName Name
7645 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007646 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007647 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007648 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007649 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007650 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007651 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007652 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007653 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007654
7655 // Build an exception specification pointing back at this constructor.
7656 FunctionProtoType::ExtProtoInfo EPI;
7657 EPI.ExceptionSpecType = EST_Unevaluated;
7658 EPI.ExceptionSpecDecl = DefaultCon;
Jordan Rosebea522f2013-03-08 21:51:21 +00007659 DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7660 ArrayRef<QualType>(),
7661 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007662
Richard Smithbc2a35d2012-12-08 08:32:28 +00007663 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7664 // constructors is easy to compute.
7665 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7666
7667 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007668 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007669
Douglas Gregor18274032010-07-03 00:47:00 +00007670 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007671 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007672
Douglas Gregor23c94db2010-07-02 17:43:08 +00007673 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007674 PushOnScopeChains(DefaultCon, S, false);
7675 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007676
Douglas Gregor32df23e2010-07-01 22:02:46 +00007677 return DefaultCon;
7678}
7679
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007680void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7681 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007682 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007683 !Constructor->doesThisDeclarationHaveABody() &&
7684 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007685 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007686
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007687 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007688 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007689
Eli Friedman9a14db32012-10-18 20:14:08 +00007690 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007691 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007692 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007693 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007694 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007695 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007696 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007697 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007698 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007699
7700 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007701 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007702
7703 Constructor->setUsed();
7704 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007705
7706 if (ASTMutationListener *L = getASTMutationListener()) {
7707 L->CompletedImplicitDefinition(Constructor);
7708 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007709}
7710
Richard Smith7a614d82011-06-11 17:19:42 +00007711void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007712 // Check that any explicitly-defaulted methods have exception specifications
7713 // compatible with their implicit exception specifications.
7714 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007715}
7716
Richard Smith4841ca52013-04-10 05:48:59 +00007717namespace {
7718/// Information on inheriting constructors to declare.
7719class InheritingConstructorInfo {
7720public:
7721 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7722 : SemaRef(SemaRef), Derived(Derived) {
7723 // Mark the constructors that we already have in the derived class.
7724 //
7725 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7726 // unless there is a user-declared constructor with the same signature in
7727 // the class where the using-declaration appears.
7728 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7729 }
7730
7731 void inheritAll(CXXRecordDecl *RD) {
7732 visitAll(RD, &InheritingConstructorInfo::inherit);
7733 }
7734
7735private:
7736 /// Information about an inheriting constructor.
7737 struct InheritingConstructor {
7738 InheritingConstructor()
7739 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7740
7741 /// If \c true, a constructor with this signature is already declared
7742 /// in the derived class.
7743 bool DeclaredInDerived;
7744
7745 /// The constructor which is inherited.
7746 const CXXConstructorDecl *BaseCtor;
7747
7748 /// The derived constructor we declared.
7749 CXXConstructorDecl *DerivedCtor;
7750 };
7751
7752 /// Inheriting constructors with a given canonical type. There can be at
7753 /// most one such non-template constructor, and any number of templated
7754 /// constructors.
7755 struct InheritingConstructorsForType {
7756 InheritingConstructor NonTemplate;
7757 llvm::SmallVector<
7758 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7759
7760 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7761 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7762 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7763 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7764 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7765 false, S.TPL_TemplateMatch))
7766 return Templates[I].second;
7767 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7768 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007769 }
Richard Smith4841ca52013-04-10 05:48:59 +00007770
7771 return NonTemplate;
7772 }
7773 };
7774
7775 /// Get or create the inheriting constructor record for a constructor.
7776 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7777 QualType CtorType) {
7778 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7779 .getEntry(SemaRef, Ctor);
7780 }
7781
7782 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7783
7784 /// Process all constructors for a class.
7785 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7786 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7787 CtorE = RD->ctor_end();
7788 CtorIt != CtorE; ++CtorIt)
7789 (this->*Callback)(*CtorIt);
7790 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7791 I(RD->decls_begin()), E(RD->decls_end());
7792 I != E; ++I) {
7793 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7794 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7795 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007796 }
7797 }
Richard Smith4841ca52013-04-10 05:48:59 +00007798
7799 /// Note that a constructor (or constructor template) was declared in Derived.
7800 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7801 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7802 }
7803
7804 /// Inherit a single constructor.
7805 void inherit(const CXXConstructorDecl *Ctor) {
7806 const FunctionProtoType *CtorType =
7807 Ctor->getType()->castAs<FunctionProtoType>();
7808 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7809 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7810
7811 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7812
7813 // Core issue (no number yet): the ellipsis is always discarded.
7814 if (EPI.Variadic) {
7815 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7816 SemaRef.Diag(Ctor->getLocation(),
7817 diag::note_using_decl_constructor_ellipsis);
7818 EPI.Variadic = false;
7819 }
7820
7821 // Declare a constructor for each number of parameters.
7822 //
7823 // C++11 [class.inhctor]p1:
7824 // The candidate set of inherited constructors from the class X named in
7825 // the using-declaration consists of [... modulo defects ...] for each
7826 // constructor or constructor template of X, the set of constructors or
7827 // constructor templates that results from omitting any ellipsis parameter
7828 // specification and successively omitting parameters with a default
7829 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00007830 unsigned MinParams = minParamsToInherit(Ctor);
7831 unsigned Params = Ctor->getNumParams();
7832 if (Params >= MinParams) {
7833 do
7834 declareCtor(UsingLoc, Ctor,
7835 SemaRef.Context.getFunctionType(
7836 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7837 while (Params > MinParams &&
7838 Ctor->getParamDecl(--Params)->hasDefaultArg());
7839 }
Richard Smith4841ca52013-04-10 05:48:59 +00007840 }
7841
7842 /// Find the using-declaration which specified that we should inherit the
7843 /// constructors of \p Base.
7844 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7845 // No fancy lookup required; just look for the base constructor name
7846 // directly within the derived class.
7847 ASTContext &Context = SemaRef.Context;
7848 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7849 Context.getCanonicalType(Context.getRecordType(Base)));
7850 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
7851 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
7852 }
7853
7854 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
7855 // C++11 [class.inhctor]p3:
7856 // [F]or each constructor template in the candidate set of inherited
7857 // constructors, a constructor template is implicitly declared
7858 if (Ctor->getDescribedFunctionTemplate())
7859 return 0;
7860
7861 // For each non-template constructor in the candidate set of inherited
7862 // constructors other than a constructor having no parameters or a
7863 // copy/move constructor having a single parameter, a constructor is
7864 // implicitly declared [...]
7865 if (Ctor->getNumParams() == 0)
7866 return 1;
7867 if (Ctor->isCopyOrMoveConstructor())
7868 return 2;
7869
7870 // Per discussion on core reflector, never inherit a constructor which
7871 // would become a default, copy, or move constructor of Derived either.
7872 const ParmVarDecl *PD = Ctor->getParamDecl(0);
7873 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
7874 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
7875 }
7876
7877 /// Declare a single inheriting constructor, inheriting the specified
7878 /// constructor, with the given type.
7879 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
7880 QualType DerivedType) {
7881 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
7882
7883 // C++11 [class.inhctor]p3:
7884 // ... a constructor is implicitly declared with the same constructor
7885 // characteristics unless there is a user-declared constructor with
7886 // the same signature in the class where the using-declaration appears
7887 if (Entry.DeclaredInDerived)
7888 return;
7889
7890 // C++11 [class.inhctor]p7:
7891 // If two using-declarations declare inheriting constructors with the
7892 // same signature, the program is ill-formed
7893 if (Entry.DerivedCtor) {
7894 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
7895 // Only diagnose this once per constructor.
7896 if (Entry.DerivedCtor->isInvalidDecl())
7897 return;
7898 Entry.DerivedCtor->setInvalidDecl();
7899
7900 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7901 SemaRef.Diag(BaseCtor->getLocation(),
7902 diag::note_using_decl_constructor_conflict_current_ctor);
7903 SemaRef.Diag(Entry.BaseCtor->getLocation(),
7904 diag::note_using_decl_constructor_conflict_previous_ctor);
7905 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
7906 diag::note_using_decl_constructor_conflict_previous_using);
7907 } else {
7908 // Core issue (no number): if the same inheriting constructor is
7909 // produced by multiple base class constructors from the same base
7910 // class, the inheriting constructor is defined as deleted.
7911 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
7912 }
7913
7914 return;
7915 }
7916
7917 ASTContext &Context = SemaRef.Context;
7918 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7919 Context.getCanonicalType(Context.getRecordType(Derived)));
7920 DeclarationNameInfo NameInfo(Name, UsingLoc);
7921
7922 TemplateParameterList *TemplateParams = 0;
7923 if (const FunctionTemplateDecl *FTD =
7924 BaseCtor->getDescribedFunctionTemplate()) {
7925 TemplateParams = FTD->getTemplateParameters();
7926 // We're reusing template parameters from a different DeclContext. This
7927 // is questionable at best, but works out because the template depth in
7928 // both places is guaranteed to be 0.
7929 // FIXME: Rebuild the template parameters in the new context, and
7930 // transform the function type to refer to them.
7931 }
7932
7933 // Build type source info pointing at the using-declaration. This is
7934 // required by template instantiation.
7935 TypeSourceInfo *TInfo =
7936 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
7937 FunctionProtoTypeLoc ProtoLoc =
7938 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
7939
7940 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
7941 Context, Derived, UsingLoc, NameInfo, DerivedType,
7942 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
7943 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
7944
7945 // Build an unevaluated exception specification for this constructor.
7946 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
7947 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7948 EPI.ExceptionSpecType = EST_Unevaluated;
7949 EPI.ExceptionSpecDecl = DerivedCtor;
7950 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
7951 FPT->getArgTypes(), EPI));
7952
7953 // Build the parameter declarations.
7954 SmallVector<ParmVarDecl *, 16> ParamDecls;
7955 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
7956 TypeSourceInfo *TInfo =
7957 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
7958 ParmVarDecl *PD = ParmVarDecl::Create(
7959 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
7960 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
7961 PD->setScopeInfo(0, I);
7962 PD->setImplicit();
7963 ParamDecls.push_back(PD);
7964 ProtoLoc.setArg(I, PD);
7965 }
7966
7967 // Set up the new constructor.
7968 DerivedCtor->setAccess(BaseCtor->getAccess());
7969 DerivedCtor->setParams(ParamDecls);
7970 DerivedCtor->setInheritedConstructor(BaseCtor);
7971 if (BaseCtor->isDeleted())
7972 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
7973
7974 // If this is a constructor template, build the template declaration.
7975 if (TemplateParams) {
7976 FunctionTemplateDecl *DerivedTemplate =
7977 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
7978 TemplateParams, DerivedCtor);
7979 DerivedTemplate->setAccess(BaseCtor->getAccess());
7980 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
7981 Derived->addDecl(DerivedTemplate);
7982 } else {
7983 Derived->addDecl(DerivedCtor);
7984 }
7985
7986 Entry.BaseCtor = BaseCtor;
7987 Entry.DerivedCtor = DerivedCtor;
7988 }
7989
7990 Sema &SemaRef;
7991 CXXRecordDecl *Derived;
7992 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
7993 MapType Map;
7994};
7995}
7996
7997void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
7998 // Defer declaring the inheriting constructors until the class is
7999 // instantiated.
8000 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008001 return;
8002
Richard Smith4841ca52013-04-10 05:48:59 +00008003 // Find base classes from which we might inherit constructors.
8004 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8005 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8006 BaseE = ClassDecl->bases_end();
8007 BaseIt != BaseE; ++BaseIt)
8008 if (BaseIt->getInheritConstructors())
8009 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008010
Richard Smith4841ca52013-04-10 05:48:59 +00008011 // Go no further if we're not inheriting any constructors.
8012 if (InheritedBases.empty())
8013 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008014
Richard Smith4841ca52013-04-10 05:48:59 +00008015 // Declare the inherited constructors.
8016 InheritingConstructorInfo ICI(*this, ClassDecl);
8017 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8018 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008019}
8020
Richard Smith07b0fdc2013-03-18 21:12:30 +00008021void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8022 CXXConstructorDecl *Constructor) {
8023 CXXRecordDecl *ClassDecl = Constructor->getParent();
8024 assert(Constructor->getInheritedConstructor() &&
8025 !Constructor->doesThisDeclarationHaveABody() &&
8026 !Constructor->isDeleted());
8027
8028 SynthesizedFunctionScope Scope(*this, Constructor);
8029 DiagnosticErrorTrap Trap(Diags);
8030 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8031 Trap.hasErrorOccurred()) {
8032 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8033 << Context.getTagDeclType(ClassDecl);
8034 Constructor->setInvalidDecl();
8035 return;
8036 }
8037
8038 SourceLocation Loc = Constructor->getLocation();
8039 Constructor->setBody(new (Context) CompoundStmt(Loc));
8040
8041 Constructor->setUsed();
8042 MarkVTableUsed(CurrentLocation, ClassDecl);
8043
8044 if (ASTMutationListener *L = getASTMutationListener()) {
8045 L->CompletedImplicitDefinition(Constructor);
8046 }
8047}
8048
8049
Sean Huntcb45a0f2011-05-12 22:46:25 +00008050Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008051Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8052 CXXRecordDecl *ClassDecl = MD->getParent();
8053
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008054 // C++ [except.spec]p14:
8055 // An implicitly declared special member function (Clause 12) shall have
8056 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008057 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008058 if (ClassDecl->isInvalidDecl())
8059 return ExceptSpec;
8060
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008061 // Direct base-class destructors.
8062 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8063 BEnd = ClassDecl->bases_end();
8064 B != BEnd; ++B) {
8065 if (B->isVirtual()) // Handled below.
8066 continue;
8067
8068 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008069 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008070 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008071 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008072
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008073 // Virtual base-class destructors.
8074 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8075 BEnd = ClassDecl->vbases_end();
8076 B != BEnd; ++B) {
8077 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008078 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008079 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008080 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008081
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008082 // Field destructors.
8083 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8084 FEnd = ClassDecl->field_end();
8085 F != FEnd; ++F) {
8086 if (const RecordType *RecordTy
8087 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008088 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008089 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008090 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008091
Sean Huntcb45a0f2011-05-12 22:46:25 +00008092 return ExceptSpec;
8093}
8094
8095CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8096 // C++ [class.dtor]p2:
8097 // If a class has no user-declared destructor, a destructor is
8098 // declared implicitly. An implicitly-declared destructor is an
8099 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008100 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008101
Richard Smithafb49182012-11-29 01:34:07 +00008102 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8103 if (DSM.isAlreadyBeingDeclared())
8104 return 0;
8105
Douglas Gregor4923aa22010-07-02 20:37:36 +00008106 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008107 CanQualType ClassType
8108 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008109 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008110 DeclarationName Name
8111 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008112 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008113 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008114 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8115 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008116 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008117 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008118 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008119 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008120
8121 // Build an exception specification pointing back at this destructor.
8122 FunctionProtoType::ExtProtoInfo EPI;
8123 EPI.ExceptionSpecType = EST_Unevaluated;
8124 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008125 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8126 ArrayRef<QualType>(),
8127 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008128
Richard Smithbc2a35d2012-12-08 08:32:28 +00008129 AddOverriddenMethods(ClassDecl, Destructor);
8130
8131 // We don't need to use SpecialMemberIsTrivial here; triviality for
8132 // destructors is easy to compute.
8133 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8134
8135 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008136 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008137
Douglas Gregor4923aa22010-07-02 20:37:36 +00008138 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008139 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008140
Douglas Gregor4923aa22010-07-02 20:37:36 +00008141 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008142 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008143 PushOnScopeChains(Destructor, S, false);
8144 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008145
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008146 return Destructor;
8147}
8148
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008149void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008150 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008151 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008152 !Destructor->doesThisDeclarationHaveABody() &&
8153 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008154 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008155 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008156 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008157
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008158 if (Destructor->isInvalidDecl())
8159 return;
8160
Eli Friedman9a14db32012-10-18 20:14:08 +00008161 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008162
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008163 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008164 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8165 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008166
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008167 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008168 Diag(CurrentLocation, diag::note_member_synthesized_at)
8169 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8170
8171 Destructor->setInvalidDecl();
8172 return;
8173 }
8174
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008175 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008176 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008177 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008178 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008179 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008180
8181 if (ASTMutationListener *L = getASTMutationListener()) {
8182 L->CompletedImplicitDefinition(Destructor);
8183 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008184}
8185
Richard Smitha4156b82012-04-21 18:42:51 +00008186/// \brief Perform any semantic analysis which needs to be delayed until all
8187/// pending class member declarations have been parsed.
8188void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008189 // If the context is an invalid C++ class, just suppress these checks.
8190 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8191 if (Record->isInvalidDecl()) {
8192 DelayedDestructorExceptionSpecChecks.clear();
8193 return;
8194 }
8195 }
8196
Richard Smitha4156b82012-04-21 18:42:51 +00008197 // Perform any deferred checking of exception specifications for virtual
8198 // destructors.
8199 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8200 i != e; ++i) {
8201 const CXXDestructorDecl *Dtor =
8202 DelayedDestructorExceptionSpecChecks[i].first;
8203 assert(!Dtor->getParent()->isDependentType() &&
8204 "Should not ever add destructors of templates into the list.");
8205 CheckOverridingFunctionExceptionSpec(Dtor,
8206 DelayedDestructorExceptionSpecChecks[i].second);
8207 }
8208 DelayedDestructorExceptionSpecChecks.clear();
8209}
8210
Richard Smithb9d0b762012-07-27 04:22:15 +00008211void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8212 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008213 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008214 "adjusting dtor exception specs was introduced in c++11");
8215
Sebastian Redl0ee33912011-05-19 05:13:44 +00008216 // C++11 [class.dtor]p3:
8217 // A declaration of a destructor that does not have an exception-
8218 // specification is implicitly considered to have the same exception-
8219 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008220 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008221 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008222 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008223 return;
8224
Chandler Carruth3f224b22011-09-20 04:55:26 +00008225 // Replace the destructor's type, building off the existing one. Fortunately,
8226 // the only thing of interest in the destructor type is its extended info.
8227 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008228 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8229 EPI.ExceptionSpecType = EST_Unevaluated;
8230 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008231 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8232 ArrayRef<QualType>(),
8233 EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008234
Sebastian Redl0ee33912011-05-19 05:13:44 +00008235 // FIXME: If the destructor has a body that could throw, and the newly created
8236 // spec doesn't allow exceptions, we should emit a warning, because this
8237 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008238 // However, we don't have a body or an exception specification yet, so it
8239 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008240}
8241
Richard Smith8c889532012-11-14 00:50:40 +00008242/// When generating a defaulted copy or move assignment operator, if a field
8243/// should be copied with __builtin_memcpy rather than via explicit assignments,
8244/// do so. This optimization only applies for arrays of scalars, and for arrays
8245/// of class type where the selected copy/move-assignment operator is trivial.
8246static StmtResult
8247buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8248 Expr *To, Expr *From) {
8249 // Compute the size of the memory buffer to be copied.
8250 QualType SizeType = S.Context.getSizeType();
8251 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8252 S.Context.getTypeSizeInChars(T).getQuantity());
8253
8254 // Take the address of the field references for "from" and "to". We
8255 // directly construct UnaryOperators here because semantic analysis
8256 // does not permit us to take the address of an xvalue.
8257 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8258 S.Context.getPointerType(From->getType()),
8259 VK_RValue, OK_Ordinary, Loc);
8260 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8261 S.Context.getPointerType(To->getType()),
8262 VK_RValue, OK_Ordinary, Loc);
8263
8264 const Type *E = T->getBaseElementTypeUnsafe();
8265 bool NeedsCollectableMemCpy =
8266 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8267
8268 // Create a reference to the __builtin_objc_memmove_collectable function
8269 StringRef MemCpyName = NeedsCollectableMemCpy ?
8270 "__builtin_objc_memmove_collectable" :
8271 "__builtin_memcpy";
8272 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8273 Sema::LookupOrdinaryName);
8274 S.LookupName(R, S.TUScope, true);
8275
8276 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8277 if (!MemCpy)
8278 // Something went horribly wrong earlier, and we will have complained
8279 // about it.
8280 return StmtError();
8281
8282 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8283 VK_RValue, Loc, 0);
8284 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8285
8286 Expr *CallArgs[] = {
8287 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8288 };
8289 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8290 Loc, CallArgs, Loc);
8291
8292 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8293 return S.Owned(Call.takeAs<Stmt>());
8294}
8295
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008296/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008297/// \c To.
8298///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008299/// This routine is used to copy/move the members of a class with an
8300/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008301/// copied are arrays, this routine builds for loops to copy them.
8302///
8303/// \param S The Sema object used for type-checking.
8304///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008305/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008306///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008307/// \param T The type of the expressions being copied/moved. Both expressions
8308/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008309///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008310/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008311///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008312/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008313///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008314/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008315/// Otherwise, it's a non-static member subobject.
8316///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008317/// \param Copying Whether we're copying or moving.
8318///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008319/// \param Depth Internal parameter recording the depth of the recursion.
8320///
Richard Smith8c889532012-11-14 00:50:40 +00008321/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8322/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008323static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008324buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8325 Expr *To, Expr *From,
8326 bool CopyingBaseSubobject, bool Copying,
8327 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008328 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008329 // Each subobject is assigned in the manner appropriate to its type:
8330 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008331 // - if the subobject is of class type, as if by a call to operator= with
8332 // the subobject as the object expression and the corresponding
8333 // subobject of x as a single function argument (as if by explicit
8334 // qualification; that is, ignoring any possible virtual overriding
8335 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008336 //
8337 // C++03 [class.copy]p13:
8338 // - if the subobject is of class type, the copy assignment operator for
8339 // the class is used (as if by explicit qualification; that is,
8340 // ignoring any possible virtual overriding functions in more derived
8341 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008342 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8343 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008344
Douglas Gregor06a9f362010-05-01 20:49:11 +00008345 // Look for operator=.
8346 DeclarationName Name
8347 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8348 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8349 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008350
Richard Smith044c8aa2012-11-13 00:54:12 +00008351 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8352 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008353 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008354 LookupResult::Filter F = OpLookup.makeFilter();
8355 while (F.hasNext()) {
8356 NamedDecl *D = F.next();
8357 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8358 if (Method->isCopyAssignmentOperator() ||
8359 (!Copying && Method->isMoveAssignmentOperator()))
8360 continue;
8361
8362 F.erase();
8363 }
8364 F.done();
John McCallb0207482010-03-16 06:11:48 +00008365 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008366
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008367 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008368 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008369 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008370 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008371 // ambiguities), we need to cast "this" to that subobject type; to
8372 // ensure that we don't go through the virtual call mechanism, we need
8373 // to qualify the operator= name with the base class (see below). However,
8374 // this means that if the base class has a protected copy assignment
8375 // operator, the protected member access check will fail. So, we
8376 // rewrite "protected" access to "public" access in this case, since we
8377 // know by construction that we're calling from a derived class.
8378 if (CopyingBaseSubobject) {
8379 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8380 L != LEnd; ++L) {
8381 if (L.getAccess() == AS_protected)
8382 L.setAccess(AS_public);
8383 }
8384 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008385
Douglas Gregor06a9f362010-05-01 20:49:11 +00008386 // Create the nested-name-specifier that will be used to qualify the
8387 // reference to operator=; this is required to suppress the virtual
8388 // call mechanism.
8389 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008390 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008391 SS.MakeTrivial(S.Context,
8392 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008393 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008394 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008395
Douglas Gregor06a9f362010-05-01 20:49:11 +00008396 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008397 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008398 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008399 /*TemplateKWLoc=*/SourceLocation(),
8400 /*FirstQualifierInScope=*/0,
8401 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008402 /*TemplateArgs=*/0,
8403 /*SuppressQualifierCheck=*/true);
8404 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008405 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008406
Douglas Gregor06a9f362010-05-01 20:49:11 +00008407 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008408
Richard Smith044c8aa2012-11-13 00:54:12 +00008409 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008410 OpEqualRef.takeAs<Expr>(),
8411 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008412 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008413 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008414
Richard Smith8c889532012-11-14 00:50:40 +00008415 // If we built a call to a trivial 'operator=' while copying an array,
8416 // bail out. We'll replace the whole shebang with a memcpy.
8417 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8418 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8419 return StmtResult((Stmt*)0);
8420
Richard Smith044c8aa2012-11-13 00:54:12 +00008421 // Convert to an expression-statement, and clean up any produced
8422 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008423 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008424 }
John McCallb0207482010-03-16 06:11:48 +00008425
Richard Smith044c8aa2012-11-13 00:54:12 +00008426 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008427 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008428 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008429 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008430 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008431 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008432 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008433 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008434 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008435
8436 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008437 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008438
Douglas Gregor06a9f362010-05-01 20:49:11 +00008439 // Construct a loop over the array bounds, e.g.,
8440 //
8441 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8442 //
8443 // that will copy each of the array elements.
8444 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008445
Douglas Gregor06a9f362010-05-01 20:49:11 +00008446 // Create the iteration variable.
8447 IdentifierInfo *IterationVarName = 0;
8448 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008449 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008450 llvm::raw_svector_ostream OS(Str);
8451 OS << "__i" << Depth;
8452 IterationVarName = &S.Context.Idents.get(OS.str());
8453 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008454 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008455 IterationVarName, SizeType,
8456 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008457 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008458
Douglas Gregor06a9f362010-05-01 20:49:11 +00008459 // Initialize the iteration variable to zero.
8460 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008461 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008462
8463 // Create a reference to the iteration variable; we'll use this several
8464 // times throughout.
8465 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008466 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008467 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008468 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8469 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8470
Douglas Gregor06a9f362010-05-01 20:49:11 +00008471 // Create the DeclStmt that holds the iteration variable.
8472 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008473
Douglas Gregor06a9f362010-05-01 20:49:11 +00008474 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008475 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008476 IterationVarRefRVal,
8477 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008478 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008479 IterationVarRefRVal,
8480 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008481 if (!Copying) // Cast to rvalue
8482 From = CastForMoving(S, From);
8483
8484 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008485 StmtResult Copy =
8486 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8487 To, From, CopyingBaseSubobject,
8488 Copying, Depth + 1);
8489 // Bail out if copying fails or if we determined that we should use memcpy.
8490 if (Copy.isInvalid() || !Copy.get())
8491 return Copy;
8492
8493 // Create the comparison against the array bound.
8494 llvm::APInt Upper
8495 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8496 Expr *Comparison
8497 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8498 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8499 BO_NE, S.Context.BoolTy,
8500 VK_RValue, OK_Ordinary, Loc, false);
8501
8502 // Create the pre-increment of the iteration variable.
8503 Expr *Increment
8504 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8505 VK_LValue, OK_Ordinary, Loc);
8506
Douglas Gregor06a9f362010-05-01 20:49:11 +00008507 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008508 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008509 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008510 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008511 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008512}
8513
Richard Smith8c889532012-11-14 00:50:40 +00008514static StmtResult
8515buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8516 Expr *To, Expr *From,
8517 bool CopyingBaseSubobject, bool Copying) {
8518 // Maybe we should use a memcpy?
8519 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8520 T.isTriviallyCopyableType(S.Context))
8521 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8522
8523 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8524 CopyingBaseSubobject,
8525 Copying, 0));
8526
8527 // If we ended up picking a trivial assignment operator for an array of a
8528 // non-trivially-copyable class type, just emit a memcpy.
8529 if (!Result.isInvalid() && !Result.get())
8530 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8531
8532 return Result;
8533}
8534
Richard Smithb9d0b762012-07-27 04:22:15 +00008535Sema::ImplicitExceptionSpecification
8536Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8537 CXXRecordDecl *ClassDecl = MD->getParent();
8538
8539 ImplicitExceptionSpecification ExceptSpec(*this);
8540 if (ClassDecl->isInvalidDecl())
8541 return ExceptSpec;
8542
8543 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8544 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8545 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8546
Douglas Gregorb87786f2010-07-01 17:48:08 +00008547 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008548 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008549 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008550
8551 // It is unspecified whether or not an implicit copy assignment operator
8552 // attempts to deduplicate calls to assignment operators of virtual bases are
8553 // made. As such, this exception specification is effectively unspecified.
8554 // Based on a similar decision made for constness in C++0x, we're erring on
8555 // the side of assuming such calls to be made regardless of whether they
8556 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008557 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8558 BaseEnd = ClassDecl->bases_end();
8559 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008560 if (Base->isVirtual())
8561 continue;
8562
Douglas Gregora376d102010-07-02 21:50:04 +00008563 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008564 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008565 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8566 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008567 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008568 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008569
8570 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8571 BaseEnd = ClassDecl->vbases_end();
8572 Base != BaseEnd; ++Base) {
8573 CXXRecordDecl *BaseClassDecl
8574 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8575 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8576 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008577 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008578 }
8579
Douglas Gregorb87786f2010-07-01 17:48:08 +00008580 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8581 FieldEnd = ClassDecl->field_end();
8582 Field != FieldEnd;
8583 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008584 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008585 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8586 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008587 LookupCopyingAssignment(FieldClassDecl,
8588 ArgQuals | FieldType.getCVRQualifiers(),
8589 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008590 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008591 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008592 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008593
Richard Smithb9d0b762012-07-27 04:22:15 +00008594 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008595}
8596
8597CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8598 // Note: The following rules are largely analoguous to the copy
8599 // constructor rules. Note that virtual bases are not taken into account
8600 // for determining the argument type of the operator. Note also that
8601 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008602 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008603
Richard Smithafb49182012-11-29 01:34:07 +00008604 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8605 if (DSM.isAlreadyBeingDeclared())
8606 return 0;
8607
Sean Hunt30de05c2011-05-14 05:23:20 +00008608 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8609 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008610 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008611 ArgType = ArgType.withConst();
8612 ArgType = Context.getLValueReferenceType(ArgType);
8613
Douglas Gregord3c35902010-07-01 16:36:15 +00008614 // An implicitly-declared copy assignment operator is an inline public
8615 // member of its class.
8616 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008617 SourceLocation ClassLoc = ClassDecl->getLocation();
8618 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008619 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008620 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008621 /*TInfo=*/0,
8622 /*StorageClass=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008623 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008624 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008625 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008626 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008627 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008628
8629 // Build an exception specification pointing back at this member.
8630 FunctionProtoType::ExtProtoInfo EPI;
8631 EPI.ExceptionSpecType = EST_Unevaluated;
8632 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008633 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008634
Douglas Gregord3c35902010-07-01 16:36:15 +00008635 // Add the parameter to the operator.
8636 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008637 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008638 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008639 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008640 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008641
Richard Smithbc2a35d2012-12-08 08:32:28 +00008642 AddOverriddenMethods(ClassDecl, CopyAssignment);
8643
8644 CopyAssignment->setTrivial(
8645 ClassDecl->needsOverloadResolutionForCopyAssignment()
8646 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8647 : ClassDecl->hasTrivialCopyAssignment());
8648
Nico Weberafcc96a2012-01-23 03:19:29 +00008649 // C++0x [class.copy]p19:
8650 // .... If the class definition does not explicitly declare a copy
8651 // assignment operator, there is no user-declared move constructor, and
8652 // there is no user-declared move assignment operator, a copy assignment
8653 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008654 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008655 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008656
Richard Smithbc2a35d2012-12-08 08:32:28 +00008657 // Note that we have added this copy-assignment operator.
8658 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8659
8660 if (Scope *S = getScopeForContext(ClassDecl))
8661 PushOnScopeChains(CopyAssignment, S, false);
8662 ClassDecl->addDecl(CopyAssignment);
8663
Douglas Gregord3c35902010-07-01 16:36:15 +00008664 return CopyAssignment;
8665}
8666
Douglas Gregor06a9f362010-05-01 20:49:11 +00008667void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8668 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008669 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008670 CopyAssignOperator->isOverloadedOperator() &&
8671 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008672 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8673 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008674 "DefineImplicitCopyAssignment called for wrong function");
8675
8676 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8677
8678 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8679 CopyAssignOperator->setInvalidDecl();
8680 return;
8681 }
8682
8683 CopyAssignOperator->setUsed();
8684
Eli Friedman9a14db32012-10-18 20:14:08 +00008685 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008686 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008687
8688 // C++0x [class.copy]p30:
8689 // The implicitly-defined or explicitly-defaulted copy assignment operator
8690 // for a non-union class X performs memberwise copy assignment of its
8691 // subobjects. The direct base classes of X are assigned first, in the
8692 // order of their declaration in the base-specifier-list, and then the
8693 // immediate non-static data members of X are assigned, in the order in
8694 // which they were declared in the class definition.
8695
8696 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008697 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008698
8699 // The parameter for the "other" object, which we are copying from.
8700 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8701 Qualifiers OtherQuals = Other->getType().getQualifiers();
8702 QualType OtherRefType = Other->getType();
8703 if (const LValueReferenceType *OtherRef
8704 = OtherRefType->getAs<LValueReferenceType>()) {
8705 OtherRefType = OtherRef->getPointeeType();
8706 OtherQuals = OtherRefType.getQualifiers();
8707 }
8708
8709 // Our location for everything implicitly-generated.
8710 SourceLocation Loc = CopyAssignOperator->getLocation();
8711
8712 // Construct a reference to the "other" object. We'll be using this
8713 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008714 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008715 assert(OtherRef && "Reference to parameter cannot fail!");
8716
8717 // Construct the "this" pointer. We'll be using this throughout the generated
8718 // ASTs.
8719 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8720 assert(This && "Reference to this cannot fail!");
8721
8722 // Assign base classes.
8723 bool Invalid = false;
8724 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8725 E = ClassDecl->bases_end(); Base != E; ++Base) {
8726 // Form the assignment:
8727 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8728 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008729 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008730 Invalid = true;
8731 continue;
8732 }
8733
John McCallf871d0c2010-08-07 06:22:56 +00008734 CXXCastPath BasePath;
8735 BasePath.push_back(Base);
8736
Douglas Gregor06a9f362010-05-01 20:49:11 +00008737 // Construct the "from" expression, which is an implicit cast to the
8738 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008739 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008740 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8741 CK_UncheckedDerivedToBase,
8742 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008743
8744 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008745 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008746
8747 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008748 To = ImpCastExprToType(To.take(),
8749 Context.getCVRQualifiedType(BaseType,
8750 CopyAssignOperator->getTypeQualifiers()),
8751 CK_UncheckedDerivedToBase,
8752 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008753
8754 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008755 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008756 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008757 /*CopyingBaseSubobject=*/true,
8758 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008759 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008760 Diag(CurrentLocation, diag::note_member_synthesized_at)
8761 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8762 CopyAssignOperator->setInvalidDecl();
8763 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008764 }
8765
8766 // Success! Record the copy.
8767 Statements.push_back(Copy.takeAs<Expr>());
8768 }
8769
Douglas Gregor06a9f362010-05-01 20:49:11 +00008770 // Assign non-static members.
8771 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8772 FieldEnd = ClassDecl->field_end();
8773 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008774 if (Field->isUnnamedBitfield())
8775 continue;
8776
Douglas Gregor06a9f362010-05-01 20:49:11 +00008777 // Check for members of reference type; we can't copy those.
8778 if (Field->getType()->isReferenceType()) {
8779 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8780 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8781 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008782 Diag(CurrentLocation, diag::note_member_synthesized_at)
8783 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008784 Invalid = true;
8785 continue;
8786 }
8787
8788 // Check for members of const-qualified, non-class type.
8789 QualType BaseType = Context.getBaseElementType(Field->getType());
8790 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8791 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8792 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8793 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008794 Diag(CurrentLocation, diag::note_member_synthesized_at)
8795 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008796 Invalid = true;
8797 continue;
8798 }
John McCallb77115d2011-06-17 00:18:42 +00008799
8800 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008801 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8802 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008803
8804 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008805 if (FieldType->isIncompleteArrayType()) {
8806 assert(ClassDecl->hasFlexibleArrayMember() &&
8807 "Incomplete array type is not valid");
8808 continue;
8809 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008810
8811 // Build references to the field in the object we're copying from and to.
8812 CXXScopeSpec SS; // Intentionally empty
8813 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8814 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008815 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008816 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008817 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008818 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008819 SS, SourceLocation(), 0,
8820 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008821 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008822 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008823 SS, SourceLocation(), 0,
8824 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008825 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8826 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008827
Douglas Gregor06a9f362010-05-01 20:49:11 +00008828 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008829 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008830 To.get(), From.get(),
8831 /*CopyingBaseSubobject=*/false,
8832 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008833 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008834 Diag(CurrentLocation, diag::note_member_synthesized_at)
8835 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8836 CopyAssignOperator->setInvalidDecl();
8837 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008838 }
8839
8840 // Success! Record the copy.
8841 Statements.push_back(Copy.takeAs<Stmt>());
8842 }
8843
8844 if (!Invalid) {
8845 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008846 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008847
John McCall60d7b3a2010-08-24 06:29:42 +00008848 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008849 if (Return.isInvalid())
8850 Invalid = true;
8851 else {
8852 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008853
8854 if (Trap.hasErrorOccurred()) {
8855 Diag(CurrentLocation, diag::note_member_synthesized_at)
8856 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8857 Invalid = true;
8858 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008859 }
8860 }
8861
8862 if (Invalid) {
8863 CopyAssignOperator->setInvalidDecl();
8864 return;
8865 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008866
8867 StmtResult Body;
8868 {
8869 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008870 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008871 /*isStmtExpr=*/false);
8872 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8873 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008874 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008875
8876 if (ASTMutationListener *L = getASTMutationListener()) {
8877 L->CompletedImplicitDefinition(CopyAssignOperator);
8878 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008879}
8880
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008881Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008882Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8883 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008884
Richard Smithb9d0b762012-07-27 04:22:15 +00008885 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008886 if (ClassDecl->isInvalidDecl())
8887 return ExceptSpec;
8888
8889 // C++0x [except.spec]p14:
8890 // An implicitly declared special member function (Clause 12) shall have an
8891 // exception-specification. [...]
8892
8893 // It is unspecified whether or not an implicit move assignment operator
8894 // attempts to deduplicate calls to assignment operators of virtual bases are
8895 // made. As such, this exception specification is effectively unspecified.
8896 // Based on a similar decision made for constness in C++0x, we're erring on
8897 // the side of assuming such calls to be made regardless of whether they
8898 // actually happen.
8899 // Note that a move constructor is not implicitly declared when there are
8900 // virtual bases, but it can still be user-declared and explicitly defaulted.
8901 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8902 BaseEnd = ClassDecl->bases_end();
8903 Base != BaseEnd; ++Base) {
8904 if (Base->isVirtual())
8905 continue;
8906
8907 CXXRecordDecl *BaseClassDecl
8908 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8909 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008910 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008911 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008912 }
8913
8914 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8915 BaseEnd = ClassDecl->vbases_end();
8916 Base != BaseEnd; ++Base) {
8917 CXXRecordDecl *BaseClassDecl
8918 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8919 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008920 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008921 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008922 }
8923
8924 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8925 FieldEnd = ClassDecl->field_end();
8926 Field != FieldEnd;
8927 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008928 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008929 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008930 if (CXXMethodDecl *MoveAssign =
8931 LookupMovingAssignment(FieldClassDecl,
8932 FieldType.getCVRQualifiers(),
8933 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008934 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008935 }
8936 }
8937
8938 return ExceptSpec;
8939}
8940
Richard Smith1c931be2012-04-02 18:40:40 +00008941/// Determine whether the class type has any direct or indirect virtual base
8942/// classes which have a non-trivial move assignment operator.
8943static bool
8944hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8945 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8946 BaseEnd = ClassDecl->vbases_end();
8947 Base != BaseEnd; ++Base) {
8948 CXXRecordDecl *BaseClass =
8949 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8950
8951 // Try to declare the move assignment. If it would be deleted, then the
8952 // class does not have a non-trivial move assignment.
8953 if (BaseClass->needsImplicitMoveAssignment())
8954 S.DeclareImplicitMoveAssignment(BaseClass);
8955
Richard Smith426391c2012-11-16 00:53:38 +00008956 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008957 return true;
8958 }
8959
8960 return false;
8961}
8962
8963/// Determine whether the given type either has a move constructor or is
8964/// trivially copyable.
8965static bool
8966hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8967 Type = S.Context.getBaseElementType(Type);
8968
8969 // FIXME: Technically, non-trivially-copyable non-class types, such as
8970 // reference types, are supposed to return false here, but that appears
8971 // to be a standard defect.
8972 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008973 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008974 return true;
8975
8976 if (Type.isTriviallyCopyableType(S.Context))
8977 return true;
8978
8979 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008980 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8981 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008982 if (ClassDecl->needsImplicitMoveConstructor())
8983 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008984 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008985 }
8986
Richard Smithe5411b72012-12-01 02:35:44 +00008987 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8988 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008989 if (ClassDecl->needsImplicitMoveAssignment())
8990 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008991 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008992}
8993
8994/// Determine whether all non-static data members and direct or virtual bases
8995/// of class \p ClassDecl have either a move operation, or are trivially
8996/// copyable.
8997static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8998 bool IsConstructor) {
8999 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9000 BaseEnd = ClassDecl->bases_end();
9001 Base != BaseEnd; ++Base) {
9002 if (Base->isVirtual())
9003 continue;
9004
9005 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9006 return false;
9007 }
9008
9009 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9010 BaseEnd = ClassDecl->vbases_end();
9011 Base != BaseEnd; ++Base) {
9012 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9013 return false;
9014 }
9015
9016 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9017 FieldEnd = ClassDecl->field_end();
9018 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009019 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009020 return false;
9021 }
9022
9023 return true;
9024}
9025
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009026CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009027 // C++11 [class.copy]p20:
9028 // If the definition of a class X does not explicitly declare a move
9029 // assignment operator, one will be implicitly declared as defaulted
9030 // if and only if:
9031 //
9032 // - [first 4 bullets]
9033 assert(ClassDecl->needsImplicitMoveAssignment());
9034
Richard Smithafb49182012-11-29 01:34:07 +00009035 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9036 if (DSM.isAlreadyBeingDeclared())
9037 return 0;
9038
Richard Smith1c931be2012-04-02 18:40:40 +00009039 // [Checked after we build the declaration]
9040 // - the move assignment operator would not be implicitly defined as
9041 // deleted,
9042
9043 // [DR1402]:
9044 // - X has no direct or indirect virtual base class with a non-trivial
9045 // move assignment operator, and
9046 // - each of X's non-static data members and direct or virtual base classes
9047 // has a type that either has a move assignment operator or is trivially
9048 // copyable.
9049 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9050 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9051 ClassDecl->setFailedImplicitMoveAssignment();
9052 return 0;
9053 }
9054
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009055 // Note: The following rules are largely analoguous to the move
9056 // constructor rules.
9057
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009058 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9059 QualType RetType = Context.getLValueReferenceType(ArgType);
9060 ArgType = Context.getRValueReferenceType(ArgType);
9061
9062 // An implicitly-declared move assignment operator is an inline public
9063 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009064 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9065 SourceLocation ClassLoc = ClassDecl->getLocation();
9066 DeclarationNameInfo NameInfo(Name, ClassLoc);
9067 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00009068 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009069 /*TInfo=*/0,
9070 /*StorageClass=*/SC_None,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009071 /*isInline=*/true,
9072 /*isConstexpr=*/false,
9073 SourceLocation());
9074 MoveAssignment->setAccess(AS_public);
9075 MoveAssignment->setDefaulted();
9076 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009077
Richard Smithb9d0b762012-07-27 04:22:15 +00009078 // Build an exception specification pointing back at this member.
9079 FunctionProtoType::ExtProtoInfo EPI;
9080 EPI.ExceptionSpecType = EST_Unevaluated;
9081 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009082 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009083
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009084 // Add the parameter to the operator.
9085 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9086 ClassLoc, ClassLoc, /*Id=*/0,
9087 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009088 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009089 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009090
Richard Smithbc2a35d2012-12-08 08:32:28 +00009091 AddOverriddenMethods(ClassDecl, MoveAssignment);
9092
9093 MoveAssignment->setTrivial(
9094 ClassDecl->needsOverloadResolutionForMoveAssignment()
9095 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9096 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009097
9098 // C++0x [class.copy]p9:
9099 // If the definition of a class X does not explicitly declare a move
9100 // assignment operator, one will be implicitly declared as defaulted if and
9101 // only if:
9102 // [...]
9103 // - the move assignment operator would not be implicitly defined as
9104 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009105 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009106 // Cache this result so that we don't try to generate this over and over
9107 // on every lookup, leaking memory and wasting time.
9108 ClassDecl->setFailedImplicitMoveAssignment();
9109 return 0;
9110 }
9111
Richard Smithbc2a35d2012-12-08 08:32:28 +00009112 // Note that we have added this copy-assignment operator.
9113 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9114
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009115 if (Scope *S = getScopeForContext(ClassDecl))
9116 PushOnScopeChains(MoveAssignment, S, false);
9117 ClassDecl->addDecl(MoveAssignment);
9118
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009119 return MoveAssignment;
9120}
9121
9122void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9123 CXXMethodDecl *MoveAssignOperator) {
9124 assert((MoveAssignOperator->isDefaulted() &&
9125 MoveAssignOperator->isOverloadedOperator() &&
9126 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009127 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9128 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009129 "DefineImplicitMoveAssignment called for wrong function");
9130
9131 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9132
9133 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9134 MoveAssignOperator->setInvalidDecl();
9135 return;
9136 }
9137
9138 MoveAssignOperator->setUsed();
9139
Eli Friedman9a14db32012-10-18 20:14:08 +00009140 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009141 DiagnosticErrorTrap Trap(Diags);
9142
9143 // C++0x [class.copy]p28:
9144 // The implicitly-defined or move assignment operator for a non-union class
9145 // X performs memberwise move assignment of its subobjects. The direct base
9146 // classes of X are assigned first, in the order of their declaration in the
9147 // base-specifier-list, and then the immediate non-static data members of X
9148 // are assigned, in the order in which they were declared in the class
9149 // definition.
9150
9151 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009152 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009153
9154 // The parameter for the "other" object, which we are move from.
9155 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9156 QualType OtherRefType = Other->getType()->
9157 getAs<RValueReferenceType>()->getPointeeType();
9158 assert(OtherRefType.getQualifiers() == 0 &&
9159 "Bad argument type of defaulted move assignment");
9160
9161 // Our location for everything implicitly-generated.
9162 SourceLocation Loc = MoveAssignOperator->getLocation();
9163
9164 // Construct a reference to the "other" object. We'll be using this
9165 // throughout the generated ASTs.
9166 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9167 assert(OtherRef && "Reference to parameter cannot fail!");
9168 // Cast to rvalue.
9169 OtherRef = CastForMoving(*this, OtherRef);
9170
9171 // Construct the "this" pointer. We'll be using this throughout the generated
9172 // ASTs.
9173 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9174 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009175
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009176 // Assign base classes.
9177 bool Invalid = false;
9178 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9179 E = ClassDecl->bases_end(); Base != E; ++Base) {
9180 // Form the assignment:
9181 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9182 QualType BaseType = Base->getType().getUnqualifiedType();
9183 if (!BaseType->isRecordType()) {
9184 Invalid = true;
9185 continue;
9186 }
9187
9188 CXXCastPath BasePath;
9189 BasePath.push_back(Base);
9190
9191 // Construct the "from" expression, which is an implicit cast to the
9192 // appropriately-qualified base type.
9193 Expr *From = OtherRef;
9194 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009195 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009196
9197 // Dereference "this".
9198 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9199
9200 // Implicitly cast "this" to the appropriately-qualified base type.
9201 To = ImpCastExprToType(To.take(),
9202 Context.getCVRQualifiedType(BaseType,
9203 MoveAssignOperator->getTypeQualifiers()),
9204 CK_UncheckedDerivedToBase,
9205 VK_LValue, &BasePath);
9206
9207 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009208 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009209 To.get(), From,
9210 /*CopyingBaseSubobject=*/true,
9211 /*Copying=*/false);
9212 if (Move.isInvalid()) {
9213 Diag(CurrentLocation, diag::note_member_synthesized_at)
9214 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9215 MoveAssignOperator->setInvalidDecl();
9216 return;
9217 }
9218
9219 // Success! Record the move.
9220 Statements.push_back(Move.takeAs<Expr>());
9221 }
9222
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009223 // Assign non-static members.
9224 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9225 FieldEnd = ClassDecl->field_end();
9226 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009227 if (Field->isUnnamedBitfield())
9228 continue;
9229
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009230 // Check for members of reference type; we can't move those.
9231 if (Field->getType()->isReferenceType()) {
9232 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9233 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9234 Diag(Field->getLocation(), diag::note_declared_at);
9235 Diag(CurrentLocation, diag::note_member_synthesized_at)
9236 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9237 Invalid = true;
9238 continue;
9239 }
9240
9241 // Check for members of const-qualified, non-class type.
9242 QualType BaseType = Context.getBaseElementType(Field->getType());
9243 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9244 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9245 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9246 Diag(Field->getLocation(), diag::note_declared_at);
9247 Diag(CurrentLocation, diag::note_member_synthesized_at)
9248 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9249 Invalid = true;
9250 continue;
9251 }
9252
9253 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009254 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9255 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009256
9257 QualType FieldType = Field->getType().getNonReferenceType();
9258 if (FieldType->isIncompleteArrayType()) {
9259 assert(ClassDecl->hasFlexibleArrayMember() &&
9260 "Incomplete array type is not valid");
9261 continue;
9262 }
9263
9264 // Build references to the field in the object we're copying from and to.
9265 CXXScopeSpec SS; // Intentionally empty
9266 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9267 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009268 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009269 MemberLookup.resolveKind();
9270 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9271 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009272 SS, SourceLocation(), 0,
9273 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009274 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9275 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009276 SS, SourceLocation(), 0,
9277 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009278 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9279 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9280
9281 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9282 "Member reference with rvalue base must be rvalue except for reference "
9283 "members, which aren't allowed for move assignment.");
9284
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009285 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009286 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009287 To.get(), From.get(),
9288 /*CopyingBaseSubobject=*/false,
9289 /*Copying=*/false);
9290 if (Move.isInvalid()) {
9291 Diag(CurrentLocation, diag::note_member_synthesized_at)
9292 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9293 MoveAssignOperator->setInvalidDecl();
9294 return;
9295 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009296
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009297 // Success! Record the copy.
9298 Statements.push_back(Move.takeAs<Stmt>());
9299 }
9300
9301 if (!Invalid) {
9302 // Add a "return *this;"
9303 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9304
9305 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9306 if (Return.isInvalid())
9307 Invalid = true;
9308 else {
9309 Statements.push_back(Return.takeAs<Stmt>());
9310
9311 if (Trap.hasErrorOccurred()) {
9312 Diag(CurrentLocation, diag::note_member_synthesized_at)
9313 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9314 Invalid = true;
9315 }
9316 }
9317 }
9318
9319 if (Invalid) {
9320 MoveAssignOperator->setInvalidDecl();
9321 return;
9322 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009323
9324 StmtResult Body;
9325 {
9326 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009327 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009328 /*isStmtExpr=*/false);
9329 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9330 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009331 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9332
9333 if (ASTMutationListener *L = getASTMutationListener()) {
9334 L->CompletedImplicitDefinition(MoveAssignOperator);
9335 }
9336}
9337
Richard Smithb9d0b762012-07-27 04:22:15 +00009338Sema::ImplicitExceptionSpecification
9339Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9340 CXXRecordDecl *ClassDecl = MD->getParent();
9341
9342 ImplicitExceptionSpecification ExceptSpec(*this);
9343 if (ClassDecl->isInvalidDecl())
9344 return ExceptSpec;
9345
9346 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9347 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9348 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9349
Douglas Gregor0d405db2010-07-01 20:59:04 +00009350 // C++ [except.spec]p14:
9351 // An implicitly declared special member function (Clause 12) shall have an
9352 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009353 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9354 BaseEnd = ClassDecl->bases_end();
9355 Base != BaseEnd;
9356 ++Base) {
9357 // Virtual bases are handled below.
9358 if (Base->isVirtual())
9359 continue;
9360
Douglas Gregor22584312010-07-02 23:41:54 +00009361 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009362 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009363 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009364 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009365 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009366 }
9367 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9368 BaseEnd = ClassDecl->vbases_end();
9369 Base != BaseEnd;
9370 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009371 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009372 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009373 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009374 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009375 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009376 }
9377 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9378 FieldEnd = ClassDecl->field_end();
9379 Field != FieldEnd;
9380 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009381 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009382 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9383 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009384 LookupCopyingConstructor(FieldClassDecl,
9385 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009386 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009387 }
9388 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009389
Richard Smithb9d0b762012-07-27 04:22:15 +00009390 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009391}
9392
9393CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9394 CXXRecordDecl *ClassDecl) {
9395 // C++ [class.copy]p4:
9396 // If the class definition does not explicitly declare a copy
9397 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009398 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009399
Richard Smithafb49182012-11-29 01:34:07 +00009400 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9401 if (DSM.isAlreadyBeingDeclared())
9402 return 0;
9403
Sean Hunt49634cf2011-05-13 06:10:58 +00009404 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9405 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009406 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009407 if (Const)
9408 ArgType = ArgType.withConst();
9409 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009410
Richard Smith7756afa2012-06-10 05:43:50 +00009411 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9412 CXXCopyConstructor,
9413 Const);
9414
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009415 DeclarationName Name
9416 = Context.DeclarationNames.getCXXConstructorName(
9417 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009418 SourceLocation ClassLoc = ClassDecl->getLocation();
9419 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009420
9421 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009422 // member of its class.
9423 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009424 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009425 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009426 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009427 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009428 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009429
Richard Smithb9d0b762012-07-27 04:22:15 +00009430 // Build an exception specification pointing back at this member.
9431 FunctionProtoType::ExtProtoInfo EPI;
9432 EPI.ExceptionSpecType = EST_Unevaluated;
9433 EPI.ExceptionSpecDecl = CopyConstructor;
9434 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009435 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009436
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009437 // Add the parameter to the constructor.
9438 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009439 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009440 /*IdentifierInfo=*/0,
9441 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009442 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009443 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009444
Richard Smithbc2a35d2012-12-08 08:32:28 +00009445 CopyConstructor->setTrivial(
9446 ClassDecl->needsOverloadResolutionForCopyConstructor()
9447 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9448 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009449
Nico Weberafcc96a2012-01-23 03:19:29 +00009450 // C++11 [class.copy]p8:
9451 // ... If the class definition does not explicitly declare a copy
9452 // constructor, there is no user-declared move constructor, and there is no
9453 // user-declared move assignment operator, a copy constructor is implicitly
9454 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009455 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009456 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009457
Richard Smithbc2a35d2012-12-08 08:32:28 +00009458 // Note that we have declared this constructor.
9459 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9460
9461 if (Scope *S = getScopeForContext(ClassDecl))
9462 PushOnScopeChains(CopyConstructor, S, false);
9463 ClassDecl->addDecl(CopyConstructor);
9464
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009465 return CopyConstructor;
9466}
9467
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009468void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009469 CXXConstructorDecl *CopyConstructor) {
9470 assert((CopyConstructor->isDefaulted() &&
9471 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009472 !CopyConstructor->doesThisDeclarationHaveABody() &&
9473 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009474 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009475
Anders Carlsson63010a72010-04-23 16:24:12 +00009476 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009477 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009478
Eli Friedman9a14db32012-10-18 20:14:08 +00009479 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009480 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009481
David Blaikie93c86172013-01-17 05:26:25 +00009482 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009483 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009484 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009485 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009486 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009487 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009488 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009489 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9490 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009491 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009492 /*isStmtExpr=*/false)
9493 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009494 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009495 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009496
9497 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009498 if (ASTMutationListener *L = getASTMutationListener()) {
9499 L->CompletedImplicitDefinition(CopyConstructor);
9500 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009501}
9502
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009503Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009504Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9505 CXXRecordDecl *ClassDecl = MD->getParent();
9506
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009507 // C++ [except.spec]p14:
9508 // An implicitly declared special member function (Clause 12) shall have an
9509 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009510 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009511 if (ClassDecl->isInvalidDecl())
9512 return ExceptSpec;
9513
9514 // Direct base-class constructors.
9515 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9516 BEnd = ClassDecl->bases_end();
9517 B != BEnd; ++B) {
9518 if (B->isVirtual()) // Handled below.
9519 continue;
9520
9521 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9522 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009523 CXXConstructorDecl *Constructor =
9524 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009525 // If this is a deleted function, add it anyway. This might be conformant
9526 // with the standard. This might not. I'm not sure. It might not matter.
9527 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009528 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009529 }
9530 }
9531
9532 // Virtual base-class constructors.
9533 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9534 BEnd = ClassDecl->vbases_end();
9535 B != BEnd; ++B) {
9536 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9537 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009538 CXXConstructorDecl *Constructor =
9539 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009540 // If this is a deleted function, add it anyway. This might be conformant
9541 // with the standard. This might not. I'm not sure. It might not matter.
9542 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009543 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009544 }
9545 }
9546
9547 // Field constructors.
9548 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9549 FEnd = ClassDecl->field_end();
9550 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009551 QualType FieldType = Context.getBaseElementType(F->getType());
9552 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9553 CXXConstructorDecl *Constructor =
9554 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009555 // If this is a deleted function, add it anyway. This might be conformant
9556 // with the standard. This might not. I'm not sure. It might not matter.
9557 // In particular, the problem is that this function never gets called. It
9558 // might just be ill-formed because this function attempts to refer to
9559 // a deleted function here.
9560 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009561 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009562 }
9563 }
9564
9565 return ExceptSpec;
9566}
9567
9568CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9569 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009570 // C++11 [class.copy]p9:
9571 // If the definition of a class X does not explicitly declare a move
9572 // constructor, one will be implicitly declared as defaulted if and only if:
9573 //
9574 // - [first 4 bullets]
9575 assert(ClassDecl->needsImplicitMoveConstructor());
9576
Richard Smithafb49182012-11-29 01:34:07 +00009577 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9578 if (DSM.isAlreadyBeingDeclared())
9579 return 0;
9580
Richard Smith1c931be2012-04-02 18:40:40 +00009581 // [Checked after we build the declaration]
9582 // - the move assignment operator would not be implicitly defined as
9583 // deleted,
9584
9585 // [DR1402]:
9586 // - each of X's non-static data members and direct or virtual base classes
9587 // has a type that either has a move constructor or is trivially copyable.
9588 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9589 ClassDecl->setFailedImplicitMoveConstructor();
9590 return 0;
9591 }
9592
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009593 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9594 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009595
Richard Smith7756afa2012-06-10 05:43:50 +00009596 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9597 CXXMoveConstructor,
9598 false);
9599
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009600 DeclarationName Name
9601 = Context.DeclarationNames.getCXXConstructorName(
9602 Context.getCanonicalType(ClassType));
9603 SourceLocation ClassLoc = ClassDecl->getLocation();
9604 DeclarationNameInfo NameInfo(Name, ClassLoc);
9605
9606 // C++0x [class.copy]p11:
9607 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009608 // member of its class.
9609 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009610 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009611 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009612 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009613 MoveConstructor->setAccess(AS_public);
9614 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009615
Richard Smithb9d0b762012-07-27 04:22:15 +00009616 // Build an exception specification pointing back at this member.
9617 FunctionProtoType::ExtProtoInfo EPI;
9618 EPI.ExceptionSpecType = EST_Unevaluated;
9619 EPI.ExceptionSpecDecl = MoveConstructor;
9620 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009621 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009622
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009623 // Add the parameter to the constructor.
9624 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9625 ClassLoc, ClassLoc,
9626 /*IdentifierInfo=*/0,
9627 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009628 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009629 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009630
Richard Smithbc2a35d2012-12-08 08:32:28 +00009631 MoveConstructor->setTrivial(
9632 ClassDecl->needsOverloadResolutionForMoveConstructor()
9633 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9634 : ClassDecl->hasTrivialMoveConstructor());
9635
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009636 // C++0x [class.copy]p9:
9637 // If the definition of a class X does not explicitly declare a move
9638 // constructor, one will be implicitly declared as defaulted if and only if:
9639 // [...]
9640 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009641 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009642 // Cache this result so that we don't try to generate this over and over
9643 // on every lookup, leaking memory and wasting time.
9644 ClassDecl->setFailedImplicitMoveConstructor();
9645 return 0;
9646 }
9647
9648 // Note that we have declared this constructor.
9649 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9650
9651 if (Scope *S = getScopeForContext(ClassDecl))
9652 PushOnScopeChains(MoveConstructor, S, false);
9653 ClassDecl->addDecl(MoveConstructor);
9654
9655 return MoveConstructor;
9656}
9657
9658void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9659 CXXConstructorDecl *MoveConstructor) {
9660 assert((MoveConstructor->isDefaulted() &&
9661 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009662 !MoveConstructor->doesThisDeclarationHaveABody() &&
9663 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009664 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9665
9666 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9667 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9668
Eli Friedman9a14db32012-10-18 20:14:08 +00009669 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009670 DiagnosticErrorTrap Trap(Diags);
9671
David Blaikie93c86172013-01-17 05:26:25 +00009672 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009673 Trap.hasErrorOccurred()) {
9674 Diag(CurrentLocation, diag::note_member_synthesized_at)
9675 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9676 MoveConstructor->setInvalidDecl();
9677 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009678 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009679 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9680 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009681 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009682 /*isStmtExpr=*/false)
9683 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009684 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009685 }
9686
9687 MoveConstructor->setUsed();
9688
9689 if (ASTMutationListener *L = getASTMutationListener()) {
9690 L->CompletedImplicitDefinition(MoveConstructor);
9691 }
9692}
9693
Douglas Gregore4e68d42012-02-15 19:33:52 +00009694bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9695 return FD->isDeleted() &&
9696 (FD->isDefaulted() || FD->isImplicit()) &&
9697 isa<CXXMethodDecl>(FD);
9698}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009699
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009700/// \brief Mark the call operator of the given lambda closure type as "used".
9701static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9702 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009703 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009704 Lambda->lookup(
9705 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009706 CallOperator->setReferenced();
9707 CallOperator->setUsed();
9708}
9709
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009710void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9711 SourceLocation CurrentLocation,
9712 CXXConversionDecl *Conv)
9713{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009714 CXXRecordDecl *Lambda = Conv->getParent();
9715
9716 // Make sure that the lambda call operator is marked used.
9717 markLambdaCallOperatorUsed(*this, Lambda);
9718
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009719 Conv->setUsed();
9720
Eli Friedman9a14db32012-10-18 20:14:08 +00009721 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009722 DiagnosticErrorTrap Trap(Diags);
9723
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009724 // Return the address of the __invoke function.
9725 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9726 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009727 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009728 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9729 VK_LValue, Conv->getLocation()).take();
9730 assert(FunctionRef && "Can't refer to __invoke function?");
9731 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009732 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009733 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009734 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009735
9736 // Fill in the __invoke function with a dummy implementation. IR generation
9737 // will fill in the actual details.
9738 Invoke->setUsed();
9739 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009740 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009741
9742 if (ASTMutationListener *L = getASTMutationListener()) {
9743 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009744 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009745 }
9746}
9747
9748void Sema::DefineImplicitLambdaToBlockPointerConversion(
9749 SourceLocation CurrentLocation,
9750 CXXConversionDecl *Conv)
9751{
9752 Conv->setUsed();
9753
Eli Friedman9a14db32012-10-18 20:14:08 +00009754 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009755 DiagnosticErrorTrap Trap(Diags);
9756
Douglas Gregorac1303e2012-02-22 05:02:47 +00009757 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009758 Expr *This = ActOnCXXThis(CurrentLocation).take();
9759 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009760
Eli Friedman23f02672012-03-01 04:01:32 +00009761 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9762 Conv->getLocation(),
9763 Conv, DerefThis);
9764
9765 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9766 // behavior. Note that only the general conversion function does this
9767 // (since it's unusable otherwise); in the case where we inline the
9768 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009769 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009770 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9771 CK_CopyAndAutoreleaseBlockObject,
9772 BuildBlock.get(), 0, VK_RValue);
9773
9774 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009775 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009776 Conv->setInvalidDecl();
9777 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009778 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009779
Douglas Gregorac1303e2012-02-22 05:02:47 +00009780 // Create the return statement that returns the block from the conversion
9781 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009782 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009783 if (Return.isInvalid()) {
9784 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9785 Conv->setInvalidDecl();
9786 return;
9787 }
9788
9789 // Set the body of the conversion function.
9790 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009791 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009792 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009793 Conv->getLocation()));
9794
Douglas Gregorac1303e2012-02-22 05:02:47 +00009795 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009796 if (ASTMutationListener *L = getASTMutationListener()) {
9797 L->CompletedImplicitDefinition(Conv);
9798 }
9799}
9800
Douglas Gregorf52757d2012-03-10 06:53:13 +00009801/// \brief Determine whether the given list arguments contains exactly one
9802/// "real" (non-default) argument.
9803static bool hasOneRealArgument(MultiExprArg Args) {
9804 switch (Args.size()) {
9805 case 0:
9806 return false;
9807
9808 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009809 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009810 return false;
9811
9812 // fall through
9813 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009814 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009815 }
9816
9817 return false;
9818}
9819
John McCall60d7b3a2010-08-24 06:29:42 +00009820ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009821Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009822 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009823 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009824 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009825 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009826 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009827 unsigned ConstructKind,
9828 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009829 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009830
Douglas Gregor2f599792010-04-02 18:24:57 +00009831 // C++0x [class.copy]p34:
9832 // When certain criteria are met, an implementation is allowed to
9833 // omit the copy/move construction of a class object, even if the
9834 // copy/move constructor and/or destructor for the object have
9835 // side effects. [...]
9836 // - when a temporary class object that has not been bound to a
9837 // reference (12.2) would be copied/moved to a class object
9838 // with the same cv-unqualified type, the copy/move operation
9839 // can be omitted by constructing the temporary object
9840 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009841 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009842 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009843 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009844 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009845 }
Mike Stump1eb44332009-09-09 15:08:12 +00009846
9847 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009848 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009849 IsListInitialization, RequiresZeroInit,
9850 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009851}
9852
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009853/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9854/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009855ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009856Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9857 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009858 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009859 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009860 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009861 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009862 unsigned ConstructKind,
9863 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009864 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009865 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009866 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009867 HadMultipleCandidates,
9868 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009869 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9870 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009871}
9872
John McCall68c6c9a2010-02-02 09:10:11 +00009873void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009874 if (VD->isInvalidDecl()) return;
9875
John McCall68c6c9a2010-02-02 09:10:11 +00009876 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009877 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009878 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009879 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009880
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009881 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009882 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009883 CheckDestructorAccess(VD->getLocation(), Destructor,
9884 PDiag(diag::err_access_dtor_var)
9885 << VD->getDeclName()
9886 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009887 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009888
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009889 if (!VD->hasGlobalStorage()) return;
9890
9891 // Emit warning for non-trivial dtor in global scope (a real global,
9892 // class-static, function-static).
9893 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9894
9895 // TODO: this should be re-enabled for static locals by !CXAAtExit
9896 if (!VD->isStaticLocal())
9897 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009898}
9899
Douglas Gregor39da0b82009-09-09 23:08:42 +00009900/// \brief Given a constructor and the set of arguments provided for the
9901/// constructor, convert the arguments and add any required default arguments
9902/// to form a proper call to this constructor.
9903///
9904/// \returns true if an error occurred, false otherwise.
9905bool
9906Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9907 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009908 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009909 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009910 bool AllowExplicit,
9911 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009912 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9913 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009914 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009915
9916 const FunctionProtoType *Proto
9917 = Constructor->getType()->getAs<FunctionProtoType>();
9918 assert(Proto && "Constructor without a prototype?");
9919 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009920
9921 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009922 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009923 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009924 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009925 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009926
9927 VariadicCallType CallType =
9928 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009929 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009930 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9931 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009932 CallType, AllowExplicit,
9933 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009934 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009935
9936 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9937
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009938 CheckConstructorCall(Constructor,
9939 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9940 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009941 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009942
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009943 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009944}
9945
Anders Carlsson20d45d22009-12-12 00:32:00 +00009946static inline bool
9947CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9948 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009949 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009950 if (isa<NamespaceDecl>(DC)) {
9951 return SemaRef.Diag(FnDecl->getLocation(),
9952 diag::err_operator_new_delete_declared_in_namespace)
9953 << FnDecl->getDeclName();
9954 }
9955
9956 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009957 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009958 return SemaRef.Diag(FnDecl->getLocation(),
9959 diag::err_operator_new_delete_declared_static)
9960 << FnDecl->getDeclName();
9961 }
9962
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009963 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009964}
9965
Anders Carlsson156c78e2009-12-13 17:53:43 +00009966static inline bool
9967CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9968 CanQualType ExpectedResultType,
9969 CanQualType ExpectedFirstParamType,
9970 unsigned DependentParamTypeDiag,
9971 unsigned InvalidParamTypeDiag) {
9972 QualType ResultType =
9973 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9974
9975 // Check that the result type is not dependent.
9976 if (ResultType->isDependentType())
9977 return SemaRef.Diag(FnDecl->getLocation(),
9978 diag::err_operator_new_delete_dependent_result_type)
9979 << FnDecl->getDeclName() << ExpectedResultType;
9980
9981 // Check that the result type is what we expect.
9982 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9983 return SemaRef.Diag(FnDecl->getLocation(),
9984 diag::err_operator_new_delete_invalid_result_type)
9985 << FnDecl->getDeclName() << ExpectedResultType;
9986
9987 // A function template must have at least 2 parameters.
9988 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9989 return SemaRef.Diag(FnDecl->getLocation(),
9990 diag::err_operator_new_delete_template_too_few_parameters)
9991 << FnDecl->getDeclName();
9992
9993 // The function decl must have at least 1 parameter.
9994 if (FnDecl->getNumParams() == 0)
9995 return SemaRef.Diag(FnDecl->getLocation(),
9996 diag::err_operator_new_delete_too_few_parameters)
9997 << FnDecl->getDeclName();
9998
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009999 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010000 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10001 if (FirstParamType->isDependentType())
10002 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10003 << FnDecl->getDeclName() << ExpectedFirstParamType;
10004
10005 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010006 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010007 ExpectedFirstParamType)
10008 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10009 << FnDecl->getDeclName() << ExpectedFirstParamType;
10010
10011 return false;
10012}
10013
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010014static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010015CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010016 // C++ [basic.stc.dynamic.allocation]p1:
10017 // A program is ill-formed if an allocation function is declared in a
10018 // namespace scope other than global scope or declared static in global
10019 // scope.
10020 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10021 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010022
10023 CanQualType SizeTy =
10024 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10025
10026 // C++ [basic.stc.dynamic.allocation]p1:
10027 // The return type shall be void*. The first parameter shall have type
10028 // std::size_t.
10029 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10030 SizeTy,
10031 diag::err_operator_new_dependent_param_type,
10032 diag::err_operator_new_param_type))
10033 return true;
10034
10035 // C++ [basic.stc.dynamic.allocation]p1:
10036 // The first parameter shall not have an associated default argument.
10037 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010038 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010039 diag::err_operator_new_default_arg)
10040 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10041
10042 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010043}
10044
10045static bool
Richard Smith444d3842012-10-20 08:26:51 +000010046CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010047 // C++ [basic.stc.dynamic.deallocation]p1:
10048 // A program is ill-formed if deallocation functions are declared in a
10049 // namespace scope other than global scope or declared static in global
10050 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010051 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10052 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010053
10054 // C++ [basic.stc.dynamic.deallocation]p2:
10055 // Each deallocation function shall return void and its first parameter
10056 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010057 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10058 SemaRef.Context.VoidPtrTy,
10059 diag::err_operator_delete_dependent_param_type,
10060 diag::err_operator_delete_param_type))
10061 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010062
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010063 return false;
10064}
10065
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010066/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10067/// of this overloaded operator is well-formed. If so, returns false;
10068/// otherwise, emits appropriate diagnostics and returns true.
10069bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010070 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010071 "Expected an overloaded operator declaration");
10072
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010073 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10074
Mike Stump1eb44332009-09-09 15:08:12 +000010075 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010076 // The allocation and deallocation functions, operator new,
10077 // operator new[], operator delete and operator delete[], are
10078 // described completely in 3.7.3. The attributes and restrictions
10079 // found in the rest of this subclause do not apply to them unless
10080 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010081 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010082 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010083
Anders Carlssona3ccda52009-12-12 00:26:23 +000010084 if (Op == OO_New || Op == OO_Array_New)
10085 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010086
10087 // C++ [over.oper]p6:
10088 // An operator function shall either be a non-static member
10089 // function or be a non-member function and have at least one
10090 // parameter whose type is a class, a reference to a class, an
10091 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010092 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10093 if (MethodDecl->isStatic())
10094 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010095 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010096 } else {
10097 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010098 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10099 ParamEnd = FnDecl->param_end();
10100 Param != ParamEnd; ++Param) {
10101 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010102 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10103 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010104 ClassOrEnumParam = true;
10105 break;
10106 }
10107 }
10108
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010109 if (!ClassOrEnumParam)
10110 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010111 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010112 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010113 }
10114
10115 // C++ [over.oper]p8:
10116 // An operator function cannot have default arguments (8.3.6),
10117 // except where explicitly stated below.
10118 //
Mike Stump1eb44332009-09-09 15:08:12 +000010119 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010120 // (C++ [over.call]p1).
10121 if (Op != OO_Call) {
10122 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10123 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010124 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010125 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010126 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010127 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010128 }
10129 }
10130
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010131 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10132 { false, false, false }
10133#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10134 , { Unary, Binary, MemberOnly }
10135#include "clang/Basic/OperatorKinds.def"
10136 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010137
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010138 bool CanBeUnaryOperator = OperatorUses[Op][0];
10139 bool CanBeBinaryOperator = OperatorUses[Op][1];
10140 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010141
10142 // C++ [over.oper]p8:
10143 // [...] Operator functions cannot have more or fewer parameters
10144 // than the number required for the corresponding operator, as
10145 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010146 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010147 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010148 if (Op != OO_Call &&
10149 ((NumParams == 1 && !CanBeUnaryOperator) ||
10150 (NumParams == 2 && !CanBeBinaryOperator) ||
10151 (NumParams < 1) || (NumParams > 2))) {
10152 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010153 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010154 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010155 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010156 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010157 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010158 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010159 assert(CanBeBinaryOperator &&
10160 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010161 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010162 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010163
Chris Lattner416e46f2008-11-21 07:57:12 +000010164 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010165 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010166 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010167
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010168 // Overloaded operators other than operator() cannot be variadic.
10169 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010170 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010171 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010172 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010173 }
10174
10175 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010176 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10177 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010178 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010179 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010180 }
10181
10182 // C++ [over.inc]p1:
10183 // The user-defined function called operator++ implements the
10184 // prefix and postfix ++ operator. If this function is a member
10185 // function with no parameters, or a non-member function with one
10186 // parameter of class or enumeration type, it defines the prefix
10187 // increment operator ++ for objects of that type. If the function
10188 // is a member function with one parameter (which shall be of type
10189 // int) or a non-member function with two parameters (the second
10190 // of which shall be of type int), it defines the postfix
10191 // increment operator ++ for objects of that type.
10192 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10193 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10194 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010195 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010196 ParamIsInt = BT->getKind() == BuiltinType::Int;
10197
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010198 if (!ParamIsInt)
10199 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010200 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010201 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010202 }
10203
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010204 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010205}
Chris Lattner5a003a42008-12-17 07:09:26 +000010206
Sean Hunta6c058d2010-01-13 09:01:02 +000010207/// CheckLiteralOperatorDeclaration - Check whether the declaration
10208/// of this literal operator function is well-formed. If so, returns
10209/// false; otherwise, emits appropriate diagnostics and returns true.
10210bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010211 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010212 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10213 << FnDecl->getDeclName();
10214 return true;
10215 }
10216
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010217 if (FnDecl->isExternC()) {
10218 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10219 return true;
10220 }
10221
Sean Hunta6c058d2010-01-13 09:01:02 +000010222 bool Valid = false;
10223
Richard Smith36f5cfe2012-03-09 08:00:36 +000010224 // This might be the definition of a literal operator template.
10225 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10226 // This might be a specialization of a literal operator template.
10227 if (!TpDecl)
10228 TpDecl = FnDecl->getPrimaryTemplate();
10229
Sean Hunt216c2782010-04-07 23:11:06 +000010230 // template <char...> type operator "" name() is the only valid template
10231 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010232 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010233 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010234 // Must have only one template parameter
10235 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10236 if (Params->size() == 1) {
10237 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010238 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010239
Sean Hunt216c2782010-04-07 23:11:06 +000010240 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010241 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10242 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10243 Valid = true;
10244 }
10245 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010246 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010247 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010248 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10249
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010250 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010251
Sean Hunt30019c02010-04-07 22:57:35 +000010252 // unsigned long long int, long double, and any character type are allowed
10253 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010254 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10255 Context.hasSameType(T, Context.LongDoubleTy) ||
10256 Context.hasSameType(T, Context.CharTy) ||
10257 Context.hasSameType(T, Context.WCharTy) ||
10258 Context.hasSameType(T, Context.Char16Ty) ||
10259 Context.hasSameType(T, Context.Char32Ty)) {
10260 if (++Param == FnDecl->param_end())
10261 Valid = true;
10262 goto FinishedParams;
10263 }
10264
Sean Hunt30019c02010-04-07 22:57:35 +000010265 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010266 const PointerType *PT = T->getAs<PointerType>();
10267 if (!PT)
10268 goto FinishedParams;
10269 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010270 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010271 goto FinishedParams;
10272 T = T.getUnqualifiedType();
10273
10274 // Move on to the second parameter;
10275 ++Param;
10276
10277 // If there is no second parameter, the first must be a const char *
10278 if (Param == FnDecl->param_end()) {
10279 if (Context.hasSameType(T, Context.CharTy))
10280 Valid = true;
10281 goto FinishedParams;
10282 }
10283
10284 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10285 // are allowed as the first parameter to a two-parameter function
10286 if (!(Context.hasSameType(T, Context.CharTy) ||
10287 Context.hasSameType(T, Context.WCharTy) ||
10288 Context.hasSameType(T, Context.Char16Ty) ||
10289 Context.hasSameType(T, Context.Char32Ty)))
10290 goto FinishedParams;
10291
10292 // The second and final parameter must be an std::size_t
10293 T = (*Param)->getType().getUnqualifiedType();
10294 if (Context.hasSameType(T, Context.getSizeType()) &&
10295 ++Param == FnDecl->param_end())
10296 Valid = true;
10297 }
10298
10299 // FIXME: This diagnostic is absolutely terrible.
10300FinishedParams:
10301 if (!Valid) {
10302 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10303 << FnDecl->getDeclName();
10304 return true;
10305 }
10306
Richard Smitha9e88b22012-03-09 08:16:22 +000010307 // A parameter-declaration-clause containing a default argument is not
10308 // equivalent to any of the permitted forms.
10309 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10310 ParamEnd = FnDecl->param_end();
10311 Param != ParamEnd; ++Param) {
10312 if ((*Param)->hasDefaultArg()) {
10313 Diag((*Param)->getDefaultArgRange().getBegin(),
10314 diag::err_literal_operator_default_argument)
10315 << (*Param)->getDefaultArgRange();
10316 break;
10317 }
10318 }
10319
Richard Smith2fb4ae32012-03-08 02:39:21 +000010320 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010321 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10322 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010323 // C++11 [usrlit.suffix]p1:
10324 // Literal suffix identifiers that do not start with an underscore
10325 // are reserved for future standardization.
10326 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010327 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010328
Sean Hunta6c058d2010-01-13 09:01:02 +000010329 return false;
10330}
10331
Douglas Gregor074149e2009-01-05 19:45:36 +000010332/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10333/// linkage specification, including the language and (if present)
10334/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10335/// the location of the language string literal, which is provided
10336/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10337/// the '{' brace. Otherwise, this linkage specification does not
10338/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010339Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10340 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010341 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010342 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010343 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010344 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010345 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010346 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010347 Language = LinkageSpecDecl::lang_cxx;
10348 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010349 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010350 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010351 }
Mike Stump1eb44332009-09-09 15:08:12 +000010352
Chris Lattnercc98eac2008-12-17 07:13:27 +000010353 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010354
Douglas Gregor074149e2009-01-05 19:45:36 +000010355 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010356 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010357 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010358 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010359 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010360}
10361
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010362/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010363/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10364/// valid, it's the position of the closing '}' brace in a linkage
10365/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010366Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010367 Decl *LinkageSpec,
10368 SourceLocation RBraceLoc) {
10369 if (LinkageSpec) {
10370 if (RBraceLoc.isValid()) {
10371 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10372 LSDecl->setRBraceLoc(RBraceLoc);
10373 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010374 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010375 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010376 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010377}
10378
Michael Han684aa732013-02-22 17:15:32 +000010379Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10380 AttributeList *AttrList,
10381 SourceLocation SemiLoc) {
10382 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10383 // Attribute declarations appertain to empty declaration so we handle
10384 // them here.
10385 if (AttrList)
10386 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010387
Michael Han684aa732013-02-22 17:15:32 +000010388 CurContext->addDecl(ED);
10389 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010390}
10391
Douglas Gregord308e622009-05-18 20:51:54 +000010392/// \brief Perform semantic analysis for the variable declaration that
10393/// occurs within a C++ catch clause, returning the newly-created
10394/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010395VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010396 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010397 SourceLocation StartLoc,
10398 SourceLocation Loc,
10399 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010400 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010401 QualType ExDeclType = TInfo->getType();
10402
Sebastian Redl4b07b292008-12-22 19:15:10 +000010403 // Arrays and functions decay.
10404 if (ExDeclType->isArrayType())
10405 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10406 else if (ExDeclType->isFunctionType())
10407 ExDeclType = Context.getPointerType(ExDeclType);
10408
10409 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10410 // The exception-declaration shall not denote a pointer or reference to an
10411 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010412 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010413 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010414 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010415 Invalid = true;
10416 }
Douglas Gregord308e622009-05-18 20:51:54 +000010417
Sebastian Redl4b07b292008-12-22 19:15:10 +000010418 QualType BaseType = ExDeclType;
10419 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010420 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010421 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010422 BaseType = Ptr->getPointeeType();
10423 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010424 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010425 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010426 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010427 BaseType = Ref->getPointeeType();
10428 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010429 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010430 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010431 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010432 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010433 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010434
Mike Stump1eb44332009-09-09 15:08:12 +000010435 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010436 RequireNonAbstractType(Loc, ExDeclType,
10437 diag::err_abstract_type_in_decl,
10438 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010439 Invalid = true;
10440
John McCall5a180392010-07-24 00:37:23 +000010441 // Only the non-fragile NeXT runtime currently supports C++ catches
10442 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010443 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010444 QualType T = ExDeclType;
10445 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10446 T = RT->getPointeeType();
10447
10448 if (T->isObjCObjectType()) {
10449 Diag(Loc, diag::err_objc_object_catch);
10450 Invalid = true;
10451 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010452 // FIXME: should this be a test for macosx-fragile specifically?
10453 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010454 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010455 }
10456 }
10457
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010458 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010459 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010460 ExDecl->setExceptionVariable(true);
10461
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010462 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010463 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010464 Invalid = true;
10465
Douglas Gregorc41b8782011-07-06 18:14:43 +000010466 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010467 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010468 // Insulate this from anything else we might currently be parsing.
10469 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10470
Douglas Gregor6d182892010-03-05 23:38:39 +000010471 // C++ [except.handle]p16:
10472 // The object declared in an exception-declaration or, if the
10473 // exception-declaration does not specify a name, a temporary (12.2) is
10474 // copy-initialized (8.5) from the exception object. [...]
10475 // The object is destroyed when the handler exits, after the destruction
10476 // of any automatic objects initialized within the handler.
10477 //
10478 // We just pretend to initialize the object with itself, then make sure
10479 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010480 QualType initType = ExDeclType;
10481
10482 InitializedEntity entity =
10483 InitializedEntity::InitializeVariable(ExDecl);
10484 InitializationKind initKind =
10485 InitializationKind::CreateCopy(Loc, SourceLocation());
10486
10487 Expr *opaqueValue =
10488 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10489 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10490 ExprResult result = sequence.Perform(*this, entity, initKind,
10491 MultiExprArg(&opaqueValue, 1));
10492 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010493 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010494 else {
10495 // If the constructor used was non-trivial, set this as the
10496 // "initializer".
10497 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10498 if (!construct->getConstructor()->isTrivial()) {
10499 Expr *init = MaybeCreateExprWithCleanups(construct);
10500 ExDecl->setInit(init);
10501 }
10502
10503 // And make sure it's destructable.
10504 FinalizeVarWithDestructor(ExDecl, recordType);
10505 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010506 }
10507 }
10508
Douglas Gregord308e622009-05-18 20:51:54 +000010509 if (Invalid)
10510 ExDecl->setInvalidDecl();
10511
10512 return ExDecl;
10513}
10514
10515/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10516/// handler.
John McCalld226f652010-08-21 09:40:31 +000010517Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010518 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010519 bool Invalid = D.isInvalidType();
10520
10521 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010522 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10523 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010524 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10525 D.getIdentifierLoc());
10526 Invalid = true;
10527 }
10528
Sebastian Redl4b07b292008-12-22 19:15:10 +000010529 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010530 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010531 LookupOrdinaryName,
10532 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010533 // The scope should be freshly made just for us. There is just no way
10534 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010535 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010536 if (PrevDecl->isTemplateParameter()) {
10537 // Maybe we will complain about the shadowed template parameter.
10538 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010539 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010540 }
10541 }
10542
Chris Lattnereaaebc72009-04-25 08:06:05 +000010543 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010544 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10545 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010546 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010547 }
10548
Douglas Gregor83cb9422010-09-09 17:09:21 +000010549 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010550 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010551 D.getIdentifierLoc(),
10552 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010553 if (Invalid)
10554 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010555
Sebastian Redl4b07b292008-12-22 19:15:10 +000010556 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010557 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010558 PushOnScopeChains(ExDecl, S);
10559 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010560 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010561
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010562 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010563 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010564}
Anders Carlssonfb311762009-03-14 00:25:26 +000010565
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010566Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010567 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010568 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010569 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010570 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010571
Richard Smithe3f470a2012-07-11 22:37:56 +000010572 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10573 return 0;
10574
10575 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10576 AssertMessage, RParenLoc, false);
10577}
10578
10579Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10580 Expr *AssertExpr,
10581 StringLiteral *AssertMessage,
10582 SourceLocation RParenLoc,
10583 bool Failed) {
10584 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10585 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010586 // In a static_assert-declaration, the constant-expression shall be a
10587 // constant expression that can be contextually converted to bool.
10588 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10589 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010590 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010591
Richard Smithdaaefc52011-12-14 23:32:26 +000010592 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010593 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010594 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010595 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010596 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010597
Richard Smithe3f470a2012-07-11 22:37:56 +000010598 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010599 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010600 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010601 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010602 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010603 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010604 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010605 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010606 }
Mike Stump1eb44332009-09-09 15:08:12 +000010607
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010608 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010609 AssertExpr, AssertMessage, RParenLoc,
10610 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010611
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010612 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010613 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010614}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010615
Douglas Gregor1d869352010-04-07 16:53:43 +000010616/// \brief Perform semantic analysis of the given friend type declaration.
10617///
10618/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010619FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010620 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010621 TypeSourceInfo *TSInfo) {
10622 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10623
10624 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010625 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010626
Richard Smith6b130222011-10-18 21:39:00 +000010627 // C++03 [class.friend]p2:
10628 // An elaborated-type-specifier shall be used in a friend declaration
10629 // for a class.*
10630 //
10631 // * The class-key of the elaborated-type-specifier is required.
10632 if (!ActiveTemplateInstantiations.empty()) {
10633 // Do not complain about the form of friend template types during
10634 // template instantiation; we will already have complained when the
10635 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010636 } else {
10637 if (!T->isElaboratedTypeSpecifier()) {
10638 // If we evaluated the type to a record type, suggest putting
10639 // a tag in front.
10640 if (const RecordType *RT = T->getAs<RecordType>()) {
10641 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010642
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010643 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010644
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010645 Diag(TypeRange.getBegin(),
10646 getLangOpts().CPlusPlus11 ?
10647 diag::warn_cxx98_compat_unelaborated_friend_type :
10648 diag::ext_unelaborated_friend_type)
10649 << (unsigned) RD->getTagKind()
10650 << T
10651 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10652 InsertionText);
10653 } else {
10654 Diag(FriendLoc,
10655 getLangOpts().CPlusPlus11 ?
10656 diag::warn_cxx98_compat_nonclass_type_friend :
10657 diag::ext_nonclass_type_friend)
10658 << T
10659 << TypeRange;
10660 }
10661 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010662 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010663 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010664 diag::warn_cxx98_compat_enum_friend :
10665 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010666 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010667 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010668 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010669
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010670 // C++11 [class.friend]p3:
10671 // A friend declaration that does not declare a function shall have one
10672 // of the following forms:
10673 // friend elaborated-type-specifier ;
10674 // friend simple-type-specifier ;
10675 // friend typename-specifier ;
10676 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10677 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10678 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010679
Douglas Gregor06245bf2010-04-07 17:57:12 +000010680 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010681 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010682 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010683 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010684}
10685
John McCall9a34edb2010-10-19 01:40:49 +000010686/// Handle a friend tag declaration where the scope specifier was
10687/// templated.
10688Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10689 unsigned TagSpec, SourceLocation TagLoc,
10690 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010691 IdentifierInfo *Name,
10692 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010693 AttributeList *Attr,
10694 MultiTemplateParamsArg TempParamLists) {
10695 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10696
10697 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010698 bool Invalid = false;
10699
10700 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010701 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010702 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010703 TempParamLists.size(),
10704 /*friend*/ true,
10705 isExplicitSpecialization,
10706 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010707 if (TemplateParams->size() > 0) {
10708 // This is a declaration of a class template.
10709 if (Invalid)
10710 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010711
Eric Christopher4110e132011-07-21 05:34:24 +000010712 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10713 SS, Name, NameLoc, Attr,
10714 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010715 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010716 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010717 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010718 } else {
10719 // The "template<>" header is extraneous.
10720 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10721 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10722 isExplicitSpecialization = true;
10723 }
10724 }
10725
10726 if (Invalid) return 0;
10727
John McCall9a34edb2010-10-19 01:40:49 +000010728 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010729 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010730 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010731 isAllExplicitSpecializations = false;
10732 break;
10733 }
10734 }
10735
10736 // FIXME: don't ignore attributes.
10737
10738 // If it's explicit specializations all the way down, just forget
10739 // about the template header and build an appropriate non-templated
10740 // friend. TODO: for source fidelity, remember the headers.
10741 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010742 if (SS.isEmpty()) {
10743 bool Owned = false;
10744 bool IsDependent = false;
10745 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10746 Attr, AS_public,
10747 /*ModulePrivateLoc=*/SourceLocation(),
10748 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010749 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010750 /*ScopedEnumUsesClassTag=*/false,
10751 /*UnderlyingType=*/TypeResult());
10752 }
10753
Douglas Gregor2494dd02011-03-01 01:34:45 +000010754 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010755 ElaboratedTypeKeyword Keyword
10756 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010757 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010758 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010759 if (T.isNull())
10760 return 0;
10761
10762 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10763 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010764 DependentNameTypeLoc TL =
10765 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010766 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010767 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010768 TL.setNameLoc(NameLoc);
10769 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010770 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010771 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010772 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010773 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010774 }
10775
10776 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010777 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010778 Friend->setAccess(AS_public);
10779 CurContext->addDecl(Friend);
10780 return Friend;
10781 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010782
10783 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10784
10785
John McCall9a34edb2010-10-19 01:40:49 +000010786
10787 // Handle the case of a templated-scope friend class. e.g.
10788 // template <class T> class A<T>::B;
10789 // FIXME: we don't support these right now.
10790 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10791 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10792 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010793 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010794 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010795 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010796 TL.setNameLoc(NameLoc);
10797
10798 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010799 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010800 Friend->setAccess(AS_public);
10801 Friend->setUnsupportedFriend(true);
10802 CurContext->addDecl(Friend);
10803 return Friend;
10804}
10805
10806
John McCalldd4a3b02009-09-16 22:47:08 +000010807/// Handle a friend type declaration. This works in tandem with
10808/// ActOnTag.
10809///
10810/// Notes on friend class templates:
10811///
10812/// We generally treat friend class declarations as if they were
10813/// declaring a class. So, for example, the elaborated type specifier
10814/// in a friend declaration is required to obey the restrictions of a
10815/// class-head (i.e. no typedefs in the scope chain), template
10816/// parameters are required to match up with simple template-ids, &c.
10817/// However, unlike when declaring a template specialization, it's
10818/// okay to refer to a template specialization without an empty
10819/// template parameter declaration, e.g.
10820/// friend class A<T>::B<unsigned>;
10821/// We permit this as a special case; if there are any template
10822/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010823/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010824Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010825 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010826 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010827
10828 assert(DS.isFriendSpecified());
10829 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10830
John McCalldd4a3b02009-09-16 22:47:08 +000010831 // Try to convert the decl specifier to a type. This works for
10832 // friend templates because ActOnTag never produces a ClassTemplateDecl
10833 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010834 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010835 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10836 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010837 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010838 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010839
Douglas Gregor6ccab972010-12-16 01:14:37 +000010840 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10841 return 0;
10842
John McCalldd4a3b02009-09-16 22:47:08 +000010843 // This is definitely an error in C++98. It's probably meant to
10844 // be forbidden in C++0x, too, but the specification is just
10845 // poorly written.
10846 //
10847 // The problem is with declarations like the following:
10848 // template <T> friend A<T>::foo;
10849 // where deciding whether a class C is a friend or not now hinges
10850 // on whether there exists an instantiation of A that causes
10851 // 'foo' to equal C. There are restrictions on class-heads
10852 // (which we declare (by fiat) elaborated friend declarations to
10853 // be) that makes this tractable.
10854 //
10855 // FIXME: handle "template <> friend class A<T>;", which
10856 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010857 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010858 Diag(Loc, diag::err_tagless_friend_type_template)
10859 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010860 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010861 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010862
John McCall02cace72009-08-28 07:59:38 +000010863 // C++98 [class.friend]p1: A friend of a class is a function
10864 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010865 // This is fixed in DR77, which just barely didn't make the C++03
10866 // deadline. It's also a very silly restriction that seriously
10867 // affects inner classes and which nobody else seems to implement;
10868 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010869 //
10870 // But note that we could warn about it: it's always useless to
10871 // friend one of your own members (it's not, however, worthless to
10872 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010873
John McCalldd4a3b02009-09-16 22:47:08 +000010874 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010875 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010876 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010877 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010878 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010879 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010880 DS.getFriendSpecLoc());
10881 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010882 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010883
10884 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010885 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010886
John McCalldd4a3b02009-09-16 22:47:08 +000010887 D->setAccess(AS_public);
10888 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010889
John McCalld226f652010-08-21 09:40:31 +000010890 return D;
John McCall02cace72009-08-28 07:59:38 +000010891}
10892
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010893NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10894 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010895 const DeclSpec &DS = D.getDeclSpec();
10896
10897 assert(DS.isFriendSpecified());
10898 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10899
10900 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010901 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010902
10903 // C++ [class.friend]p1
10904 // A friend of a class is a function or class....
10905 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010906 // It *doesn't* see through dependent types, which is correct
10907 // according to [temp.arg.type]p3:
10908 // If a declaration acquires a function type through a
10909 // type dependent on a template-parameter and this causes
10910 // a declaration that does not use the syntactic form of a
10911 // function declarator to have a function type, the program
10912 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010913 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010914 Diag(Loc, diag::err_unexpected_friend);
10915
10916 // It might be worthwhile to try to recover by creating an
10917 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010918 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010919 }
10920
10921 // C++ [namespace.memdef]p3
10922 // - If a friend declaration in a non-local class first declares a
10923 // class or function, the friend class or function is a member
10924 // of the innermost enclosing namespace.
10925 // - The name of the friend is not found by simple name lookup
10926 // until a matching declaration is provided in that namespace
10927 // scope (either before or after the class declaration granting
10928 // friendship).
10929 // - If a friend function is called, its name may be found by the
10930 // name lookup that considers functions from namespaces and
10931 // classes associated with the types of the function arguments.
10932 // - When looking for a prior declaration of a class or a function
10933 // declared as a friend, scopes outside the innermost enclosing
10934 // namespace scope are not considered.
10935
John McCall337ec3d2010-10-12 23:13:28 +000010936 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010937 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10938 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010939 assert(Name);
10940
Douglas Gregor6ccab972010-12-16 01:14:37 +000010941 // Check for unexpanded parameter packs.
10942 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10943 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10944 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10945 return 0;
10946
John McCall67d1a672009-08-06 02:15:43 +000010947 // The context we found the declaration in, or in which we should
10948 // create the declaration.
10949 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010950 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010951 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010952 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010953
John McCall337ec3d2010-10-12 23:13:28 +000010954 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010955
John McCall337ec3d2010-10-12 23:13:28 +000010956 // There are four cases here.
10957 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010958 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010959 // there as appropriate.
10960 // Recover from invalid scope qualifiers as if they just weren't there.
10961 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010962 // C++0x [namespace.memdef]p3:
10963 // If the name in a friend declaration is neither qualified nor
10964 // a template-id and the declaration is a function or an
10965 // elaborated-type-specifier, the lookup to determine whether
10966 // the entity has been previously declared shall not consider
10967 // any scopes outside the innermost enclosing namespace.
10968 // C++0x [class.friend]p11:
10969 // If a friend declaration appears in a local class and the name
10970 // specified is an unqualified name, a prior declaration is
10971 // looked up without considering scopes that are outside the
10972 // innermost enclosing non-class scope. For a friend function
10973 // declaration, if there is no prior declaration, the program is
10974 // ill-formed.
10975 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010976 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010977
John McCall29ae6e52010-10-13 05:45:15 +000010978 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010979 DC = CurContext;
10980 while (true) {
10981 // Skip class contexts. If someone can cite chapter and verse
10982 // for this behavior, that would be nice --- it's what GCC and
10983 // EDG do, and it seems like a reasonable intent, but the spec
10984 // really only says that checks for unqualified existing
10985 // declarations should stop at the nearest enclosing namespace,
10986 // not that they should only consider the nearest enclosing
10987 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010988 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010989 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010990
John McCall68263142009-11-18 22:49:29 +000010991 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010992
10993 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010994 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010995 break;
John McCall29ae6e52010-10-13 05:45:15 +000010996
John McCall8a407372010-10-14 22:22:28 +000010997 if (isTemplateId) {
10998 if (isa<TranslationUnitDecl>(DC)) break;
10999 } else {
11000 if (DC->isFileContext()) break;
11001 }
John McCall67d1a672009-08-06 02:15:43 +000011002 DC = DC->getParent();
11003 }
11004
John McCall380aaa42010-10-13 06:22:15 +000011005 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011006
Douglas Gregor883af832011-10-10 01:11:59 +000011007 // C++ [class.friend]p6:
11008 // A function can be defined in a friend declaration of a class if and
11009 // only if the class is a non-local class (9.8), the function name is
11010 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011011 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011012 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11013 }
11014
John McCall337ec3d2010-10-12 23:13:28 +000011015 // - There's a non-dependent scope specifier, in which case we
11016 // compute it and do a previous lookup there for a function
11017 // or function template.
11018 } else if (!SS.getScopeRep()->isDependent()) {
11019 DC = computeDeclContext(SS);
11020 if (!DC) return 0;
11021
11022 if (RequireCompleteDeclContext(SS, DC)) return 0;
11023
11024 LookupQualifiedName(Previous, DC);
11025
11026 // Ignore things found implicitly in the wrong scope.
11027 // TODO: better diagnostics for this case. Suggesting the right
11028 // qualified scope would be nice...
11029 LookupResult::Filter F = Previous.makeFilter();
11030 while (F.hasNext()) {
11031 NamedDecl *D = F.next();
11032 if (!DC->InEnclosingNamespaceSetOf(
11033 D->getDeclContext()->getRedeclContext()))
11034 F.erase();
11035 }
11036 F.done();
11037
11038 if (Previous.empty()) {
11039 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011040 Diag(Loc, diag::err_qualified_friend_not_found)
11041 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011042 return 0;
11043 }
11044
11045 // C++ [class.friend]p1: A friend of a class is a function or
11046 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011047 if (DC->Equals(CurContext))
11048 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011049 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011050 diag::warn_cxx98_compat_friend_is_member :
11051 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011052
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011053 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011054 // C++ [class.friend]p6:
11055 // A function can be defined in a friend declaration of a class if and
11056 // only if the class is a non-local class (9.8), the function name is
11057 // unqualified, and the function has namespace scope.
11058 SemaDiagnosticBuilder DB
11059 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11060
11061 DB << SS.getScopeRep();
11062 if (DC->isFileContext())
11063 DB << FixItHint::CreateRemoval(SS.getRange());
11064 SS.clear();
11065 }
John McCall337ec3d2010-10-12 23:13:28 +000011066
11067 // - There's a scope specifier that does not match any template
11068 // parameter lists, in which case we use some arbitrary context,
11069 // create a method or method template, and wait for instantiation.
11070 // - There's a scope specifier that does match some template
11071 // parameter lists, which we don't handle right now.
11072 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011073 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011074 // C++ [class.friend]p6:
11075 // A function can be defined in a friend declaration of a class if and
11076 // only if the class is a non-local class (9.8), the function name is
11077 // unqualified, and the function has namespace scope.
11078 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11079 << SS.getScopeRep();
11080 }
11081
John McCall337ec3d2010-10-12 23:13:28 +000011082 DC = CurContext;
11083 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011084 }
Douglas Gregor883af832011-10-10 01:11:59 +000011085
John McCall29ae6e52010-10-13 05:45:15 +000011086 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011087 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011088 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11089 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11090 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011091 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011092 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11093 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011094 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011095 }
John McCall67d1a672009-08-06 02:15:43 +000011096 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011097
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011098 // FIXME: This is an egregious hack to cope with cases where the scope stack
11099 // does not contain the declaration context, i.e., in an out-of-line
11100 // definition of a class.
11101 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11102 if (!DCScope) {
11103 FakeDCScope.setEntity(DC);
11104 DCScope = &FakeDCScope;
11105 }
11106
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011107 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011108 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011109 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011110 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011111
Douglas Gregor182ddf02009-09-28 00:08:27 +000011112 assert(ND->getDeclContext() == DC);
11113 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011114
John McCallab88d972009-08-31 22:39:49 +000011115 // Add the function declaration to the appropriate lookup tables,
11116 // adjusting the redeclarations list as necessary. We don't
11117 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011118 //
John McCallab88d972009-08-31 22:39:49 +000011119 // Also update the scope-based lookup if the target context's
11120 // lookup context is in lexical scope.
11121 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011122 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011123 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011124 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011125 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011126 }
John McCall02cace72009-08-28 07:59:38 +000011127
11128 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011129 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011130 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011131 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011132 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011133
John McCall1f2e1a92012-08-10 03:15:35 +000011134 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011135 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011136 } else {
11137 if (DC->isRecord()) CheckFriendAccess(ND);
11138
John McCall6102ca12010-10-16 06:59:13 +000011139 FunctionDecl *FD;
11140 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11141 FD = FTD->getTemplatedDecl();
11142 else
11143 FD = cast<FunctionDecl>(ND);
11144
11145 // Mark templated-scope function declarations as unsupported.
11146 if (FD->getNumTemplateParameterLists())
11147 FrD->setUnsupportedFriend(true);
11148 }
John McCall337ec3d2010-10-12 23:13:28 +000011149
John McCalld226f652010-08-21 09:40:31 +000011150 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011151}
11152
John McCalld226f652010-08-21 09:40:31 +000011153void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11154 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011155
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011156 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011157 if (!Fn) {
11158 Diag(DelLoc, diag::err_deleted_non_function);
11159 return;
11160 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011161
Douglas Gregoref96ee02012-01-14 16:38:05 +000011162 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011163 // Don't consider the implicit declaration we generate for explicit
11164 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011165 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11166 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011167 Diag(DelLoc, diag::err_deleted_decl_not_first);
11168 Diag(Prev->getLocation(), diag::note_previous_declaration);
11169 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011170 // If the declaration wasn't the first, we delete the function anyway for
11171 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011172 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011173 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011174
11175 if (Fn->isDeleted())
11176 return;
11177
11178 // See if we're deleting a function which is already known to override a
11179 // non-deleted virtual function.
11180 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11181 bool IssuedDiagnostic = false;
11182 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11183 E = MD->end_overridden_methods();
11184 I != E; ++I) {
11185 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11186 if (!IssuedDiagnostic) {
11187 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11188 IssuedDiagnostic = true;
11189 }
11190 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11191 }
11192 }
11193 }
11194
Sean Hunt10620eb2011-05-06 20:44:56 +000011195 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011196}
Sebastian Redl13e88542009-04-27 21:33:24 +000011197
Sean Hunte4246a62011-05-12 06:15:49 +000011198void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011199 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011200
11201 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011202 if (MD->getParent()->isDependentType()) {
11203 MD->setDefaulted();
11204 MD->setExplicitlyDefaulted();
11205 return;
11206 }
11207
Sean Hunte4246a62011-05-12 06:15:49 +000011208 CXXSpecialMember Member = getSpecialMember(MD);
11209 if (Member == CXXInvalid) {
11210 Diag(DefaultLoc, diag::err_default_special_members);
11211 return;
11212 }
11213
11214 MD->setDefaulted();
11215 MD->setExplicitlyDefaulted();
11216
Sean Huntcd10dec2011-05-23 23:14:04 +000011217 // If this definition appears within the record, do the checking when
11218 // the record is complete.
11219 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011220 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011221 // Find the uninstantiated declaration that actually had the '= default'
11222 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011223 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011224
Richard Smith12fef492013-03-27 00:22:47 +000011225 // If the method was defaulted on its first declaration, we will have
11226 // already performed the checking in CheckCompletedCXXClass. Such a
11227 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011228 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011229 return;
11230
Richard Smithb9d0b762012-07-27 04:22:15 +000011231 CheckExplicitlyDefaultedSpecialMember(MD);
11232
Richard Smith1d28caf2012-12-11 01:14:52 +000011233 // The exception specification is needed because we are defining the
11234 // function.
11235 ResolveExceptionSpec(DefaultLoc,
11236 MD->getType()->castAs<FunctionProtoType>());
11237
Sean Hunte4246a62011-05-12 06:15:49 +000011238 switch (Member) {
11239 case CXXDefaultConstructor: {
11240 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011241 if (!CD->isInvalidDecl())
11242 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11243 break;
11244 }
11245
11246 case CXXCopyConstructor: {
11247 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011248 if (!CD->isInvalidDecl())
11249 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011250 break;
11251 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011252
Sean Hunt2b188082011-05-14 05:23:28 +000011253 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011254 if (!MD->isInvalidDecl())
11255 DefineImplicitCopyAssignment(DefaultLoc, MD);
11256 break;
11257 }
11258
Sean Huntcb45a0f2011-05-12 22:46:25 +000011259 case CXXDestructor: {
11260 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011261 if (!DD->isInvalidDecl())
11262 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011263 break;
11264 }
11265
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011266 case CXXMoveConstructor: {
11267 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011268 if (!CD->isInvalidDecl())
11269 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011270 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011271 }
Sean Hunt82713172011-05-25 23:16:36 +000011272
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011273 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011274 if (!MD->isInvalidDecl())
11275 DefineImplicitMoveAssignment(DefaultLoc, MD);
11276 break;
11277 }
11278
11279 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011280 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011281 }
11282 } else {
11283 Diag(DefaultLoc, diag::err_default_special_members);
11284 }
11285}
11286
Sebastian Redl13e88542009-04-27 21:33:24 +000011287static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011288 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011289 Stmt *SubStmt = *CI;
11290 if (!SubStmt)
11291 continue;
11292 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011293 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011294 diag::err_return_in_constructor_handler);
11295 if (!isa<Expr>(SubStmt))
11296 SearchForReturnInStmt(Self, SubStmt);
11297 }
11298}
11299
11300void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11301 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11302 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11303 SearchForReturnInStmt(*this, Handler);
11304 }
11305}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011306
David Blaikie299adab2013-01-18 23:03:15 +000011307bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011308 const CXXMethodDecl *Old) {
11309 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11310 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11311
11312 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11313
11314 // If the calling conventions match, everything is fine
11315 if (NewCC == OldCC)
11316 return false;
11317
11318 // If either of the calling conventions are set to "default", we need to pick
11319 // something more sensible based on the target. This supports code where the
11320 // one method explicitly sets thiscall, and another has no explicit calling
11321 // convention.
11322 CallingConv Default =
11323 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11324 if (NewCC == CC_Default)
11325 NewCC = Default;
11326 if (OldCC == CC_Default)
11327 OldCC = Default;
11328
11329 // If the calling conventions still don't match, then report the error
11330 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011331 Diag(New->getLocation(),
11332 diag::err_conflicting_overriding_cc_attributes)
11333 << New->getDeclName() << New->getType() << Old->getType();
11334 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11335 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011336 }
11337
11338 return false;
11339}
11340
Mike Stump1eb44332009-09-09 15:08:12 +000011341bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011342 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011343 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11344 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011345
Chandler Carruth73857792010-02-15 11:53:20 +000011346 if (Context.hasSameType(NewTy, OldTy) ||
11347 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011348 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011349
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011350 // Check if the return types are covariant
11351 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011352
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011353 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011354 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11355 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011356 NewClassTy = NewPT->getPointeeType();
11357 OldClassTy = OldPT->getPointeeType();
11358 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011359 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11360 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11361 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11362 NewClassTy = NewRT->getPointeeType();
11363 OldClassTy = OldRT->getPointeeType();
11364 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011365 }
11366 }
Mike Stump1eb44332009-09-09 15:08:12 +000011367
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011368 // The return types aren't either both pointers or references to a class type.
11369 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011370 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011371 diag::err_different_return_type_for_overriding_virtual_function)
11372 << New->getDeclName() << NewTy << OldTy;
11373 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011374
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011375 return true;
11376 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011377
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011378 // C++ [class.virtual]p6:
11379 // If the return type of D::f differs from the return type of B::f, the
11380 // class type in the return type of D::f shall be complete at the point of
11381 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011382 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11383 if (!RT->isBeingDefined() &&
11384 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011385 diag::err_covariant_return_incomplete,
11386 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011387 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011388 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011389
Douglas Gregora4923eb2009-11-16 21:35:15 +000011390 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011391 // Check if the new class derives from the old class.
11392 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11393 Diag(New->getLocation(),
11394 diag::err_covariant_return_not_derived)
11395 << New->getDeclName() << NewTy << OldTy;
11396 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11397 return true;
11398 }
Mike Stump1eb44332009-09-09 15:08:12 +000011399
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011400 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011401 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011402 diag::err_covariant_return_inaccessible_base,
11403 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11404 // FIXME: Should this point to the return type?
11405 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011406 // FIXME: this note won't trigger for delayed access control
11407 // diagnostics, and it's impossible to get an undelayed error
11408 // here from access control during the original parse because
11409 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011410 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11411 return true;
11412 }
11413 }
Mike Stump1eb44332009-09-09 15:08:12 +000011414
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011415 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011416 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011417 Diag(New->getLocation(),
11418 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011419 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011420 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11421 return true;
11422 };
Mike Stump1eb44332009-09-09 15:08:12 +000011423
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011424
11425 // The new class type must have the same or less qualifiers as the old type.
11426 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11427 Diag(New->getLocation(),
11428 diag::err_covariant_return_type_class_type_more_qualified)
11429 << New->getDeclName() << NewTy << OldTy;
11430 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11431 return true;
11432 };
Mike Stump1eb44332009-09-09 15:08:12 +000011433
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011434 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011435}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011436
Douglas Gregor4ba31362009-12-01 17:24:26 +000011437/// \brief Mark the given method pure.
11438///
11439/// \param Method the method to be marked pure.
11440///
11441/// \param InitRange the source range that covers the "0" initializer.
11442bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011443 SourceLocation EndLoc = InitRange.getEnd();
11444 if (EndLoc.isValid())
11445 Method->setRangeEnd(EndLoc);
11446
Douglas Gregor4ba31362009-12-01 17:24:26 +000011447 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11448 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011449 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011450 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011451
11452 if (!Method->isInvalidDecl())
11453 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11454 << Method->getDeclName() << InitRange;
11455 return true;
11456}
11457
Douglas Gregor552e2992012-02-21 02:22:07 +000011458/// \brief Determine whether the given declaration is a static data member.
11459static bool isStaticDataMember(Decl *D) {
11460 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11461 if (!Var)
11462 return false;
11463
11464 return Var->isStaticDataMember();
11465}
John McCall731ad842009-12-19 09:28:58 +000011466/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11467/// an initializer for the out-of-line declaration 'Dcl'. The scope
11468/// is a fresh scope pushed for just this purpose.
11469///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011470/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11471/// static data member of class X, names should be looked up in the scope of
11472/// class X.
John McCalld226f652010-08-21 09:40:31 +000011473void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011474 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011475 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011476
John McCall731ad842009-12-19 09:28:58 +000011477 // We should only get called for declarations with scope specifiers, like:
11478 // int foo::bar;
11479 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011480 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011481
11482 // If we are parsing the initializer for a static data member, push a
11483 // new expression evaluation context that is associated with this static
11484 // data member.
11485 if (isStaticDataMember(D))
11486 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011487}
11488
11489/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011490/// initializer for the out-of-line declaration 'D'.
11491void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011492 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011493 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011494
Douglas Gregor552e2992012-02-21 02:22:07 +000011495 if (isStaticDataMember(D))
11496 PopExpressionEvaluationContext();
11497
John McCall731ad842009-12-19 09:28:58 +000011498 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011499 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011500}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011501
11502/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11503/// C++ if/switch/while/for statement.
11504/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011505DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011506 // C++ 6.4p2:
11507 // The declarator shall not specify a function or an array.
11508 // The type-specifier-seq shall not contain typedef and shall not declare a
11509 // new class or enumeration.
11510 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11511 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011512
11513 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011514 if (!Dcl)
11515 return true;
11516
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011517 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11518 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011519 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011520 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011521 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011522
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011523 return Dcl;
11524}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011525
Douglas Gregordfe65432011-07-28 19:11:31 +000011526void Sema::LoadExternalVTableUses() {
11527 if (!ExternalSource)
11528 return;
11529
11530 SmallVector<ExternalVTableUse, 4> VTables;
11531 ExternalSource->ReadUsedVTables(VTables);
11532 SmallVector<VTableUse, 4> NewUses;
11533 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11534 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11535 = VTablesUsed.find(VTables[I].Record);
11536 // Even if a definition wasn't required before, it may be required now.
11537 if (Pos != VTablesUsed.end()) {
11538 if (!Pos->second && VTables[I].DefinitionRequired)
11539 Pos->second = true;
11540 continue;
11541 }
11542
11543 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11544 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11545 }
11546
11547 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11548}
11549
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011550void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11551 bool DefinitionRequired) {
11552 // Ignore any vtable uses in unevaluated operands or for classes that do
11553 // not have a vtable.
11554 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11555 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011556 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011557 return;
11558
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011559 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011560 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011561 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11562 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11563 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11564 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011565 // If we already had an entry, check to see if we are promoting this vtable
11566 // to required a definition. If so, we need to reappend to the VTableUses
11567 // list, since we may have already processed the first entry.
11568 if (DefinitionRequired && !Pos.first->second) {
11569 Pos.first->second = true;
11570 } else {
11571 // Otherwise, we can early exit.
11572 return;
11573 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011574 }
11575
11576 // Local classes need to have their virtual members marked
11577 // immediately. For all other classes, we mark their virtual members
11578 // at the end of the translation unit.
11579 if (Class->isLocalClass())
11580 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011581 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011582 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011583}
11584
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011585bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011586 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011587 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011588 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011589
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011590 // Note: The VTableUses vector could grow as a result of marking
11591 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011592 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011593 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011594 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011595 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011596 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011597 if (!Class)
11598 continue;
11599
11600 SourceLocation Loc = VTableUses[I].second;
11601
Richard Smithb9d0b762012-07-27 04:22:15 +000011602 bool DefineVTable = true;
11603
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011604 // If this class has a key function, but that key function is
11605 // defined in another translation unit, we don't need to emit the
11606 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011607 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011608 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011609 switch (KeyFunction->getTemplateSpecializationKind()) {
11610 case TSK_Undeclared:
11611 case TSK_ExplicitSpecialization:
11612 case TSK_ExplicitInstantiationDeclaration:
11613 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011614 DefineVTable = false;
11615 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011616
11617 case TSK_ExplicitInstantiationDefinition:
11618 case TSK_ImplicitInstantiation:
11619 // We will be instantiating the key function.
11620 break;
11621 }
11622 } else if (!KeyFunction) {
11623 // If we have a class with no key function that is the subject
11624 // of an explicit instantiation declaration, suppress the
11625 // vtable; it will live with the explicit instantiation
11626 // definition.
11627 bool IsExplicitInstantiationDeclaration
11628 = Class->getTemplateSpecializationKind()
11629 == TSK_ExplicitInstantiationDeclaration;
11630 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11631 REnd = Class->redecls_end();
11632 R != REnd; ++R) {
11633 TemplateSpecializationKind TSK
11634 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11635 if (TSK == TSK_ExplicitInstantiationDeclaration)
11636 IsExplicitInstantiationDeclaration = true;
11637 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11638 IsExplicitInstantiationDeclaration = false;
11639 break;
11640 }
11641 }
11642
11643 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011644 DefineVTable = false;
11645 }
11646
11647 // The exception specifications for all virtual members may be needed even
11648 // if we are not providing an authoritative form of the vtable in this TU.
11649 // We may choose to emit it available_externally anyway.
11650 if (!DefineVTable) {
11651 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11652 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011653 }
11654
11655 // Mark all of the virtual members of this class as referenced, so
11656 // that we can build a vtable. Then, tell the AST consumer that a
11657 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011658 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011659 MarkVirtualMembersReferenced(Loc, Class);
11660 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11661 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11662
11663 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola531db822013-03-07 02:00:27 +000011664 if (Class->hasExternalLinkage() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011665 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011666 const FunctionDecl *KeyFunctionDef = 0;
11667 if (!KeyFunction ||
11668 (KeyFunction->hasBody(KeyFunctionDef) &&
11669 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011670 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11671 TSK_ExplicitInstantiationDefinition
11672 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11673 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011674 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011675 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011676 VTableUses.clear();
11677
Douglas Gregor78844032011-04-22 22:25:37 +000011678 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011679}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011680
Richard Smithb9d0b762012-07-27 04:22:15 +000011681void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11682 const CXXRecordDecl *RD) {
11683 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11684 E = RD->method_end(); I != E; ++I)
11685 if ((*I)->isVirtual() && !(*I)->isPure())
11686 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11687}
11688
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011689void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11690 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011691 // Mark all functions which will appear in RD's vtable as used.
11692 CXXFinalOverriderMap FinalOverriders;
11693 RD->getFinalOverriders(FinalOverriders);
11694 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11695 E = FinalOverriders.end();
11696 I != E; ++I) {
11697 for (OverridingMethods::const_iterator OI = I->second.begin(),
11698 OE = I->second.end();
11699 OI != OE; ++OI) {
11700 assert(OI->second.size() > 0 && "no final overrider");
11701 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011702
Richard Smithff817f72012-07-07 06:59:51 +000011703 // C++ [basic.def.odr]p2:
11704 // [...] A virtual member function is used if it is not pure. [...]
11705 if (!Overrider->isPure())
11706 MarkFunctionReferenced(Loc, Overrider);
11707 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011708 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011709
11710 // Only classes that have virtual bases need a VTT.
11711 if (RD->getNumVBases() == 0)
11712 return;
11713
11714 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11715 e = RD->bases_end(); i != e; ++i) {
11716 const CXXRecordDecl *Base =
11717 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011718 if (Base->getNumVBases() == 0)
11719 continue;
11720 MarkVirtualMembersReferenced(Loc, Base);
11721 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011722}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011723
11724/// SetIvarInitializers - This routine builds initialization ASTs for the
11725/// Objective-C implementation whose ivars need be initialized.
11726void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011727 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011728 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011729 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011730 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011731 CollectIvarsToConstructOrDestruct(OID, ivars);
11732 if (ivars.empty())
11733 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011734 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011735 for (unsigned i = 0; i < ivars.size(); i++) {
11736 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011737 if (Field->isInvalidDecl())
11738 continue;
11739
Sean Huntcbb67482011-01-08 20:30:50 +000011740 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011741 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11742 InitializationKind InitKind =
11743 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11744
11745 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011746 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011747 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011748 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011749 // Note, MemberInit could actually come back empty if no initialization
11750 // is required (e.g., because it would call a trivial default constructor)
11751 if (!MemberInit.get() || MemberInit.isInvalid())
11752 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011753
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011754 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011755 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11756 SourceLocation(),
11757 MemberInit.takeAs<Expr>(),
11758 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011759 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011760
11761 // Be sure that the destructor is accessible and is marked as referenced.
11762 if (const RecordType *RecordTy
11763 = Context.getBaseElementType(Field->getType())
11764 ->getAs<RecordType>()) {
11765 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011766 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011767 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011768 CheckDestructorAccess(Field->getLocation(), Destructor,
11769 PDiag(diag::err_access_dtor_ivar)
11770 << Context.getBaseElementType(Field->getType()));
11771 }
11772 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011773 }
11774 ObjCImplementation->setIvarInitializers(Context,
11775 AllToInit.data(), AllToInit.size());
11776 }
11777}
Sean Huntfe57eef2011-05-04 05:57:24 +000011778
Sean Huntebcbe1d2011-05-04 23:29:54 +000011779static
11780void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11781 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11782 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11783 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11784 Sema &S) {
11785 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11786 CE = Current.end();
11787 if (Ctor->isInvalidDecl())
11788 return;
11789
Richard Smitha8eaf002012-08-23 06:16:52 +000011790 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11791
11792 // Target may not be determinable yet, for instance if this is a dependent
11793 // call in an uninstantiated template.
11794 if (Target) {
11795 const FunctionDecl *FNTarget = 0;
11796 (void)Target->hasBody(FNTarget);
11797 Target = const_cast<CXXConstructorDecl*>(
11798 cast_or_null<CXXConstructorDecl>(FNTarget));
11799 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011800
11801 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11802 // Avoid dereferencing a null pointer here.
11803 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11804
11805 if (!Current.insert(Canonical))
11806 return;
11807
11808 // We know that beyond here, we aren't chaining into a cycle.
11809 if (!Target || !Target->isDelegatingConstructor() ||
11810 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11811 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11812 Valid.insert(*CI);
11813 Current.clear();
11814 // We've hit a cycle.
11815 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11816 Current.count(TCanonical)) {
11817 // If we haven't diagnosed this cycle yet, do so now.
11818 if (!Invalid.count(TCanonical)) {
11819 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011820 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011821 << Ctor;
11822
Richard Smitha8eaf002012-08-23 06:16:52 +000011823 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011824 if (TCanonical != Canonical)
11825 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11826
11827 CXXConstructorDecl *C = Target;
11828 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011829 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011830 (void)C->getTargetConstructor()->hasBody(FNTarget);
11831 assert(FNTarget && "Ctor cycle through bodiless function");
11832
Richard Smitha8eaf002012-08-23 06:16:52 +000011833 C = const_cast<CXXConstructorDecl*>(
11834 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011835 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11836 }
11837 }
11838
11839 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11840 Invalid.insert(*CI);
11841 Current.clear();
11842 } else {
11843 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11844 }
11845}
11846
11847
Sean Huntfe57eef2011-05-04 05:57:24 +000011848void Sema::CheckDelegatingCtorCycles() {
11849 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11850
Sean Huntebcbe1d2011-05-04 23:29:54 +000011851 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11852 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011853
Douglas Gregor0129b562011-07-27 21:57:17 +000011854 for (DelegatingCtorDeclsType::iterator
11855 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011856 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011857 I != E; ++I)
11858 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011859
11860 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11861 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011862}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011863
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011864namespace {
11865 /// \brief AST visitor that finds references to the 'this' expression.
11866 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11867 Sema &S;
11868
11869 public:
11870 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11871
11872 bool VisitCXXThisExpr(CXXThisExpr *E) {
11873 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11874 << E->isImplicit();
11875 return false;
11876 }
11877 };
11878}
11879
11880bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11881 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11882 if (!TSInfo)
11883 return false;
11884
11885 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011886 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011887 if (!ProtoTL)
11888 return false;
11889
11890 // C++11 [expr.prim.general]p3:
11891 // [The expression this] shall not appear before the optional
11892 // cv-qualifier-seq and it shall not appear within the declaration of a
11893 // static member function (although its type and value category are defined
11894 // within a static member function as they are within a non-static member
11895 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011896 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000011897 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011898 FindCXXThisExpr Finder(*this);
11899
11900 // If the return type came after the cv-qualifier-seq, check it now.
11901 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000011902 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011903 return true;
11904
11905 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011906 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11907 return true;
11908
11909 return checkThisInStaticMemberFunctionAttributes(Method);
11910}
11911
11912bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11913 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11914 if (!TSInfo)
11915 return false;
11916
11917 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011918 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011919 if (!ProtoTL)
11920 return false;
11921
David Blaikie39e6ab42013-02-18 22:06:02 +000011922 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011923 FindCXXThisExpr Finder(*this);
11924
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011925 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011926 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011927 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011928 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011929 case EST_DynamicNone:
11930 case EST_MSAny:
11931 case EST_None:
11932 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011933
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011934 case EST_ComputedNoexcept:
11935 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11936 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011937
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011938 case EST_Dynamic:
11939 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011940 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011941 E != EEnd; ++E) {
11942 if (!Finder.TraverseType(*E))
11943 return true;
11944 }
11945 break;
11946 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011947
11948 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011949}
11950
11951bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11952 FindCXXThisExpr Finder(*this);
11953
11954 // Check attributes.
11955 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11956 A != AEnd; ++A) {
11957 // FIXME: This should be emitted by tblgen.
11958 Expr *Arg = 0;
11959 ArrayRef<Expr *> Args;
11960 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11961 Arg = G->getArg();
11962 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11963 Arg = G->getArg();
11964 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11965 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11966 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11967 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11968 else if (ExclusiveLockFunctionAttr *ELF
11969 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11970 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11971 else if (SharedLockFunctionAttr *SLF
11972 = dyn_cast<SharedLockFunctionAttr>(*A))
11973 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11974 else if (ExclusiveTrylockFunctionAttr *ETLF
11975 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11976 Arg = ETLF->getSuccessValue();
11977 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11978 } else if (SharedTrylockFunctionAttr *STLF
11979 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11980 Arg = STLF->getSuccessValue();
11981 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11982 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11983 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11984 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11985 Arg = LR->getArg();
11986 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11987 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11988 else if (ExclusiveLocksRequiredAttr *ELR
11989 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11990 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11991 else if (SharedLocksRequiredAttr *SLR
11992 = dyn_cast<SharedLocksRequiredAttr>(*A))
11993 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11994
11995 if (Arg && !Finder.TraverseStmt(Arg))
11996 return true;
11997
11998 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11999 if (!Finder.TraverseStmt(Args[I]))
12000 return true;
12001 }
12002 }
12003
12004 return false;
12005}
12006
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012007void
12008Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12009 ArrayRef<ParsedType> DynamicExceptions,
12010 ArrayRef<SourceRange> DynamicExceptionRanges,
12011 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012012 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012013 FunctionProtoType::ExtProtoInfo &EPI) {
12014 Exceptions.clear();
12015 EPI.ExceptionSpecType = EST;
12016 if (EST == EST_Dynamic) {
12017 Exceptions.reserve(DynamicExceptions.size());
12018 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12019 // FIXME: Preserve type source info.
12020 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12021
12022 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12023 collectUnexpandedParameterPacks(ET, Unexpanded);
12024 if (!Unexpanded.empty()) {
12025 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12026 UPPC_ExceptionType,
12027 Unexpanded);
12028 continue;
12029 }
12030
12031 // Check that the type is valid for an exception spec, and
12032 // drop it if not.
12033 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12034 Exceptions.push_back(ET);
12035 }
12036 EPI.NumExceptions = Exceptions.size();
12037 EPI.Exceptions = Exceptions.data();
12038 return;
12039 }
12040
12041 if (EST == EST_ComputedNoexcept) {
12042 // If an error occurred, there's no expression here.
12043 if (NoexceptExpr) {
12044 assert((NoexceptExpr->isTypeDependent() ||
12045 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12046 Context.BoolTy) &&
12047 "Parser should have made sure that the expression is boolean");
12048 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12049 EPI.ExceptionSpecType = EST_BasicNoexcept;
12050 return;
12051 }
12052
12053 if (!NoexceptExpr->isValueDependent())
12054 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012055 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012056 /*AllowFold*/ false).take();
12057 EPI.NoexceptExpr = NoexceptExpr;
12058 }
12059 return;
12060 }
12061}
12062
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012063/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12064Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12065 // Implicitly declared functions (e.g. copy constructors) are
12066 // __host__ __device__
12067 if (D->isImplicit())
12068 return CFT_HostDevice;
12069
12070 if (D->hasAttr<CUDAGlobalAttr>())
12071 return CFT_Global;
12072
12073 if (D->hasAttr<CUDADeviceAttr>()) {
12074 if (D->hasAttr<CUDAHostAttr>())
12075 return CFT_HostDevice;
12076 else
12077 return CFT_Device;
12078 }
12079
12080 return CFT_Host;
12081}
12082
12083bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12084 CUDAFunctionTarget CalleeTarget) {
12085 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12086 // Callable from the device only."
12087 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12088 return true;
12089
12090 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12091 // Callable from the host only."
12092 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12093 // Callable from the host only."
12094 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12095 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12096 return true;
12097
12098 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12099 return true;
12100
12101 return false;
12102}
John McCall76da55d2013-04-16 07:28:30 +000012103
12104/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12105///
12106MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12107 SourceLocation DeclStart,
12108 Declarator &D, Expr *BitWidth,
12109 InClassInitStyle InitStyle,
12110 AccessSpecifier AS,
12111 AttributeList *MSPropertyAttr) {
12112 IdentifierInfo *II = D.getIdentifier();
12113 if (!II) {
12114 Diag(DeclStart, diag::err_anonymous_property);
12115 return NULL;
12116 }
12117 SourceLocation Loc = D.getIdentifierLoc();
12118
12119 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12120 QualType T = TInfo->getType();
12121 if (getLangOpts().CPlusPlus) {
12122 CheckExtraCXXDefaultArguments(D);
12123
12124 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12125 UPPC_DataMemberType)) {
12126 D.setInvalidType();
12127 T = Context.IntTy;
12128 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12129 }
12130 }
12131
12132 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12133
12134 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12135 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12136 diag::err_invalid_thread)
12137 << DeclSpec::getSpecifierName(TSCS);
12138
12139 // Check to see if this name was declared as a member previously
12140 NamedDecl *PrevDecl = 0;
12141 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12142 LookupName(Previous, S);
12143 switch (Previous.getResultKind()) {
12144 case LookupResult::Found:
12145 case LookupResult::FoundUnresolvedValue:
12146 PrevDecl = Previous.getAsSingle<NamedDecl>();
12147 break;
12148
12149 case LookupResult::FoundOverloaded:
12150 PrevDecl = Previous.getRepresentativeDecl();
12151 break;
12152
12153 case LookupResult::NotFound:
12154 case LookupResult::NotFoundInCurrentInstantiation:
12155 case LookupResult::Ambiguous:
12156 break;
12157 }
12158
12159 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12160 // Maybe we will complain about the shadowed template parameter.
12161 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12162 // Just pretend that we didn't see the previous declaration.
12163 PrevDecl = 0;
12164 }
12165
12166 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12167 PrevDecl = 0;
12168
12169 SourceLocation TSSL = D.getLocStart();
12170 MSPropertyDecl *NewPD;
12171 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12172 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12173 II, T, TInfo, TSSL,
12174 Data.GetterId, Data.SetterId);
12175 ProcessDeclAttributes(TUScope, NewPD, D);
12176 NewPD->setAccess(AS);
12177
12178 if (NewPD->isInvalidDecl())
12179 Record->setInvalidDecl();
12180
12181 if (D.getDeclSpec().isModulePrivateSpecified())
12182 NewPD->setModulePrivate();
12183
12184 if (NewPD->isInvalidDecl() && PrevDecl) {
12185 // Don't introduce NewFD into scope; there's already something
12186 // with the same name in the same scope.
12187 } else if (II) {
12188 PushOnScopeChains(NewPD, S);
12189 } else
12190 Record->addDecl(NewPD);
12191
12192 return NewPD;
12193}