blob: 1c21b2cf2049d07077243c1ee1dccf9153025c68 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000068 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000069 };
Chris Lattner8123a952008-04-10 02:22:51 +000070
Chris Lattner9e979552008-04-12 23:52:44 +000071 /// VisitExpr - Visit all of the children of this expression.
72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000074 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000075 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000076 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000077 }
78
Chris Lattner9e979552008-04-12 23:52:44 +000079 /// VisitDeclRefExpr - Visit a reference to a declaration, to
80 /// determine whether this declaration can be used in the default
81 /// argument expression.
82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000084 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85 // C++ [dcl.fct.default]p9
86 // Default arguments are evaluated each time the function is
87 // called. The order of evaluation of function arguments is
88 // unspecified. Consequently, parameters of a function shall not
89 // be used in default argument expressions, even if they are not
90 // evaluated. Parameters of a function declared before a default
91 // argument expression are in scope and can hide namespace and
92 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000093 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000096 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000097 // C++ [dcl.fct.default]p7
98 // Local variables shall not be used in default argument
99 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000100 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000101 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000103 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105
Douglas Gregor3996f232008-11-04 13:41:56 +0000106 return false;
107 }
Chris Lattner9e979552008-04-12 23:52:44 +0000108
Douglas Gregor796da182008-11-04 14:32:21 +0000109 /// VisitCXXThisExpr - Visit a C++ "this" expression.
110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111 // C++ [dcl.fct.default]p8:
112 // The keyword this shall not be used in a default argument of a
113 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000114 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 diag::err_param_default_argument_references_this)
116 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000117 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000118
John McCall045d2522013-04-09 01:56:28 +0000119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120 bool Invalid = false;
121 for (PseudoObjectExpr::semantics_iterator
122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123 Expr *E = *i;
124
125 // Look through bindings.
126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127 E = OVE->getSourceExpr();
128 assert(E && "pseudo-object binding without source expression?");
129 }
130
131 Invalid |= Visit(E);
132 }
133 return Invalid;
134 }
135
Douglas Gregorf0459f82012-02-10 23:30:22 +0000136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137 // C++11 [expr.lambda.prim]p13:
138 // A lambda-expression appearing in a default argument shall not
139 // implicitly or explicitly capture any entity.
140 if (Lambda->capture_begin() == Lambda->capture_end())
141 return false;
142
143 return S->Diag(Lambda->getLocStart(),
144 diag::err_lambda_capture_default_arg);
145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146}
147
Richard Smith0b0ca472013-04-10 06:11:48 +0000148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000151 // If we have an MSAny spec already, don't bother.
152 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000153 return;
154
155 const FunctionProtoType *Proto
156 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158 if (!Proto)
159 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000160
161 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000164 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000165 ClearExceptions();
166 ComputedEST = EST;
167 return;
168 }
169
Richard Smith7a614d82011-06-11 17:19:42 +0000170 // FIXME: If the call to this decl is using any of its default arguments, we
171 // need to search them for potentially-throwing calls.
172
Sean Hunt001cad92011-05-10 00:49:42 +0000173 // If this function has a basic noexcept, it doesn't affect the outcome.
174 if (EST == EST_BasicNoexcept)
175 return;
176
177 // If we have a throw-all spec at this point, ignore the function.
178 if (ComputedEST == EST_None)
179 return;
180
181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
183 if (EST == EST_DynamicNone) {
184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
187 }
188
189 // Check out noexcept specs.
190 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
198
199 // noexcept(false) -> no spec on the new function
200 if (NR == FunctionProtoType::NR_Throw) {
201 ClearExceptions();
202 ComputedEST = EST_None;
203 }
204 // noexcept(true) won't change anything either.
205 return;
206 }
207
208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214 EEnd = Proto->exception_end();
215 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000217 Exceptions.push_back(*E);
218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson5e300d12009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000359}
360
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
398 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000403 }
404 }
405}
406
David Majnemerf6a144f2013-06-25 23:09:30 +0000407static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
408 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
409 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
410 if (!PVD->hasDefaultArg())
411 return false;
412 if (!PVD->hasInheritedDefaultArg())
413 return true;
414 }
415 return false;
416}
417
Craig Topper1a6eac82012-09-21 04:33:26 +0000418/// MergeCXXFunctionDecl - Merge two declarations of the same C++
419/// function, once we already know that they have the same
420/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
421/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000422bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
423 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000424 bool Invalid = false;
425
Chris Lattner3d1cee32008-04-08 05:04:30 +0000426 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000427 // For non-template functions, default arguments can be added in
428 // later declarations of a function in the same
429 // scope. Declarations in different scopes have completely
430 // distinct sets of default arguments. That is, declarations in
431 // inner scopes do not acquire default arguments from
432 // declarations in outer scopes, and vice versa. In a given
433 // function declaration, all parameters subsequent to a
434 // parameter with a default argument shall have default
435 // arguments supplied in this or previous declarations. A
436 // default argument shall not be redefined by a later
437 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000438 //
439 // C++ [dcl.fct.default]p6:
440 // Except for member functions of class templates, the default arguments
441 // in a member function definition that appears outside of the class
442 // definition are added to the set of default arguments provided by the
443 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000444 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
445 ParmVarDecl *OldParam = Old->getParamDecl(p);
446 ParmVarDecl *NewParam = New->getParamDecl(p);
447
James Molloy9cda03f2012-03-13 08:55:35 +0000448 bool OldParamHasDfl = OldParam->hasDefaultArg();
449 bool NewParamHasDfl = NewParam->hasDefaultArg();
450
451 NamedDecl *ND = Old;
452 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
453 // Ignore default parameters of old decl if they are not in
454 // the same scope.
455 OldParamHasDfl = false;
456
457 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000458
Francois Pichet8d051e02011-04-10 03:03:52 +0000459 unsigned DiagDefaultParamID =
460 diag::err_param_default_argument_redefinition;
461
462 // MSVC accepts that default parameters be redefined for member functions
463 // of template class. The new default parameter's value is ignored.
464 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000465 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000466 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
467 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000468 // Merge the old default argument into the new parameter.
469 NewParam->setHasInheritedDefaultArg();
470 if (OldParam->hasUninstantiatedDefaultArg())
471 NewParam->setUninstantiatedDefaultArg(
472 OldParam->getUninstantiatedDefaultArg());
473 else
474 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000475 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000476 Invalid = false;
477 }
478 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000479
Francois Pichet8cf90492011-04-10 04:58:30 +0000480 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
481 // hint here. Alternatively, we could walk the type-source information
482 // for NewParam to find the last source location in the type... but it
483 // isn't worth the effort right now. This is the kind of test case that
484 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000485 // int f(int);
486 // void g(int (*fp)(int) = f);
487 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000488 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000489 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000490
491 // Look for the function declaration where the default argument was
492 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000493 for (FunctionDecl *Older = Old->getPreviousDecl();
494 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000495 if (!Older->getParamDecl(p)->hasDefaultArg())
496 break;
497
498 OldParam = Older->getParamDecl(p);
499 }
500
501 Diag(OldParam->getLocation(), diag::note_previous_definition)
502 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000503 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000504 // Merge the old default argument into the new parameter.
505 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000506 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000507 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000508 if (OldParam->hasUninstantiatedDefaultArg())
509 NewParam->setUninstantiatedDefaultArg(
510 OldParam->getUninstantiatedDefaultArg());
511 else
John McCall3d6c1782010-05-04 01:53:42 +0000512 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000513 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000514 if (New->getDescribedFunctionTemplate()) {
515 // Paragraph 4, quoted above, only applies to non-template functions.
516 Diag(NewParam->getLocation(),
517 diag::err_param_default_argument_template_redecl)
518 << NewParam->getDefaultArgRange();
519 Diag(Old->getLocation(), diag::note_template_prev_declaration)
520 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000521 } else if (New->getTemplateSpecializationKind()
522 != TSK_ImplicitInstantiation &&
523 New->getTemplateSpecializationKind() != TSK_Undeclared) {
524 // C++ [temp.expr.spec]p21:
525 // Default function arguments shall not be specified in a declaration
526 // or a definition for one of the following explicit specializations:
527 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000528 // - the explicit specialization of a member function template;
529 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000530 // template where the class template specialization to which the
531 // member function specialization belongs is implicitly
532 // instantiated.
533 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
534 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
535 << New->getDeclName()
536 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000537 } else if (New->getDeclContext()->isDependentContext()) {
538 // C++ [dcl.fct.default]p6 (DR217):
539 // Default arguments for a member function of a class template shall
540 // be specified on the initial declaration of the member function
541 // within the class template.
542 //
543 // Reading the tea leaves a bit in DR217 and its reference to DR205
544 // leads me to the conclusion that one cannot add default function
545 // arguments for an out-of-line definition of a member function of a
546 // dependent type.
547 int WhichKind = 2;
548 if (CXXRecordDecl *Record
549 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
550 if (Record->getDescribedClassTemplate())
551 WhichKind = 0;
552 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
553 WhichKind = 1;
554 else
555 WhichKind = 2;
556 }
557
558 Diag(NewParam->getLocation(),
559 diag::err_param_default_argument_member_template_redecl)
560 << WhichKind
561 << NewParam->getDefaultArgRange();
562 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000563 }
564 }
565
Richard Smithb8abff62012-11-28 03:45:24 +0000566 // DR1344: If a default argument is added outside a class definition and that
567 // default argument makes the function a special member function, the program
568 // is ill-formed. This can only happen for constructors.
569 if (isa<CXXConstructorDecl>(New) &&
570 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
571 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
572 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
573 if (NewSM != OldSM) {
574 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
575 assert(NewParam->hasDefaultArg());
576 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
577 << NewParam->getDefaultArgRange() << NewSM;
578 Diag(Old->getLocation(), diag::note_previous_declaration);
579 }
580 }
581
Richard Smithff234882012-02-20 23:28:05 +0000582 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000583 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000584 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000585 if (New->isConstexpr() != Old->isConstexpr()) {
586 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
587 << New << New->isConstexpr();
588 Diag(Old->getLocation(), diag::note_previous_declaration);
589 Invalid = true;
590 }
591
David Majnemerf6a144f2013-06-25 23:09:30 +0000592 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
593 // argument expression, that declaration shall be a definition and shall be
594 // the only declaration of the function or function template in the
595 // translation unit.
596 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
597 functionDeclHasDefaultArgument(Old)) {
598 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
599 Diag(Old->getLocation(), diag::note_previous_declaration);
600 Invalid = true;
601 }
602
Douglas Gregore13ad832010-02-12 07:32:17 +0000603 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000604 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000605
Douglas Gregorcda9c672009-02-16 17:45:42 +0000606 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000607}
608
Sebastian Redl60618fa2011-03-12 11:50:43 +0000609/// \brief Merge the exception specifications of two variable declarations.
610///
611/// This is called when there's a redeclaration of a VarDecl. The function
612/// checks if the redeclaration might have an exception specification and
613/// validates compatibility and merges the specs if necessary.
614void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
615 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000616 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000617 return;
618
619 assert(Context.hasSameType(New->getType(), Old->getType()) &&
620 "Should only be called if types are otherwise the same.");
621
622 QualType NewType = New->getType();
623 QualType OldType = Old->getType();
624
625 // We're only interested in pointers and references to functions, as well
626 // as pointers to member functions.
627 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
628 NewType = R->getPointeeType();
629 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
630 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
631 NewType = P->getPointeeType();
632 OldType = OldType->getAs<PointerType>()->getPointeeType();
633 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
634 NewType = M->getPointeeType();
635 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
636 }
637
638 if (!NewType->isFunctionProtoType())
639 return;
640
641 // There's lots of special cases for functions. For function pointers, system
642 // libraries are hopefully not as broken so that we don't need these
643 // workarounds.
644 if (CheckEquivalentExceptionSpec(
645 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
646 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
647 New->setInvalidDecl();
648 }
649}
650
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651/// CheckCXXDefaultArguments - Verify that the default arguments for a
652/// function declaration are well-formed according to C++
653/// [dcl.fct.default].
654void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
655 unsigned NumParams = FD->getNumParams();
656 unsigned p;
657
658 // Find first parameter with a default argument
659 for (p = 0; p < NumParams; ++p) {
660 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000661 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000662 break;
663 }
664
665 // C++ [dcl.fct.default]p4:
666 // In a given function declaration, all parameters
667 // subsequent to a parameter with a default argument shall
668 // have default arguments supplied in this or previous
669 // declarations. A default argument shall not be redefined
670 // by a later declaration (not even to the same value).
671 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000672 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000674 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000675 if (Param->isInvalidDecl())
676 /* We already complained about this parameter. */;
677 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000678 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000679 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000680 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000681 else
Mike Stump1eb44332009-09-09 15:08:12 +0000682 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000683 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Chris Lattner3d1cee32008-04-08 05:04:30 +0000685 LastMissingDefaultArg = p;
686 }
687 }
688
689 if (LastMissingDefaultArg > 0) {
690 // Some default arguments were missing. Clear out all of the
691 // default arguments up to (and including) the last missing
692 // default argument, so that we leave the function parameters
693 // in a semantically valid state.
694 for (p = 0; p <= LastMissingDefaultArg; ++p) {
695 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000696 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000697 Param->setDefaultArg(0);
698 }
699 }
700 }
701}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000702
Richard Smith9f569cc2011-10-01 02:31:28 +0000703// CheckConstexprParameterTypes - Check whether a function's parameter types
704// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000705// diagnostic and return false.
706static bool CheckConstexprParameterTypes(Sema &SemaRef,
707 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000708 unsigned ArgIndex = 0;
709 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
710 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
711 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
712 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
713 SourceLocation ParamLoc = PD->getLocation();
714 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000715 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000716 diag::err_constexpr_non_literal_param,
717 ArgIndex+1, PD->getSourceRange(),
718 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000719 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000720 }
Joao Matos17d35c32012-08-31 22:18:20 +0000721 return true;
722}
723
724/// \brief Get diagnostic %select index for tag kind for
725/// record diagnostic message.
726/// WARNING: Indexes apply to particular diagnostics only!
727///
728/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000729static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000730 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000731 case TTK_Struct: return 0;
732 case TTK_Interface: return 1;
733 case TTK_Class: return 2;
734 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000735 }
Joao Matos17d35c32012-08-31 22:18:20 +0000736}
737
738// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
739// the requirements of a constexpr function definition or a constexpr
740// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000741// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000742//
Richard Smith86c3ae42012-02-13 03:54:03 +0000743// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
744bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000745 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
746 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000747 // C++11 [dcl.constexpr]p4:
748 // The definition of a constexpr constructor shall satisfy the following
749 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000750 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000751 const CXXRecordDecl *RD = MD->getParent();
752 if (RD->getNumVBases()) {
753 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
754 << isa<CXXConstructorDecl>(NewFD)
755 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
756 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
757 E = RD->vbases_end(); I != E; ++I)
758 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000759 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000760 return false;
761 }
Richard Smith35340502012-01-13 04:54:00 +0000762 }
763
764 if (!isa<CXXConstructorDecl>(NewFD)) {
765 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000766 // The definition of a constexpr function shall satisfy the following
767 // constraints:
768 // - it shall not be virtual;
769 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
770 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000772
Richard Smith86c3ae42012-02-13 03:54:03 +0000773 // If it's not obvious why this function is virtual, find an overridden
774 // function which uses the 'virtual' keyword.
775 const CXXMethodDecl *WrittenVirtual = Method;
776 while (!WrittenVirtual->isVirtualAsWritten())
777 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
778 if (WrittenVirtual != Method)
779 Diag(WrittenVirtual->getLocation(),
780 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000781 return false;
782 }
783
784 // - its return type shall be a literal type;
785 QualType RT = NewFD->getResultType();
786 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000787 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000788 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000789 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000790 }
791
Richard Smith35340502012-01-13 04:54:00 +0000792 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000793 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000794 return false;
795
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 return true;
797}
798
799/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000800/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000801///
Richard Smitha10b9782013-04-22 15:31:51 +0000802/// \return true if the body is OK (maybe only as an extension), false if we
803/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000804static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000805 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
806 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000807 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
808 // contain only
809 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
810 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
811 switch ((*DclIt)->getKind()) {
812 case Decl::StaticAssert:
813 case Decl::Using:
814 case Decl::UsingShadow:
815 case Decl::UsingDirective:
816 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000817 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000818 // - static_assert-declarations
819 // - using-declarations,
820 // - using-directives,
821 continue;
822
823 case Decl::Typedef:
824 case Decl::TypeAlias: {
825 // - typedef declarations and alias-declarations that do not define
826 // classes or enumerations,
827 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
828 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
829 // Don't allow variably-modified types in constexpr functions.
830 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
831 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
832 << TL.getSourceRange() << TL.getType()
833 << isa<CXXConstructorDecl>(Dcl);
834 return false;
835 }
836 continue;
837 }
838
839 case Decl::Enum:
840 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000841 // C++1y allows types to be defined, not just declared.
842 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
843 SemaRef.Diag(DS->getLocStart(),
844 SemaRef.getLangOpts().CPlusPlus1y
845 ? diag::warn_cxx11_compat_constexpr_type_definition
846 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000847 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000848 continue;
849
Richard Smitha10b9782013-04-22 15:31:51 +0000850 case Decl::EnumConstant:
851 case Decl::IndirectField:
852 case Decl::ParmVar:
853 // These can only appear with other declarations which are banned in
854 // C++11 and permitted in C++1y, so ignore them.
855 continue;
856
857 case Decl::Var: {
858 // C++1y [dcl.constexpr]p3 allows anything except:
859 // a definition of a variable of non-literal type or of static or
860 // thread storage duration or for which no initialization is performed.
861 VarDecl *VD = cast<VarDecl>(*DclIt);
862 if (VD->isThisDeclarationADefinition()) {
863 if (VD->isStaticLocal()) {
864 SemaRef.Diag(VD->getLocation(),
865 diag::err_constexpr_local_var_static)
866 << isa<CXXConstructorDecl>(Dcl)
867 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
868 return false;
869 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000870 if (!VD->getType()->isDependentType() &&
871 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000872 VD->getLocation(), VD->getType(),
873 diag::err_constexpr_local_var_non_literal_type,
874 isa<CXXConstructorDecl>(Dcl)))
875 return false;
876 if (!VD->hasInit()) {
877 SemaRef.Diag(VD->getLocation(),
878 diag::err_constexpr_local_var_no_init)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882 }
883 SemaRef.Diag(VD->getLocation(),
884 SemaRef.getLangOpts().CPlusPlus1y
885 ? diag::warn_cxx11_compat_constexpr_local_var
886 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000887 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000888 continue;
889 }
890
891 case Decl::NamespaceAlias:
892 case Decl::Function:
893 // These are disallowed in C++11 and permitted in C++1y. Allow them
894 // everywhere as an extension.
895 if (!Cxx1yLoc.isValid())
896 Cxx1yLoc = DS->getLocStart();
897 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000898
899 default:
900 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
901 << isa<CXXConstructorDecl>(Dcl);
902 return false;
903 }
904 }
905
906 return true;
907}
908
909/// Check that the given field is initialized within a constexpr constructor.
910///
911/// \param Dcl The constexpr constructor being checked.
912/// \param Field The field being checked. This may be a member of an anonymous
913/// struct or union nested within the class being checked.
914/// \param Inits All declarations, including anonymous struct/union members and
915/// indirect members, for which any initialization was provided.
916/// \param Diagnosed Set to true if an error is produced.
917static void CheckConstexprCtorInitializer(Sema &SemaRef,
918 const FunctionDecl *Dcl,
919 FieldDecl *Field,
920 llvm::SmallSet<Decl*, 16> &Inits,
921 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000922 if (Field->isInvalidDecl())
923 return;
924
Douglas Gregord61db332011-10-10 17:22:13 +0000925 if (Field->isUnnamedBitfield())
926 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000927
928 if (Field->isAnonymousStructOrUnion() &&
929 Field->getType()->getAsCXXRecordDecl()->isEmpty())
930 return;
931
Richard Smith9f569cc2011-10-01 02:31:28 +0000932 if (!Inits.count(Field)) {
933 if (!Diagnosed) {
934 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
935 Diagnosed = true;
936 }
937 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
938 } else if (Field->isAnonymousStructOrUnion()) {
939 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
940 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
941 I != E; ++I)
942 // If an anonymous union contains an anonymous struct of which any member
943 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000944 if (!RD->isUnion() || Inits.count(*I))
945 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000946 }
947}
948
Richard Smitha10b9782013-04-22 15:31:51 +0000949/// Check the provided statement is allowed in a constexpr function
950/// definition.
951static bool
952CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
953 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
954 SourceLocation &Cxx1yLoc) {
955 // - its function-body shall be [...] a compound-statement that contains only
956 switch (S->getStmtClass()) {
957 case Stmt::NullStmtClass:
958 // - null statements,
959 return true;
960
961 case Stmt::DeclStmtClass:
962 // - static_assert-declarations
963 // - using-declarations,
964 // - using-directives,
965 // - typedef declarations and alias-declarations that do not define
966 // classes or enumerations,
967 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
968 return false;
969 return true;
970
971 case Stmt::ReturnStmtClass:
972 // - and exactly one return statement;
973 if (isa<CXXConstructorDecl>(Dcl)) {
974 // C++1y allows return statements in constexpr constructors.
975 if (!Cxx1yLoc.isValid())
976 Cxx1yLoc = S->getLocStart();
977 return true;
978 }
979
980 ReturnStmts.push_back(S->getLocStart());
981 return true;
982
983 case Stmt::CompoundStmtClass: {
984 // C++1y allows compound-statements.
985 if (!Cxx1yLoc.isValid())
986 Cxx1yLoc = S->getLocStart();
987
988 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
989 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
990 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
991 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
992 Cxx1yLoc))
993 return false;
994 }
995 return true;
996 }
997
998 case Stmt::AttributedStmtClass:
999 if (!Cxx1yLoc.isValid())
1000 Cxx1yLoc = S->getLocStart();
1001 return true;
1002
1003 case Stmt::IfStmtClass: {
1004 // C++1y allows if-statements.
1005 if (!Cxx1yLoc.isValid())
1006 Cxx1yLoc = S->getLocStart();
1007
1008 IfStmt *If = cast<IfStmt>(S);
1009 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1010 Cxx1yLoc))
1011 return false;
1012 if (If->getElse() &&
1013 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1014 Cxx1yLoc))
1015 return false;
1016 return true;
1017 }
1018
1019 case Stmt::WhileStmtClass:
1020 case Stmt::DoStmtClass:
1021 case Stmt::ForStmtClass:
1022 case Stmt::CXXForRangeStmtClass:
1023 case Stmt::ContinueStmtClass:
1024 // C++1y allows all of these. We don't allow them as extensions in C++11,
1025 // because they don't make sense without variable mutation.
1026 if (!SemaRef.getLangOpts().CPlusPlus1y)
1027 break;
1028 if (!Cxx1yLoc.isValid())
1029 Cxx1yLoc = S->getLocStart();
1030 for (Stmt::child_range Children = S->children(); Children; ++Children)
1031 if (*Children &&
1032 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1033 Cxx1yLoc))
1034 return false;
1035 return true;
1036
1037 case Stmt::SwitchStmtClass:
1038 case Stmt::CaseStmtClass:
1039 case Stmt::DefaultStmtClass:
1040 case Stmt::BreakStmtClass:
1041 // C++1y allows switch-statements, and since they don't need variable
1042 // mutation, we can reasonably allow them in C++11 as an extension.
1043 if (!Cxx1yLoc.isValid())
1044 Cxx1yLoc = S->getLocStart();
1045 for (Stmt::child_range Children = S->children(); Children; ++Children)
1046 if (*Children &&
1047 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1048 Cxx1yLoc))
1049 return false;
1050 return true;
1051
1052 default:
1053 if (!isa<Expr>(S))
1054 break;
1055
1056 // C++1y allows expression-statements.
1057 if (!Cxx1yLoc.isValid())
1058 Cxx1yLoc = S->getLocStart();
1059 return true;
1060 }
1061
1062 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1063 << isa<CXXConstructorDecl>(Dcl);
1064 return false;
1065}
1066
Richard Smith9f569cc2011-10-01 02:31:28 +00001067/// Check the body for the given constexpr function declaration only contains
1068/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1069///
1070/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001071bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001072 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001073 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001074 // The definition of a constexpr function shall satisfy the following
1075 // constraints: [...]
1076 // - its function-body shall be = delete, = default, or a
1077 // compound-statement
1078 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001079 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001080 // In the definition of a constexpr constructor, [...]
1081 // - its function-body shall not be a function-try-block;
1082 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1083 << isa<CXXConstructorDecl>(Dcl);
1084 return false;
1085 }
1086
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001087 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001088
1089 // - its function-body shall be [...] a compound-statement that contains only
1090 // [... list of cases ...]
1091 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1092 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001093 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1094 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001095 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1096 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001097 }
1098
Richard Smitha10b9782013-04-22 15:31:51 +00001099 if (Cxx1yLoc.isValid())
1100 Diag(Cxx1yLoc,
1101 getLangOpts().CPlusPlus1y
1102 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1103 : diag::ext_constexpr_body_invalid_stmt)
1104 << isa<CXXConstructorDecl>(Dcl);
1105
Richard Smith9f569cc2011-10-01 02:31:28 +00001106 if (const CXXConstructorDecl *Constructor
1107 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1108 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001109 // DR1359:
1110 // - every non-variant non-static data member and base class sub-object
1111 // shall be initialized;
1112 // - if the class is a non-empty union, or for each non-empty anonymous
1113 // union member of a non-union class, exactly one non-static data member
1114 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001115 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001116 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001117 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1118 return false;
1119 }
Richard Smith6e433752011-10-10 16:38:04 +00001120 } else if (!Constructor->isDependentContext() &&
1121 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001122 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1123
1124 // Skip detailed checking if we have enough initializers, and we would
1125 // allow at most one initializer per member.
1126 bool AnyAnonStructUnionMembers = false;
1127 unsigned Fields = 0;
1128 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1129 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001130 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001131 AnyAnonStructUnionMembers = true;
1132 break;
1133 }
1134 }
1135 if (AnyAnonStructUnionMembers ||
1136 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1137 // Check initialization of non-static data members. Base classes are
1138 // always initialized so do not need to be checked. Dependent bases
1139 // might not have initializers in the member initializer list.
1140 llvm::SmallSet<Decl*, 16> Inits;
1141 for (CXXConstructorDecl::init_const_iterator
1142 I = Constructor->init_begin(), E = Constructor->init_end();
1143 I != E; ++I) {
1144 if (FieldDecl *FD = (*I)->getMember())
1145 Inits.insert(FD);
1146 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1147 Inits.insert(ID->chain_begin(), ID->chain_end());
1148 }
1149
1150 bool Diagnosed = false;
1151 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1152 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001153 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001154 if (Diagnosed)
1155 return false;
1156 }
1157 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001158 } else {
1159 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001160 // C++1y doesn't require constexpr functions to contain a 'return'
1161 // statement. We still do, unless the return type is void, because
1162 // otherwise if there's no return statement, the function cannot
1163 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001164 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001165 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001166 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1167 : diag::err_constexpr_body_no_return);
1168 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001169 }
1170 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001171 Diag(ReturnStmts.back(),
1172 getLangOpts().CPlusPlus1y
1173 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1174 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001175 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1176 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001177 }
1178 }
1179
Richard Smith5ba73e12012-02-04 00:33:54 +00001180 // C++11 [dcl.constexpr]p5:
1181 // if no function argument values exist such that the function invocation
1182 // substitution would produce a constant expression, the program is
1183 // ill-formed; no diagnostic required.
1184 // C++11 [dcl.constexpr]p3:
1185 // - every constructor call and implicit conversion used in initializing the
1186 // return value shall be one of those allowed in a constant expression.
1187 // C++11 [dcl.constexpr]p4:
1188 // - every constructor involved in initializing non-static data members and
1189 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001190 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001191 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001192 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001193 << isa<CXXConstructorDecl>(Dcl);
1194 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1195 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001196 // Don't return false here: we allow this for compatibility in
1197 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001198 }
1199
Richard Smith9f569cc2011-10-01 02:31:28 +00001200 return true;
1201}
1202
Douglas Gregorb48fe382008-10-31 09:07:45 +00001203/// isCurrentClassName - Determine whether the identifier II is the
1204/// name of the class type currently being defined. In the case of
1205/// nested classes, this will only return true if II is the name of
1206/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001207bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1208 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001209 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001210
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001211 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001212 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001213 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001214 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1215 } else
1216 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1217
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001218 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001219 return &II == CurDecl->getIdentifier();
1220 else
1221 return false;
1222}
1223
Douglas Gregor229d47a2012-11-10 07:24:09 +00001224/// \brief Determine whether the given class is a base class of the given
1225/// class, including looking at dependent bases.
1226static bool findCircularInheritance(const CXXRecordDecl *Class,
1227 const CXXRecordDecl *Current) {
1228 SmallVector<const CXXRecordDecl*, 8> Queue;
1229
1230 Class = Class->getCanonicalDecl();
1231 while (true) {
1232 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1233 E = Current->bases_end();
1234 I != E; ++I) {
1235 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1236 if (!Base)
1237 continue;
1238
1239 Base = Base->getDefinition();
1240 if (!Base)
1241 continue;
1242
1243 if (Base->getCanonicalDecl() == Class)
1244 return true;
1245
1246 Queue.push_back(Base);
1247 }
1248
1249 if (Queue.empty())
1250 return false;
1251
1252 Current = Queue.back();
1253 Queue.pop_back();
1254 }
1255
1256 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001257}
1258
Mike Stump1eb44332009-09-09 15:08:12 +00001259/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001260///
1261/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1262/// and returns NULL otherwise.
1263CXXBaseSpecifier *
1264Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1265 SourceRange SpecifierRange,
1266 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001267 TypeSourceInfo *TInfo,
1268 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001269 QualType BaseType = TInfo->getType();
1270
Douglas Gregor2943aed2009-03-03 04:44:36 +00001271 // C++ [class.union]p1:
1272 // A union shall not have base classes.
1273 if (Class->isUnion()) {
1274 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1275 << SpecifierRange;
1276 return 0;
1277 }
1278
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001279 if (EllipsisLoc.isValid() &&
1280 !TInfo->getType()->containsUnexpandedParameterPack()) {
1281 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1282 << TInfo->getTypeLoc().getSourceRange();
1283 EllipsisLoc = SourceLocation();
1284 }
Douglas Gregord777e282012-11-10 01:18:17 +00001285
1286 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1287
1288 if (BaseType->isDependentType()) {
1289 // Make sure that we don't have circular inheritance among our dependent
1290 // bases. For non-dependent bases, the check for completeness below handles
1291 // this.
1292 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1293 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1294 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001295 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001296 Diag(BaseLoc, diag::err_circular_inheritance)
1297 << BaseType << Context.getTypeDeclType(Class);
1298
1299 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1300 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1301 << BaseType;
1302
1303 return 0;
1304 }
1305 }
1306
Mike Stump1eb44332009-09-09 15:08:12 +00001307 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001308 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001309 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001310 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311
1312 // Base specifiers must be record types.
1313 if (!BaseType->isRecordType()) {
1314 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1315 return 0;
1316 }
1317
1318 // C++ [class.union]p1:
1319 // A union shall not be used as a base class.
1320 if (BaseType->isUnionType()) {
1321 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1322 return 0;
1323 }
1324
1325 // C++ [class.derived]p2:
1326 // The class-name in a base-specifier shall not be an incompletely
1327 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001328 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001329 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001330 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001331 return 0;
John McCall572fc622010-08-17 07:23:57 +00001332 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001333
Eli Friedman1d954f62009-08-15 21:55:26 +00001334 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001335 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001336 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001337 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001338 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001339 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001340 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001341
Anders Carlsson1d209272011-03-25 14:55:14 +00001342 // C++ [class]p3:
1343 // If a class is marked final and it appears as a base-type-specifier in
1344 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001345 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001346 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1347 << CXXBaseDecl->getDeclName();
1348 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1349 << CXXBaseDecl->getDeclName();
1350 return 0;
1351 }
1352
John McCall572fc622010-08-17 07:23:57 +00001353 if (BaseDecl->isInvalidDecl())
1354 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001355
1356 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001357 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001358 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001359 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001360}
1361
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001362/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1363/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001364/// example:
1365/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001366/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001367BaseResult
John McCalld226f652010-08-21 09:40:31 +00001368Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001369 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001370 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001371 ParsedType basetype, SourceLocation BaseLoc,
1372 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001373 if (!classdecl)
1374 return true;
1375
Douglas Gregor40808ce2009-03-09 23:48:35 +00001376 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001377 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001378 if (!Class)
1379 return true;
1380
Richard Smith05321402013-02-19 23:47:15 +00001381 // We do not support any C++11 attributes on base-specifiers yet.
1382 // Diagnose any attributes we see.
1383 if (!Attributes.empty()) {
1384 for (AttributeList *Attr = Attributes.getList(); Attr;
1385 Attr = Attr->getNext()) {
1386 if (Attr->isInvalid() ||
1387 Attr->getKind() == AttributeList::IgnoredAttribute)
1388 continue;
1389 Diag(Attr->getLoc(),
1390 Attr->getKind() == AttributeList::UnknownAttribute
1391 ? diag::warn_unknown_attribute_ignored
1392 : diag::err_base_specifier_attribute)
1393 << Attr->getName();
1394 }
1395 }
1396
Nick Lewycky56062202010-07-26 16:56:01 +00001397 TypeSourceInfo *TInfo = 0;
1398 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001399
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001400 if (EllipsisLoc.isInvalid() &&
1401 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001402 UPPC_BaseType))
1403 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001404
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001406 Virtual, Access, TInfo,
1407 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001408 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001409 else
1410 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Douglas Gregor2943aed2009-03-03 04:44:36 +00001412 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001413}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001414
Douglas Gregor2943aed2009-03-03 04:44:36 +00001415/// \brief Performs the actual work of attaching the given base class
1416/// specifiers to a C++ class.
1417bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1418 unsigned NumBases) {
1419 if (NumBases == 0)
1420 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001421
1422 // Used to keep track of which base types we have already seen, so
1423 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001424 // that the key is always the unqualified canonical type of the base
1425 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001426 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1427
1428 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001429 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001430 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001431 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001432 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001433 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001434 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001435
1436 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1437 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001438 // C++ [class.mi]p3:
1439 // A class shall not be specified as a direct base class of a
1440 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001441 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001442 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001443 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001444 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001445
1446 // Delete the duplicate base class specifier; we're going to
1447 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001448 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001449
1450 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001451 } else {
1452 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001453 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001454 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001455 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1456 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1457 if (Class->isInterface() &&
1458 (!RD->isInterface() ||
1459 KnownBase->getAccessSpecifier() != AS_public)) {
1460 // The Microsoft extension __interface does not permit bases that
1461 // are not themselves public interfaces.
1462 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1463 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1464 << RD->getSourceRange();
1465 Invalid = true;
1466 }
1467 if (RD->hasAttr<WeakAttr>())
1468 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1469 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001470 }
1471 }
1472
1473 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001474 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001475
1476 // Delete the remaining (good) base class specifiers, since their
1477 // data has been copied into the CXXRecordDecl.
1478 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001479 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001480
1481 return Invalid;
1482}
1483
1484/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1485/// class, after checking whether there are any duplicate base
1486/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001487void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001488 unsigned NumBases) {
1489 if (!ClassDecl || !Bases || !NumBases)
1490 return;
1491
1492 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001493 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001494 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001495}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001496
Douglas Gregora8f32e02009-10-06 17:59:45 +00001497/// \brief Determine whether the type \p Derived is a C++ class that is
1498/// derived from the type \p Base.
1499bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001500 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001501 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001502
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001503 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001504 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001505 return false;
1506
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001507 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001508 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001509 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001510
1511 // If either the base or the derived type is invalid, don't try to
1512 // check whether one is derived from the other.
1513 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1514 return false;
1515
John McCall86ff3082010-02-04 22:26:26 +00001516 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1517 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001518}
1519
1520/// \brief Determine whether the type \p Derived is a C++ class that is
1521/// derived from the type \p Base.
1522bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001523 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001524 return false;
1525
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001526 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001527 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001528 return false;
1529
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001530 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001531 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001532 return false;
1533
Douglas Gregora8f32e02009-10-06 17:59:45 +00001534 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1535}
1536
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001537void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001538 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001539 assert(BasePathArray.empty() && "Base path array must be empty!");
1540 assert(Paths.isRecordingPaths() && "Must record paths!");
1541
1542 const CXXBasePath &Path = Paths.front();
1543
1544 // We first go backward and check if we have a virtual base.
1545 // FIXME: It would be better if CXXBasePath had the base specifier for
1546 // the nearest virtual base.
1547 unsigned Start = 0;
1548 for (unsigned I = Path.size(); I != 0; --I) {
1549 if (Path[I - 1].Base->isVirtual()) {
1550 Start = I - 1;
1551 break;
1552 }
1553 }
1554
1555 // Now add all bases.
1556 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001557 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001558}
1559
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001560/// \brief Determine whether the given base path includes a virtual
1561/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001562bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1563 for (CXXCastPath::const_iterator B = BasePath.begin(),
1564 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001565 B != BEnd; ++B)
1566 if ((*B)->isVirtual())
1567 return true;
1568
1569 return false;
1570}
1571
Douglas Gregora8f32e02009-10-06 17:59:45 +00001572/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1573/// conversion (where Derived and Base are class types) is
1574/// well-formed, meaning that the conversion is unambiguous (and
1575/// that all of the base classes are accessible). Returns true
1576/// and emits a diagnostic if the code is ill-formed, returns false
1577/// otherwise. Loc is the location where this routine should point to
1578/// if there is an error, and Range is the source range to highlight
1579/// if there is an error.
1580bool
1581Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001582 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001583 unsigned AmbigiousBaseConvID,
1584 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001585 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001586 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001587 // First, determine whether the path from Derived to Base is
1588 // ambiguous. This is slightly more expensive than checking whether
1589 // the Derived to Base conversion exists, because here we need to
1590 // explore multiple paths to determine if there is an ambiguity.
1591 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1592 /*DetectVirtual=*/false);
1593 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1594 assert(DerivationOkay &&
1595 "Can only be used with a derived-to-base conversion");
1596 (void)DerivationOkay;
1597
1598 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001599 if (InaccessibleBaseID) {
1600 // Check that the base class can be accessed.
1601 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1602 InaccessibleBaseID)) {
1603 case AR_inaccessible:
1604 return true;
1605 case AR_accessible:
1606 case AR_dependent:
1607 case AR_delayed:
1608 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001609 }
John McCall6b2accb2010-02-10 09:31:12 +00001610 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001611
1612 // Build a base path if necessary.
1613 if (BasePath)
1614 BuildBasePathArray(Paths, *BasePath);
1615 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001616 }
1617
David Majnemer2f686692013-06-22 06:43:58 +00001618 if (AmbigiousBaseConvID) {
1619 // We know that the derived-to-base conversion is ambiguous, and
1620 // we're going to produce a diagnostic. Perform the derived-to-base
1621 // search just one more time to compute all of the possible paths so
1622 // that we can print them out. This is more expensive than any of
1623 // the previous derived-to-base checks we've done, but at this point
1624 // performance isn't as much of an issue.
1625 Paths.clear();
1626 Paths.setRecordingPaths(true);
1627 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1628 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1629 (void)StillOkay;
1630
1631 // Build up a textual representation of the ambiguous paths, e.g.,
1632 // D -> B -> A, that will be used to illustrate the ambiguous
1633 // conversions in the diagnostic. We only print one of the paths
1634 // to each base class subobject.
1635 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1636
1637 Diag(Loc, AmbigiousBaseConvID)
1638 << Derived << Base << PathDisplayStr << Range << Name;
1639 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001640 return true;
1641}
1642
1643bool
1644Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001645 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001646 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001647 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001648 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001649 IgnoreAccess ? 0
1650 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001651 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001652 Loc, Range, DeclarationName(),
1653 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001654}
1655
1656
1657/// @brief Builds a string representing ambiguous paths from a
1658/// specific derived class to different subobjects of the same base
1659/// class.
1660///
1661/// This function builds a string that can be used in error messages
1662/// to show the different paths that one can take through the
1663/// inheritance hierarchy to go from the derived class to different
1664/// subobjects of a base class. The result looks something like this:
1665/// @code
1666/// struct D -> struct B -> struct A
1667/// struct D -> struct C -> struct A
1668/// @endcode
1669std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1670 std::string PathDisplayStr;
1671 std::set<unsigned> DisplayedPaths;
1672 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1673 Path != Paths.end(); ++Path) {
1674 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1675 // We haven't displayed a path to this particular base
1676 // class subobject yet.
1677 PathDisplayStr += "\n ";
1678 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1679 for (CXXBasePath::const_iterator Element = Path->begin();
1680 Element != Path->end(); ++Element)
1681 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1682 }
1683 }
1684
1685 return PathDisplayStr;
1686}
1687
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001688//===----------------------------------------------------------------------===//
1689// C++ class member Handling
1690//===----------------------------------------------------------------------===//
1691
Abramo Bagnara6206d532010-06-05 05:09:32 +00001692/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001693bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1694 SourceLocation ASLoc,
1695 SourceLocation ColonLoc,
1696 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001697 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001698 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001699 ASLoc, ColonLoc);
1700 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001701 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001702}
1703
Richard Smitha4b39652012-08-06 03:25:17 +00001704/// CheckOverrideControl - Check C++11 override control semantics.
1705void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001706 if (D->isInvalidDecl())
1707 return;
1708
Chris Lattner5f9e2722011-07-23 10:55:15 +00001709 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001710
Richard Smitha4b39652012-08-06 03:25:17 +00001711 // Do we know which functions this declaration might be overriding?
1712 bool OverridesAreKnown = !MD ||
1713 (!MD->getParent()->hasAnyDependentBases() &&
1714 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001715
Richard Smitha4b39652012-08-06 03:25:17 +00001716 if (!MD || !MD->isVirtual()) {
1717 if (OverridesAreKnown) {
1718 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1719 Diag(OA->getLocation(),
1720 diag::override_keyword_only_allowed_on_virtual_member_functions)
1721 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1722 D->dropAttr<OverrideAttr>();
1723 }
1724 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1725 Diag(FA->getLocation(),
1726 diag::override_keyword_only_allowed_on_virtual_member_functions)
1727 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1728 D->dropAttr<FinalAttr>();
1729 }
1730 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001731 return;
1732 }
Richard Smitha4b39652012-08-06 03:25:17 +00001733
1734 if (!OverridesAreKnown)
1735 return;
1736
1737 // C++11 [class.virtual]p5:
1738 // If a virtual function is marked with the virt-specifier override and
1739 // does not override a member function of a base class, the program is
1740 // ill-formed.
1741 bool HasOverriddenMethods =
1742 MD->begin_overridden_methods() != MD->end_overridden_methods();
1743 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1744 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1745 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001746}
1747
Richard Smitha4b39652012-08-06 03:25:17 +00001748/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001749/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001750/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001751bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1752 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001753 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001754 return false;
1755
1756 Diag(New->getLocation(), diag::err_final_function_overridden)
1757 << New->getDeclName();
1758 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1759 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001760}
1761
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001762static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001763 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1764 // FIXME: Destruction of ObjC lifetime types has side-effects.
1765 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1766 return !RD->isCompleteDefinition() ||
1767 !RD->hasTrivialDefaultConstructor() ||
1768 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001769 return false;
1770}
1771
John McCall76da55d2013-04-16 07:28:30 +00001772static AttributeList *getMSPropertyAttr(AttributeList *list) {
1773 for (AttributeList* it = list; it != 0; it = it->getNext())
1774 if (it->isDeclspecPropertyAttribute())
1775 return it;
1776 return 0;
1777}
1778
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001779/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1780/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001781/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001782/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1783/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001784NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001785Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001786 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001787 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001788 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001789 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001790 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1791 DeclarationName Name = NameInfo.getName();
1792 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001793
1794 // For anonymous bitfields, the location should point to the type.
1795 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001796 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001797
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001798 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001799
John McCall4bde1e12010-06-04 08:34:12 +00001800 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001801 assert(!DS.isFriendSpecified());
1802
Richard Smith1ab0d902011-06-25 02:28:38 +00001803 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001804
John McCalle402e722012-09-25 07:32:39 +00001805 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1806 // The Microsoft extension __interface only permits public member functions
1807 // and prohibits constructors, destructors, operators, non-public member
1808 // functions, static methods and data members.
1809 unsigned InvalidDecl;
1810 bool ShowDeclName = true;
1811 if (!isFunc)
1812 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1813 else if (AS != AS_public)
1814 InvalidDecl = 2;
1815 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1816 InvalidDecl = 3;
1817 else switch (Name.getNameKind()) {
1818 case DeclarationName::CXXConstructorName:
1819 InvalidDecl = 4;
1820 ShowDeclName = false;
1821 break;
1822
1823 case DeclarationName::CXXDestructorName:
1824 InvalidDecl = 5;
1825 ShowDeclName = false;
1826 break;
1827
1828 case DeclarationName::CXXOperatorName:
1829 case DeclarationName::CXXConversionFunctionName:
1830 InvalidDecl = 6;
1831 break;
1832
1833 default:
1834 InvalidDecl = 0;
1835 break;
1836 }
1837
1838 if (InvalidDecl) {
1839 if (ShowDeclName)
1840 Diag(Loc, diag::err_invalid_member_in_interface)
1841 << (InvalidDecl-1) << Name;
1842 else
1843 Diag(Loc, diag::err_invalid_member_in_interface)
1844 << (InvalidDecl-1) << "";
1845 return 0;
1846 }
1847 }
1848
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001849 // C++ 9.2p6: A member shall not be declared to have automatic storage
1850 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001851 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1852 // data members and cannot be applied to names declared const or static,
1853 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001854 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001855 case DeclSpec::SCS_unspecified:
1856 case DeclSpec::SCS_typedef:
1857 case DeclSpec::SCS_static:
1858 break;
1859 case DeclSpec::SCS_mutable:
1860 if (isFunc) {
1861 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Richard Smithec642442013-04-12 22:46:28 +00001863 // FIXME: It would be nicer if the keyword was ignored only for this
1864 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001865 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001866 }
1867 break;
1868 default:
1869 Diag(DS.getStorageClassSpecLoc(),
1870 diag::err_storageclass_invalid_for_member);
1871 D.getMutableDeclSpec().ClearStorageClassSpecs();
1872 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001873 }
1874
Sebastian Redl669d5d72008-11-14 23:42:31 +00001875 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1876 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001877 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001878
David Blaikie1d87fba2013-01-30 01:22:18 +00001879 if (DS.isConstexprSpecified() && isInstField) {
1880 SemaDiagnosticBuilder B =
1881 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1882 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1883 if (InitStyle == ICIS_NoInit) {
1884 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1885 D.getMutableDeclSpec().ClearConstexprSpec();
1886 const char *PrevSpec;
1887 unsigned DiagID;
1888 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1889 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001890 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001891 assert(!Failed && "Making a constexpr member const shouldn't fail");
1892 } else {
1893 B << 1;
1894 const char *PrevSpec;
1895 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001896 if (D.getMutableDeclSpec().SetStorageClassSpec(
1897 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001898 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001899 "This is the only DeclSpec that should fail to be applied");
1900 B << 1;
1901 } else {
1902 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1903 isInstField = false;
1904 }
1905 }
1906 }
1907
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001908 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001909 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001910 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001911
1912 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001913 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001914 Diag(Loc, diag::err_bad_variable_name)
1915 << Name;
1916 return 0;
1917 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001918
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001919 IdentifierInfo *II = Name.getAsIdentifierInfo();
1920
Douglas Gregorf2503652011-09-21 14:40:46 +00001921 // Member field could not be with "template" keyword.
1922 // So TemplateParameterLists should be empty in this case.
1923 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001924 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001925 if (TemplateParams->size()) {
1926 // There is no such thing as a member field template.
1927 Diag(D.getIdentifierLoc(), diag::err_template_member)
1928 << II
1929 << SourceRange(TemplateParams->getTemplateLoc(),
1930 TemplateParams->getRAngleLoc());
1931 } else {
1932 // There is an extraneous 'template<>' for this member.
1933 Diag(TemplateParams->getTemplateLoc(),
1934 diag::err_template_member_noparams)
1935 << II
1936 << SourceRange(TemplateParams->getTemplateLoc(),
1937 TemplateParams->getRAngleLoc());
1938 }
1939 return 0;
1940 }
1941
Douglas Gregor922fff22010-10-13 22:19:53 +00001942 if (SS.isSet() && !SS.isInvalid()) {
1943 // The user provided a superfluous scope specifier inside a class
1944 // definition:
1945 //
1946 // class X {
1947 // int X::member;
1948 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001949 if (DeclContext *DC = computeDeclContext(SS, false))
1950 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001951 else
1952 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1953 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001954
Douglas Gregor922fff22010-10-13 22:19:53 +00001955 SS.clear();
1956 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001957
John McCall76da55d2013-04-16 07:28:30 +00001958 AttributeList *MSPropertyAttr =
1959 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00001960 if (MSPropertyAttr) {
1961 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1962 BitWidth, InitStyle, AS, MSPropertyAttr);
1963 if (!Member)
1964 return 0;
1965 isInstField = false;
1966 } else {
1967 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1968 BitWidth, InitStyle, AS);
1969 assert(Member && "HandleField never returns null");
1970 }
1971 } else {
1972 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1973
1974 Member = HandleDeclarator(S, D, TemplateParameterLists);
1975 if (!Member)
1976 return 0;
1977
1978 // Non-instance-fields can't have a bitfield.
1979 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001980 if (Member->isInvalidDecl()) {
1981 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001982 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001983 // C++ 9.6p3: A bit-field shall not be a static member.
1984 // "static member 'A' cannot be a bit-field"
1985 Diag(Loc, diag::err_static_not_bitfield)
1986 << Name << BitWidth->getSourceRange();
1987 } else if (isa<TypedefDecl>(Member)) {
1988 // "typedef member 'x' cannot be a bit-field"
1989 Diag(Loc, diag::err_typedef_not_bitfield)
1990 << Name << BitWidth->getSourceRange();
1991 } else {
1992 // A function typedef ("typedef int f(); f a;").
1993 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1994 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001995 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001996 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001997 }
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Chris Lattner8b963ef2009-03-05 23:01:03 +00001999 BitWidth = 0;
2000 Member->setInvalidDecl();
2001 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002002
2003 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Douglas Gregor37b372b2009-08-20 22:52:58 +00002005 // If we have declared a member function template, set the access of the
2006 // templated declaration as well.
2007 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2008 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002009 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002010
Richard Smitha4b39652012-08-06 03:25:17 +00002011 if (VS.isOverrideSpecified())
2012 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2013 if (VS.isFinalSpecified())
2014 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002015
Douglas Gregorf5251602011-03-08 17:10:18 +00002016 if (VS.getLastLocation().isValid()) {
2017 // Update the end location of a method that has a virt-specifiers.
2018 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2019 MD->setRangeEnd(VS.getLastLocation());
2020 }
Richard Smitha4b39652012-08-06 03:25:17 +00002021
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002022 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002023
Douglas Gregor10bd3682008-11-17 22:58:34 +00002024 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002025
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002026 if (isInstField) {
2027 FieldDecl *FD = cast<FieldDecl>(Member);
2028 FieldCollector->Add(FD);
2029
2030 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2031 FD->getLocation())
2032 != DiagnosticsEngine::Ignored) {
2033 // Remember all explicit private FieldDecls that have a name, no side
2034 // effects and are not part of a dependent type declaration.
2035 if (!FD->isImplicit() && FD->getDeclName() &&
2036 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002037 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002038 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002039 !InitializationHasSideEffects(*FD))
2040 UnusedPrivateFields.insert(FD);
2041 }
2042 }
2043
John McCalld226f652010-08-21 09:40:31 +00002044 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002045}
2046
Hans Wennborg471f9852012-09-18 15:58:06 +00002047namespace {
2048 class UninitializedFieldVisitor
2049 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2050 Sema &S;
2051 ValueDecl *VD;
2052 public:
2053 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2054 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002055 S(S) {
2056 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2057 this->VD = IFD->getAnonField();
2058 else
2059 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002060 }
2061
2062 void HandleExpr(Expr *E) {
2063 if (!E) return;
2064
2065 // Expressions like x(x) sometimes lack the surrounding expressions
2066 // but need to be checked anyways.
2067 HandleValue(E);
2068 Visit(E);
2069 }
2070
2071 void HandleValue(Expr *E) {
2072 E = E->IgnoreParens();
2073
2074 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2075 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002076 return;
2077
2078 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2079 // or union.
2080 MemberExpr *FieldME = ME;
2081
Hans Wennborg471f9852012-09-18 15:58:06 +00002082 Expr *Base = E;
2083 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002084 ME = cast<MemberExpr>(Base);
2085
2086 if (isa<VarDecl>(ME->getMemberDecl()))
2087 return;
2088
2089 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2090 if (!FD->isAnonymousStructOrUnion())
2091 FieldME = ME;
2092
Hans Wennborg471f9852012-09-18 15:58:06 +00002093 Base = ME->getBase();
2094 }
2095
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002096 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002097 unsigned diag = VD->getType()->isReferenceType()
2098 ? diag::warn_reference_field_is_uninit
2099 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002100 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002101 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002102 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002103 }
2104
2105 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2106 HandleValue(CO->getTrueExpr());
2107 HandleValue(CO->getFalseExpr());
2108 return;
2109 }
2110
2111 if (BinaryConditionalOperator *BCO =
2112 dyn_cast<BinaryConditionalOperator>(E)) {
2113 HandleValue(BCO->getCommon());
2114 HandleValue(BCO->getFalseExpr());
2115 return;
2116 }
2117
2118 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2119 switch (BO->getOpcode()) {
2120 default:
2121 return;
2122 case(BO_PtrMemD):
2123 case(BO_PtrMemI):
2124 HandleValue(BO->getLHS());
2125 return;
2126 case(BO_Comma):
2127 HandleValue(BO->getRHS());
2128 return;
2129 }
2130 }
2131 }
2132
2133 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2134 if (E->getCastKind() == CK_LValueToRValue)
2135 HandleValue(E->getSubExpr());
2136
2137 Inherited::VisitImplicitCastExpr(E);
2138 }
2139
2140 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2141 Expr *Callee = E->getCallee();
2142 if (isa<MemberExpr>(Callee))
2143 HandleValue(Callee);
2144
2145 Inherited::VisitCXXMemberCallExpr(E);
2146 }
2147 };
2148 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2149 ValueDecl *VD) {
2150 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2151 }
2152} // namespace
2153
Richard Smith7a614d82011-06-11 17:19:42 +00002154/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002155/// in-class initializer for a non-static C++ class member, and after
2156/// instantiating an in-class initializer in a class template. Such actions
2157/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002158void
Richard Smithca523302012-06-10 03:12:00 +00002159Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002160 Expr *InitExpr) {
2161 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002162 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2163 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002164
2165 if (!InitExpr) {
2166 FD->setInvalidDecl();
2167 FD->removeInClassInitializer();
2168 return;
2169 }
2170
Peter Collingbournefef21892011-10-23 18:59:44 +00002171 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2172 FD->setInvalidDecl();
2173 FD->removeInClassInitializer();
2174 return;
2175 }
2176
Hans Wennborg471f9852012-09-18 15:58:06 +00002177 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2178 != DiagnosticsEngine::Ignored) {
2179 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2180 }
2181
Richard Smith7a614d82011-06-11 17:19:42 +00002182 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002183 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002184 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002185 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002186 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002187 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002188 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2189 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002190 if (Init.isInvalid()) {
2191 FD->setInvalidDecl();
2192 return;
2193 }
Richard Smith7a614d82011-06-11 17:19:42 +00002194 }
2195
Richard Smith41956372013-01-14 22:39:08 +00002196 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002197 // The initialization of each base and member constitutes a
2198 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002199 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002200 if (Init.isInvalid()) {
2201 FD->setInvalidDecl();
2202 return;
2203 }
2204
2205 InitExpr = Init.release();
2206
2207 FD->setInClassInitializer(InitExpr);
2208}
2209
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002210/// \brief Find the direct and/or virtual base specifiers that
2211/// correspond to the given base type, for use in base initialization
2212/// within a constructor.
2213static bool FindBaseInitializer(Sema &SemaRef,
2214 CXXRecordDecl *ClassDecl,
2215 QualType BaseType,
2216 const CXXBaseSpecifier *&DirectBaseSpec,
2217 const CXXBaseSpecifier *&VirtualBaseSpec) {
2218 // First, check for a direct base class.
2219 DirectBaseSpec = 0;
2220 for (CXXRecordDecl::base_class_const_iterator Base
2221 = ClassDecl->bases_begin();
2222 Base != ClassDecl->bases_end(); ++Base) {
2223 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2224 // We found a direct base of this type. That's what we're
2225 // initializing.
2226 DirectBaseSpec = &*Base;
2227 break;
2228 }
2229 }
2230
2231 // Check for a virtual base class.
2232 // FIXME: We might be able to short-circuit this if we know in advance that
2233 // there are no virtual bases.
2234 VirtualBaseSpec = 0;
2235 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2236 // We haven't found a base yet; search the class hierarchy for a
2237 // virtual base class.
2238 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2239 /*DetectVirtual=*/false);
2240 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2241 BaseType, Paths)) {
2242 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2243 Path != Paths.end(); ++Path) {
2244 if (Path->back().Base->isVirtual()) {
2245 VirtualBaseSpec = Path->back().Base;
2246 break;
2247 }
2248 }
2249 }
2250 }
2251
2252 return DirectBaseSpec || VirtualBaseSpec;
2253}
2254
Sebastian Redl6df65482011-09-24 17:48:25 +00002255/// \brief Handle a C++ member initializer using braced-init-list syntax.
2256MemInitResult
2257Sema::ActOnMemInitializer(Decl *ConstructorD,
2258 Scope *S,
2259 CXXScopeSpec &SS,
2260 IdentifierInfo *MemberOrBase,
2261 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002262 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002263 SourceLocation IdLoc,
2264 Expr *InitList,
2265 SourceLocation EllipsisLoc) {
2266 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002267 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002268 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002269}
2270
2271/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002272MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002273Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002274 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002275 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002276 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002277 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002278 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002279 SourceLocation IdLoc,
2280 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002281 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002282 SourceLocation RParenLoc,
2283 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002284 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002285 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002286 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002287 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002288}
2289
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002290namespace {
2291
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002292// Callback to only accept typo corrections that can be a valid C++ member
2293// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002294class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2295 public:
2296 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2297 : ClassDecl(ClassDecl) {}
2298
2299 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2300 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2301 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2302 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2303 else
2304 return isa<TypeDecl>(ND);
2305 }
2306 return false;
2307 }
2308
2309 private:
2310 CXXRecordDecl *ClassDecl;
2311};
2312
2313}
2314
Sebastian Redl6df65482011-09-24 17:48:25 +00002315/// \brief Handle a C++ member initializer.
2316MemInitResult
2317Sema::BuildMemInitializer(Decl *ConstructorD,
2318 Scope *S,
2319 CXXScopeSpec &SS,
2320 IdentifierInfo *MemberOrBase,
2321 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002322 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002323 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002324 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002325 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002326 if (!ConstructorD)
2327 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002328
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002329 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002330
2331 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002332 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002333 if (!Constructor) {
2334 // The user wrote a constructor initializer on a function that is
2335 // not a C++ constructor. Ignore the error for now, because we may
2336 // have more member initializers coming; we'll diagnose it just
2337 // once in ActOnMemInitializers.
2338 return true;
2339 }
2340
2341 CXXRecordDecl *ClassDecl = Constructor->getParent();
2342
2343 // C++ [class.base.init]p2:
2344 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002345 // constructor's class and, if not found in that scope, are looked
2346 // up in the scope containing the constructor's definition.
2347 // [Note: if the constructor's class contains a member with the
2348 // same name as a direct or virtual base class of the class, a
2349 // mem-initializer-id naming the member or base class and composed
2350 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002351 // mem-initializer-id for the hidden base class may be specified
2352 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002353 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002354 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002355 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002356 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002357 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002358 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002359 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2360 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002361 if (EllipsisLoc.isValid())
2362 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002363 << MemberOrBase
2364 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002365
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002366 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002367 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002368 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002369 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002370 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002371 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002372 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002373
2374 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002375 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002376 } else if (DS.getTypeSpecType() == TST_decltype) {
2377 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002378 } else {
2379 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2380 LookupParsedName(R, S, &SS);
2381
2382 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2383 if (!TyD) {
2384 if (R.isAmbiguous()) return true;
2385
John McCallfd225442010-04-09 19:01:14 +00002386 // We don't want access-control diagnostics here.
2387 R.suppressDiagnostics();
2388
Douglas Gregor7a886e12010-01-19 06:46:48 +00002389 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2390 bool NotUnknownSpecialization = false;
2391 DeclContext *DC = computeDeclContext(SS, false);
2392 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2393 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2394
2395 if (!NotUnknownSpecialization) {
2396 // When the scope specifier can refer to a member of an unknown
2397 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002398 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2399 SS.getWithLocInContext(Context),
2400 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002401 if (BaseType.isNull())
2402 return true;
2403
Douglas Gregor7a886e12010-01-19 06:46:48 +00002404 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002405 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002406 }
2407 }
2408
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002409 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002410 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002411 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002412 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002413 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002414 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002415 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2416 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002417 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002418 // We have found a non-static data member with a similar
2419 // name to what was typed; complain and initialize that
2420 // member.
2421 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2422 << MemberOrBase << true << CorrectedQuotedStr
2423 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2424 Diag(Member->getLocation(), diag::note_previous_decl)
2425 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002426
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002427 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002428 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002429 const CXXBaseSpecifier *DirectBaseSpec;
2430 const CXXBaseSpecifier *VirtualBaseSpec;
2431 if (FindBaseInitializer(*this, ClassDecl,
2432 Context.getTypeDeclType(Type),
2433 DirectBaseSpec, VirtualBaseSpec)) {
2434 // We have found a direct or virtual base class with a
2435 // similar name to what was typed; complain and initialize
2436 // that base class.
2437 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002438 << MemberOrBase << false << CorrectedQuotedStr
2439 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002440
2441 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2442 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002443 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002444 diag::note_base_class_specified_here)
2445 << BaseSpec->getType()
2446 << BaseSpec->getSourceRange();
2447
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002448 TyD = Type;
2449 }
2450 }
2451 }
2452
Douglas Gregor7a886e12010-01-19 06:46:48 +00002453 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002454 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002455 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002456 return true;
2457 }
John McCall2b194412009-12-21 10:41:20 +00002458 }
2459
Douglas Gregor7a886e12010-01-19 06:46:48 +00002460 if (BaseType.isNull()) {
2461 BaseType = Context.getTypeDeclType(TyD);
2462 if (SS.isSet()) {
2463 NestedNameSpecifier *Qualifier =
2464 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002465
Douglas Gregor7a886e12010-01-19 06:46:48 +00002466 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002467 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002468 }
John McCall2b194412009-12-21 10:41:20 +00002469 }
2470 }
Mike Stump1eb44332009-09-09 15:08:12 +00002471
John McCalla93c9342009-12-07 02:54:59 +00002472 if (!TInfo)
2473 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002474
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002475 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002476}
2477
Chandler Carruth81c64772011-09-03 01:14:15 +00002478/// Checks a member initializer expression for cases where reference (or
2479/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002480static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2481 Expr *Init,
2482 SourceLocation IdLoc) {
2483 QualType MemberTy = Member->getType();
2484
2485 // We only handle pointers and references currently.
2486 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2487 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2488 return;
2489
2490 const bool IsPointer = MemberTy->isPointerType();
2491 if (IsPointer) {
2492 if (const UnaryOperator *Op
2493 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2494 // The only case we're worried about with pointers requires taking the
2495 // address.
2496 if (Op->getOpcode() != UO_AddrOf)
2497 return;
2498
2499 Init = Op->getSubExpr();
2500 } else {
2501 // We only handle address-of expression initializers for pointers.
2502 return;
2503 }
2504 }
2505
Richard Smitha4bb99c2013-06-12 21:51:50 +00002506 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002507 // We only warn when referring to a non-reference parameter declaration.
2508 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2509 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002510 return;
2511
2512 S.Diag(Init->getExprLoc(),
2513 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2514 : diag::warn_bind_ref_member_to_parameter)
2515 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002516 } else {
2517 // Other initializers are fine.
2518 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002519 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002520
2521 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2522 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002523}
2524
John McCallf312b1e2010-08-26 23:41:50 +00002525MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002526Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002527 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002528 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2529 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2530 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002531 "Member must be a FieldDecl or IndirectFieldDecl");
2532
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002533 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002534 return true;
2535
Douglas Gregor464b2f02010-11-05 22:21:31 +00002536 if (Member->isInvalidDecl())
2537 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002538
John McCallb4190042009-11-04 23:02:40 +00002539 // Diagnose value-uses of fields to initialize themselves, e.g.
2540 // foo(foo)
2541 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002542 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002543 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002544 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002545 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002546 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002547 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002548 } else {
2549 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002550 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002551 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002552
Richard Trieude5e75c2012-06-14 23:11:34 +00002553 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2554 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002555 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002556 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002557 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002558 // initializing the i'th field, throw a warning if any of the >= i'th
2559 // fields are used, as they are not yet initialized.
2560 // Right now we are only handling the case where the i'th field uses
2561 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002562 // Also need to take into account that some fields may be initialized by
2563 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002564 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002565
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002566 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002567
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002568 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002569 // Can't check initialization for a member of dependent type or when
2570 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002571 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002572 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002573 bool InitList = false;
2574 if (isa<InitListExpr>(Init)) {
2575 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002576 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002577 }
2578
Chandler Carruth894aed92010-12-06 09:23:57 +00002579 // Initialize the member.
2580 InitializedEntity MemberEntity =
2581 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2582 : InitializedEntity::InitializeMember(IndirectMember, 0);
2583 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002584 InitList ? InitializationKind::CreateDirectList(IdLoc)
2585 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2586 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002587
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002588 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2589 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002590 if (MemberInit.isInvalid())
2591 return true;
2592
Richard Smith8a07cd32013-06-12 20:42:33 +00002593 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2594
Richard Smith41956372013-01-14 22:39:08 +00002595 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002596 // The initialization of each base and member constitutes a
2597 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002598 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002599 if (MemberInit.isInvalid())
2600 return true;
2601
Richard Smithc83c2302012-12-19 01:39:02 +00002602 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002603 }
2604
Chandler Carruth894aed92010-12-06 09:23:57 +00002605 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002606 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2607 InitRange.getBegin(), Init,
2608 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002609 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002610 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2611 InitRange.getBegin(), Init,
2612 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002613 }
Eli Friedman59c04372009-07-29 19:44:27 +00002614}
2615
John McCallf312b1e2010-08-26 23:41:50 +00002616MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002617Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002618 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002619 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002620 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002621 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002622 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002623 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002624
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002625 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002626 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002627 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2628 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002629 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002630 }
2631
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002632 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002633 // Initialize the object.
2634 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2635 QualType(ClassDecl->getTypeForDecl(), 0));
2636 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002637 InitList ? InitializationKind::CreateDirectList(NameLoc)
2638 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2639 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002640 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002641 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002642 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002643 if (DelegationInit.isInvalid())
2644 return true;
2645
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002646 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2647 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002648
Richard Smith41956372013-01-14 22:39:08 +00002649 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002650 // The initialization of each base and member constitutes a
2651 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002652 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2653 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002654 if (DelegationInit.isInvalid())
2655 return true;
2656
Eli Friedmand21016f2012-05-19 23:35:23 +00002657 // If we are in a dependent context, template instantiation will
2658 // perform this type-checking again. Just save the arguments that we
2659 // received in a ParenListExpr.
2660 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2661 // of the information that we have about the base
2662 // initializer. However, deconstructing the ASTs is a dicey process,
2663 // and this approach is far more likely to get the corner cases right.
2664 if (CurContext->isDependentContext())
2665 DelegationInit = Owned(Init);
2666
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002667 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002668 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002669 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002670}
2671
2672MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002673Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002674 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002675 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002676 SourceLocation BaseLoc
2677 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002678
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002679 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2680 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2681 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2682
2683 // C++ [class.base.init]p2:
2684 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002685 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002686 // of that class, the mem-initializer is ill-formed. A
2687 // mem-initializer-list can initialize a base class using any
2688 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002689 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002690
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002691 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002692 if (EllipsisLoc.isValid()) {
2693 // This is a pack expansion.
2694 if (!BaseType->containsUnexpandedParameterPack()) {
2695 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002696 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002697
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002698 EllipsisLoc = SourceLocation();
2699 }
2700 } else {
2701 // Check for any unexpanded parameter packs.
2702 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2703 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002704
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002705 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002706 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002707 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002708
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002709 // Check for direct and virtual base classes.
2710 const CXXBaseSpecifier *DirectBaseSpec = 0;
2711 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2712 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002713 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2714 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002715 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002716
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002717 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2718 VirtualBaseSpec);
2719
2720 // C++ [base.class.init]p2:
2721 // Unless the mem-initializer-id names a nonstatic data member of the
2722 // constructor's class or a direct or virtual base of that class, the
2723 // mem-initializer is ill-formed.
2724 if (!DirectBaseSpec && !VirtualBaseSpec) {
2725 // If the class has any dependent bases, then it's possible that
2726 // one of those types will resolve to the same type as
2727 // BaseType. Therefore, just treat this as a dependent base
2728 // class initialization. FIXME: Should we try to check the
2729 // initialization anyway? It seems odd.
2730 if (ClassDecl->hasAnyDependentBases())
2731 Dependent = true;
2732 else
2733 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2734 << BaseType << Context.getTypeDeclType(ClassDecl)
2735 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2736 }
2737 }
2738
2739 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002740 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Sebastian Redl6df65482011-09-24 17:48:25 +00002742 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2743 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002744 InitRange.getBegin(), Init,
2745 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002746 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002747
2748 // C++ [base.class.init]p2:
2749 // If a mem-initializer-id is ambiguous because it designates both
2750 // a direct non-virtual base class and an inherited virtual base
2751 // class, the mem-initializer is ill-formed.
2752 if (DirectBaseSpec && VirtualBaseSpec)
2753 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002754 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002755
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002756 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002757 if (!BaseSpec)
2758 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2759
2760 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002761 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002762 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002763 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002764 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002765 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002766 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002767
2768 InitializedEntity BaseEntity =
2769 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2770 InitializationKind Kind =
2771 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2772 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2773 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002774 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2775 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002776 if (BaseInit.isInvalid())
2777 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002778
Richard Smith41956372013-01-14 22:39:08 +00002779 // C++11 [class.base.init]p7:
2780 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002781 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002782 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002783 if (BaseInit.isInvalid())
2784 return true;
2785
2786 // If we are in a dependent context, template instantiation will
2787 // perform this type-checking again. Just save the arguments that we
2788 // received in a ParenListExpr.
2789 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2790 // of the information that we have about the base
2791 // initializer. However, deconstructing the ASTs is a dicey process,
2792 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002793 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002794 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002795
Sean Huntcbb67482011-01-08 20:30:50 +00002796 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002797 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002798 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002799 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002800 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002801}
2802
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002803// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002804static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2805 if (T.isNull()) T = E->getType();
2806 QualType TargetType = SemaRef.BuildReferenceType(
2807 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002808 SourceLocation ExprLoc = E->getLocStart();
2809 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2810 TargetType, ExprLoc);
2811
2812 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2813 SourceRange(ExprLoc, ExprLoc),
2814 E->getSourceRange()).take();
2815}
2816
Anders Carlssone5ef7402010-04-23 03:10:23 +00002817/// ImplicitInitializerKind - How an implicit base or member initializer should
2818/// initialize its base or member.
2819enum ImplicitInitializerKind {
2820 IIK_Default,
2821 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002822 IIK_Move,
2823 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002824};
2825
Anders Carlssondefefd22010-04-23 02:00:02 +00002826static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002827BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002828 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002829 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002830 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002831 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002832 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002833 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2834 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002835
John McCall60d7b3a2010-08-24 06:29:42 +00002836 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002837
2838 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002839 case IIK_Inherit: {
2840 const CXXRecordDecl *Inherited =
2841 Constructor->getInheritedConstructor()->getParent();
2842 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2843 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2844 // C++11 [class.inhctor]p8:
2845 // Each expression in the expression-list is of the form
2846 // static_cast<T&&>(p), where p is the name of the corresponding
2847 // constructor parameter and T is the declared type of p.
2848 SmallVector<Expr*, 16> Args;
2849 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2850 ParmVarDecl *PD = Constructor->getParamDecl(I);
2851 ExprResult ArgExpr =
2852 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2853 VK_LValue, SourceLocation());
2854 if (ArgExpr.isInvalid())
2855 return true;
2856 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2857 }
2858
2859 InitializationKind InitKind = InitializationKind::CreateDirect(
2860 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002861 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002862 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2863 break;
2864 }
2865 }
2866 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002867 case IIK_Default: {
2868 InitializationKind InitKind
2869 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002870 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2871 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002872 break;
2873 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002874
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002875 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002876 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002877 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002878 ParmVarDecl *Param = Constructor->getParamDecl(0);
2879 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002880
Anders Carlssone5ef7402010-04-23 03:10:23 +00002881 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002882 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002883 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002884 Constructor->getLocation(), ParamType,
2885 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002886
Eli Friedman5f2987c2012-02-02 03:46:19 +00002887 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2888
Anders Carlssonc7957502010-04-24 22:02:54 +00002889 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002890 QualType ArgTy =
2891 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2892 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002893
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002894 if (Moving) {
2895 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2896 }
2897
John McCallf871d0c2010-08-07 06:22:56 +00002898 CXXCastPath BasePath;
2899 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002900 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2901 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002902 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002903 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002904
Anders Carlssone5ef7402010-04-23 03:10:23 +00002905 InitializationKind InitKind
2906 = InitializationKind::CreateDirect(Constructor->getLocation(),
2907 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002908 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2909 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002910 break;
2911 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002912 }
John McCall9ae2f072010-08-23 23:25:46 +00002913
Douglas Gregor53c374f2010-12-07 00:41:46 +00002914 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002915 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002916 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002917
Anders Carlssondefefd22010-04-23 02:00:02 +00002918 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002919 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002920 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2921 SourceLocation()),
2922 BaseSpec->isVirtual(),
2923 SourceLocation(),
2924 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002925 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002926 SourceLocation());
2927
Anders Carlssondefefd22010-04-23 02:00:02 +00002928 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002929}
2930
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002931static bool RefersToRValueRef(Expr *MemRef) {
2932 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2933 return Referenced->getType()->isRValueReferenceType();
2934}
2935
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002936static bool
2937BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002938 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002939 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002940 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002941 if (Field->isInvalidDecl())
2942 return true;
2943
Chandler Carruthf186b542010-06-29 23:50:44 +00002944 SourceLocation Loc = Constructor->getLocation();
2945
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002946 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2947 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002948 ParmVarDecl *Param = Constructor->getParamDecl(0);
2949 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002950
2951 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002952 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2953 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002954
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002955 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002956 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002957 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002958 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002959
Eli Friedman5f2987c2012-02-02 03:46:19 +00002960 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2961
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002962 if (Moving) {
2963 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2964 }
2965
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002966 // Build a reference to this field within the parameter.
2967 CXXScopeSpec SS;
2968 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2969 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002970 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2971 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002972 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002973 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002974 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002975 ParamType, Loc,
2976 /*IsArrow=*/false,
2977 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002978 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002979 /*FirstQualifierInScope=*/0,
2980 MemberLookup,
2981 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002982 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002983 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002984
2985 // C++11 [class.copy]p15:
2986 // - if a member m has rvalue reference type T&&, it is direct-initialized
2987 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002988 if (RefersToRValueRef(CtorArg.get())) {
2989 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002990 }
2991
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002992 // When the field we are copying is an array, create index variables for
2993 // each dimension of the array. We use these index variables to subscript
2994 // the source array, and other clients (e.g., CodeGen) will perform the
2995 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002996 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002997 QualType BaseType = Field->getType();
2998 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002999 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003000 while (const ConstantArrayType *Array
3001 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003002 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003003 // Create the iteration variable for this array index.
3004 IdentifierInfo *IterationVarName = 0;
3005 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003006 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003007 llvm::raw_svector_ostream OS(Str);
3008 OS << "__i" << IndexVariables.size();
3009 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3010 }
3011 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003012 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003013 IterationVarName, SizeType,
3014 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003015 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003016 IndexVariables.push_back(IterationVar);
3017
3018 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003019 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003020 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003021 assert(!IterationVarRef.isInvalid() &&
3022 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003023 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3024 assert(!IterationVarRef.isInvalid() &&
3025 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003026
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003027 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003028 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003029 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003030 Loc);
3031 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003032 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003033
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003034 BaseType = Array->getElementType();
3035 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003036
3037 // The array subscript expression is an lvalue, which is wrong for moving.
3038 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003039 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003040
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003041 // Construct the entity that we will be initializing. For an array, this
3042 // will be first element in the array, which may require several levels
3043 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003044 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003045 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003046 if (Indirect)
3047 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3048 else
3049 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003050 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3051 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3052 0,
3053 Entities.back()));
3054
3055 // Direct-initialize to use the copy constructor.
3056 InitializationKind InitKind =
3057 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3058
Sebastian Redl74e611a2011-09-04 18:14:28 +00003059 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003060 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003061
John McCall60d7b3a2010-08-24 06:29:42 +00003062 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003063 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003064 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003065 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003066 if (MemberInit.isInvalid())
3067 return true;
3068
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003069 if (Indirect) {
3070 assert(IndexVariables.size() == 0 &&
3071 "Indirect field improperly initialized");
3072 CXXMemberInit
3073 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3074 Loc, Loc,
3075 MemberInit.takeAs<Expr>(),
3076 Loc);
3077 } else
3078 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3079 Loc, MemberInit.takeAs<Expr>(),
3080 Loc,
3081 IndexVariables.data(),
3082 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003083 return false;
3084 }
3085
Richard Smith07b0fdc2013-03-18 21:12:30 +00003086 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3087 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003088
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003089 QualType FieldBaseElementType =
3090 SemaRef.Context.getBaseElementType(Field->getType());
3091
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003092 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003093 InitializedEntity InitEntity
3094 = Indirect? InitializedEntity::InitializeMember(Indirect)
3095 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003096 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003097 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003098
3099 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3100 ExprResult MemberInit =
3101 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003102
Douglas Gregor53c374f2010-12-07 00:41:46 +00003103 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003104 if (MemberInit.isInvalid())
3105 return true;
3106
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003107 if (Indirect)
3108 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3109 Indirect, Loc,
3110 Loc,
3111 MemberInit.get(),
3112 Loc);
3113 else
3114 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3115 Field, Loc, Loc,
3116 MemberInit.get(),
3117 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003118 return false;
3119 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003120
Sean Hunt1f2f3842011-05-17 00:19:05 +00003121 if (!Field->getParent()->isUnion()) {
3122 if (FieldBaseElementType->isReferenceType()) {
3123 SemaRef.Diag(Constructor->getLocation(),
3124 diag::err_uninitialized_member_in_ctor)
3125 << (int)Constructor->isImplicit()
3126 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3127 << 0 << Field->getDeclName();
3128 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3129 return true;
3130 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003131
Sean Hunt1f2f3842011-05-17 00:19:05 +00003132 if (FieldBaseElementType.isConstQualified()) {
3133 SemaRef.Diag(Constructor->getLocation(),
3134 diag::err_uninitialized_member_in_ctor)
3135 << (int)Constructor->isImplicit()
3136 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3137 << 1 << Field->getDeclName();
3138 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3139 return true;
3140 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003141 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003142
David Blaikie4e4d0842012-03-11 07:00:24 +00003143 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003144 FieldBaseElementType->isObjCRetainableType() &&
3145 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3146 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003147 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003148 // Default-initialize Objective-C pointers to NULL.
3149 CXXMemberInit
3150 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3151 Loc, Loc,
3152 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3153 Loc);
3154 return false;
3155 }
3156
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003157 // Nothing to initialize.
3158 CXXMemberInit = 0;
3159 return false;
3160}
John McCallf1860e52010-05-20 23:23:51 +00003161
3162namespace {
3163struct BaseAndFieldInfo {
3164 Sema &S;
3165 CXXConstructorDecl *Ctor;
3166 bool AnyErrorsInInits;
3167 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003168 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003169 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003170
3171 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3172 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003173 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3174 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003175 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003176 else if (Generated && Ctor->isMoveConstructor())
3177 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003178 else if (Ctor->getInheritedConstructor())
3179 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003180 else
3181 IIK = IIK_Default;
3182 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003183
3184 bool isImplicitCopyOrMove() const {
3185 switch (IIK) {
3186 case IIK_Copy:
3187 case IIK_Move:
3188 return true;
3189
3190 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003191 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003192 return false;
3193 }
David Blaikie30263482012-01-20 21:50:17 +00003194
3195 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003196 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003197
3198 bool addFieldInitializer(CXXCtorInitializer *Init) {
3199 AllToInit.push_back(Init);
3200
3201 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003202 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003203 S.UnusedPrivateFields.remove(Init->getAnyMember());
3204
3205 return false;
3206 }
John McCallf1860e52010-05-20 23:23:51 +00003207};
3208}
3209
Richard Smitha4950662011-09-19 13:34:43 +00003210/// \brief Determine whether the given indirect field declaration is somewhere
3211/// within an anonymous union.
3212static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3213 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3214 CEnd = F->chain_end();
3215 C != CEnd; ++C)
3216 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3217 if (Record->isUnion())
3218 return true;
3219
3220 return false;
3221}
3222
Douglas Gregorddb21472011-11-02 23:04:16 +00003223/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3224/// array type.
3225static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3226 if (T->isIncompleteArrayType())
3227 return true;
3228
3229 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3230 if (!ArrayT->getSize())
3231 return true;
3232
3233 T = ArrayT->getElementType();
3234 }
3235
3236 return false;
3237}
3238
Richard Smith7a614d82011-06-11 17:19:42 +00003239static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003240 FieldDecl *Field,
3241 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003242 if (Field->isInvalidDecl())
3243 return false;
John McCallf1860e52010-05-20 23:23:51 +00003244
Chandler Carruthe861c602010-06-30 02:59:29 +00003245 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003246 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3247 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003248
Richard Smith0b8220a2012-08-07 21:30:42 +00003249 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003250 // has a brace-or-equal-initializer, the entity is initialized as specified
3251 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003252 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003253 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3254 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003255 CXXCtorInitializer *Init;
3256 if (Indirect)
3257 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3258 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003259 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003260 SourceLocation());
3261 else
3262 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3263 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003264 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003265 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003266 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003267 }
3268
Richard Smithc115f632011-09-18 11:14:50 +00003269 // Don't build an implicit initializer for union members if none was
3270 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003271 if (Field->getParent()->isUnion() ||
3272 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003273 return false;
3274
Douglas Gregorddb21472011-11-02 23:04:16 +00003275 // Don't initialize incomplete or zero-length arrays.
3276 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3277 return false;
3278
John McCallf1860e52010-05-20 23:23:51 +00003279 // Don't try to build an implicit initializer if there were semantic
3280 // errors in any of the initializers (and therefore we might be
3281 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003282 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003283 return false;
3284
Sean Huntcbb67482011-01-08 20:30:50 +00003285 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003286 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3287 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003288 return true;
John McCallf1860e52010-05-20 23:23:51 +00003289
Richard Smith0b8220a2012-08-07 21:30:42 +00003290 if (!Init)
3291 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003292
Richard Smith0b8220a2012-08-07 21:30:42 +00003293 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003294}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003295
3296bool
3297Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3298 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003299 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003300 Constructor->setNumCtorInitializers(1);
3301 CXXCtorInitializer **initializer =
3302 new (Context) CXXCtorInitializer*[1];
3303 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3304 Constructor->setCtorInitializers(initializer);
3305
Sean Huntb76af9c2011-05-03 23:05:34 +00003306 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003307 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003308 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3309 }
3310
Sean Huntc1598702011-05-05 00:05:47 +00003311 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003312
Sean Hunt059ce0d2011-05-01 07:04:31 +00003313 return false;
3314}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003315
David Blaikie93c86172013-01-17 05:26:25 +00003316bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3317 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003318 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003319 // Just store the initializers as written, they will be checked during
3320 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003321 if (!Initializers.empty()) {
3322 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003323 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003324 new (Context) CXXCtorInitializer*[Initializers.size()];
3325 memcpy(baseOrMemberInitializers, Initializers.data(),
3326 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003327 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003328 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003329
3330 // Let template instantiation know whether we had errors.
3331 if (AnyErrors)
3332 Constructor->setInvalidDecl();
3333
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003334 return false;
3335 }
3336
John McCallf1860e52010-05-20 23:23:51 +00003337 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003338
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003339 // We need to build the initializer AST according to order of construction
3340 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003341 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003342 if (!ClassDecl)
3343 return true;
3344
Eli Friedman80c30da2009-11-09 19:20:36 +00003345 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003346
David Blaikie93c86172013-01-17 05:26:25 +00003347 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003348 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003349
3350 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003351 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003352 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003353 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003354 }
3355
Anders Carlsson711f34a2010-04-21 19:52:01 +00003356 // Keep track of the direct virtual bases.
3357 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3358 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3359 E = ClassDecl->bases_end(); I != E; ++I) {
3360 if (I->isVirtual())
3361 DirectVBases.insert(I);
3362 }
3363
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003364 // Push virtual bases before others.
3365 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3366 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3367
Sean Huntcbb67482011-01-08 20:30:50 +00003368 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003369 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3370 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003371 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003372 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003373 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003374 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003375 VBase, IsInheritedVirtualBase,
3376 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003377 HadError = true;
3378 continue;
3379 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003380
John McCallf1860e52010-05-20 23:23:51 +00003381 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003382 }
3383 }
Mike Stump1eb44332009-09-09 15:08:12 +00003384
John McCallf1860e52010-05-20 23:23:51 +00003385 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003386 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3387 E = ClassDecl->bases_end(); Base != E; ++Base) {
3388 // Virtuals are in the virtual base list and already constructed.
3389 if (Base->isVirtual())
3390 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Sean Huntcbb67482011-01-08 20:30:50 +00003392 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003393 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3394 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003395 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003396 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003397 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003398 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003399 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003400 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003401 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003402 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003403
John McCallf1860e52010-05-20 23:23:51 +00003404 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003405 }
3406 }
Mike Stump1eb44332009-09-09 15:08:12 +00003407
John McCallf1860e52010-05-20 23:23:51 +00003408 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003409 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3410 MemEnd = ClassDecl->decls_end();
3411 Mem != MemEnd; ++Mem) {
3412 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003413 // C++ [class.bit]p2:
3414 // A declaration for a bit-field that omits the identifier declares an
3415 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3416 // initialized.
3417 if (F->isUnnamedBitfield())
3418 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003419
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003420 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003421 // handle anonymous struct/union fields based on their individual
3422 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003423 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003424 continue;
3425
3426 if (CollectFieldInitializer(*this, Info, F))
3427 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003428 continue;
3429 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003430
3431 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003432 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003433 continue;
3434
3435 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3436 if (F->getType()->isIncompleteArrayType()) {
3437 assert(ClassDecl->hasFlexibleArrayMember() &&
3438 "Incomplete array type is not valid");
3439 continue;
3440 }
3441
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003442 // Initialize each field of an anonymous struct individually.
3443 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3444 HadError = true;
3445
3446 continue;
3447 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003448 }
Mike Stump1eb44332009-09-09 15:08:12 +00003449
David Blaikie93c86172013-01-17 05:26:25 +00003450 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003451 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003452 Constructor->setNumCtorInitializers(NumInitializers);
3453 CXXCtorInitializer **baseOrMemberInitializers =
3454 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003455 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003456 NumInitializers * sizeof(CXXCtorInitializer*));
3457 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003458
John McCallef027fe2010-03-16 21:39:52 +00003459 // Constructors implicitly reference the base and member
3460 // destructors.
3461 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3462 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003463 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003464
3465 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003466}
3467
David Blaikieee000bb2013-01-17 08:49:22 +00003468static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003469 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003470 const RecordDecl *RD = RT->getDecl();
3471 if (RD->isAnonymousStructOrUnion()) {
3472 for (RecordDecl::field_iterator Field = RD->field_begin(),
3473 E = RD->field_end(); Field != E; ++Field)
3474 PopulateKeysForFields(*Field, IdealInits);
3475 return;
3476 }
Eli Friedman6347f422009-07-21 19:28:10 +00003477 }
David Blaikieee000bb2013-01-17 08:49:22 +00003478 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003479}
3480
Anders Carlssonea356fb2010-04-02 05:42:15 +00003481static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003482 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003483}
3484
Anders Carlssonea356fb2010-04-02 05:42:15 +00003485static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003486 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003487 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003488 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003489
David Blaikieee000bb2013-01-17 08:49:22 +00003490 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003491}
3492
David Blaikie93c86172013-01-17 05:26:25 +00003493static void DiagnoseBaseOrMemInitializerOrder(
3494 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3495 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003496 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003497 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003498
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003499 // Don't check initializers order unless the warning is enabled at the
3500 // location of at least one initializer.
3501 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003502 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003503 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003504 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3505 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003506 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003507 ShouldCheckOrder = true;
3508 break;
3509 }
3510 }
3511 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003512 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003513
John McCalld6ca8da2010-04-10 07:37:23 +00003514 // Build the list of bases and members in the order that they'll
3515 // actually be initialized. The explicit initializers should be in
3516 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003517 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003518
Anders Carlsson071d6102010-04-02 03:38:04 +00003519 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3520
John McCalld6ca8da2010-04-10 07:37:23 +00003521 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003522 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003523 ClassDecl->vbases_begin(),
3524 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003525 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003526
John McCalld6ca8da2010-04-10 07:37:23 +00003527 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003528 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003529 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003530 if (Base->isVirtual())
3531 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003532 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003533 }
Mike Stump1eb44332009-09-09 15:08:12 +00003534
John McCalld6ca8da2010-04-10 07:37:23 +00003535 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003536 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003537 E = ClassDecl->field_end(); Field != E; ++Field) {
3538 if (Field->isUnnamedBitfield())
3539 continue;
3540
David Blaikieee000bb2013-01-17 08:49:22 +00003541 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003542 }
3543
John McCalld6ca8da2010-04-10 07:37:23 +00003544 unsigned NumIdealInits = IdealInitKeys.size();
3545 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003546
Sean Huntcbb67482011-01-08 20:30:50 +00003547 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003548 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003549 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003550 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003551
3552 // Scan forward to try to find this initializer in the idealized
3553 // initializers list.
3554 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3555 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003556 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003557
3558 // If we didn't find this initializer, it must be because we
3559 // scanned past it on a previous iteration. That can only
3560 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003561 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003562 Sema::SemaDiagnosticBuilder D =
3563 SemaRef.Diag(PrevInit->getSourceLocation(),
3564 diag::warn_initializer_out_of_order);
3565
Francois Pichet00eb3f92010-12-04 09:14:42 +00003566 if (PrevInit->isAnyMemberInitializer())
3567 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003568 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003569 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003570
Francois Pichet00eb3f92010-12-04 09:14:42 +00003571 if (Init->isAnyMemberInitializer())
3572 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003573 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003574 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003575
3576 // Move back to the initializer's location in the ideal list.
3577 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3578 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003579 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003580
3581 assert(IdealIndex != NumIdealInits &&
3582 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003583 }
John McCalld6ca8da2010-04-10 07:37:23 +00003584
3585 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003586 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003587}
3588
John McCall3c3ccdb2010-04-10 09:28:51 +00003589namespace {
3590bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003591 CXXCtorInitializer *Init,
3592 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003593 if (!PrevInit) {
3594 PrevInit = Init;
3595 return false;
3596 }
3597
Douglas Gregordc392c12013-03-25 23:28:23 +00003598 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003599 S.Diag(Init->getSourceLocation(),
3600 diag::err_multiple_mem_initialization)
3601 << Field->getDeclName()
3602 << Init->getSourceRange();
3603 else {
John McCallf4c73712011-01-19 06:33:43 +00003604 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003605 assert(BaseClass && "neither field nor base");
3606 S.Diag(Init->getSourceLocation(),
3607 diag::err_multiple_base_initialization)
3608 << QualType(BaseClass, 0)
3609 << Init->getSourceRange();
3610 }
3611 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3612 << 0 << PrevInit->getSourceRange();
3613
3614 return true;
3615}
3616
Sean Huntcbb67482011-01-08 20:30:50 +00003617typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003618typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3619
3620bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003621 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003622 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003623 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003624 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003625 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003626
3627 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003628 if (Parent->isUnion()) {
3629 UnionEntry &En = Unions[Parent];
3630 if (En.first && En.first != Child) {
3631 S.Diag(Init->getSourceLocation(),
3632 diag::err_multiple_mem_union_initialization)
3633 << Field->getDeclName()
3634 << Init->getSourceRange();
3635 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3636 << 0 << En.second->getSourceRange();
3637 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003638 }
3639 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003640 En.first = Child;
3641 En.second = Init;
3642 }
David Blaikie6fe29652011-11-17 06:01:57 +00003643 if (!Parent->isAnonymousStructOrUnion())
3644 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003645 }
3646
3647 Child = Parent;
3648 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003649 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003650
3651 return false;
3652}
3653}
3654
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003655/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003656void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003657 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003658 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003659 bool AnyErrors) {
3660 if (!ConstructorDecl)
3661 return;
3662
3663 AdjustDeclIfTemplate(ConstructorDecl);
3664
3665 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003666 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003667
3668 if (!Constructor) {
3669 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3670 return;
3671 }
3672
John McCall3c3ccdb2010-04-10 09:28:51 +00003673 // Mapping for the duplicate initializers check.
3674 // For member initializers, this is keyed with a FieldDecl*.
3675 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003676 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003677
3678 // Mapping for the inconsistent anonymous-union initializers check.
3679 RedundantUnionMap MemberUnions;
3680
Anders Carlssonea356fb2010-04-02 05:42:15 +00003681 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003682 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003683 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003684
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003685 // Set the source order index.
3686 Init->setSourceOrder(i);
3687
Francois Pichet00eb3f92010-12-04 09:14:42 +00003688 if (Init->isAnyMemberInitializer()) {
3689 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003690 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3691 CheckRedundantUnionInit(*this, Init, MemberUnions))
3692 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003693 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003694 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3695 if (CheckRedundantInit(*this, Init, Members[Key]))
3696 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003697 } else {
3698 assert(Init->isDelegatingInitializer());
3699 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003700 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003701 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003702 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003703 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003704 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003705 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003706 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003707 // Return immediately as the initializer is set.
3708 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003709 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003710 }
3711
Anders Carlssonea356fb2010-04-02 05:42:15 +00003712 if (HadError)
3713 return;
3714
David Blaikie93c86172013-01-17 05:26:25 +00003715 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003716
David Blaikie93c86172013-01-17 05:26:25 +00003717 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003718}
3719
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003720void
John McCallef027fe2010-03-16 21:39:52 +00003721Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3722 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003723 // Ignore dependent contexts. Also ignore unions, since their members never
3724 // have destructors implicitly called.
3725 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003726 return;
John McCall58e6f342010-03-16 05:22:47 +00003727
3728 // FIXME: all the access-control diagnostics are positioned on the
3729 // field/base declaration. That's probably good; that said, the
3730 // user might reasonably want to know why the destructor is being
3731 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003732
Anders Carlsson9f853df2009-11-17 04:44:12 +00003733 // Non-static data members.
3734 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3735 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003736 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003737 if (Field->isInvalidDecl())
3738 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003739
3740 // Don't destroy incomplete or zero-length arrays.
3741 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3742 continue;
3743
Anders Carlsson9f853df2009-11-17 04:44:12 +00003744 QualType FieldType = Context.getBaseElementType(Field->getType());
3745
3746 const RecordType* RT = FieldType->getAs<RecordType>();
3747 if (!RT)
3748 continue;
3749
3750 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003751 if (FieldClassDecl->isInvalidDecl())
3752 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003753 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003754 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003755 // The destructor for an implicit anonymous union member is never invoked.
3756 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3757 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003758
Douglas Gregordb89f282010-07-01 22:47:18 +00003759 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003760 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003761 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003762 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003763 << Field->getDeclName()
3764 << FieldType);
3765
Eli Friedman5f2987c2012-02-02 03:46:19 +00003766 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003767 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003768 }
3769
John McCall58e6f342010-03-16 05:22:47 +00003770 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3771
Anders Carlsson9f853df2009-11-17 04:44:12 +00003772 // Bases.
3773 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3774 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003775 // Bases are always records in a well-formed non-dependent class.
3776 const RecordType *RT = Base->getType()->getAs<RecordType>();
3777
3778 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003779 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003780 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003781
John McCall58e6f342010-03-16 05:22:47 +00003782 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003783 // If our base class is invalid, we probably can't get its dtor anyway.
3784 if (BaseClassDecl->isInvalidDecl())
3785 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003786 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003787 continue;
John McCall58e6f342010-03-16 05:22:47 +00003788
Douglas Gregordb89f282010-07-01 22:47:18 +00003789 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003790 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003791
3792 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003793 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003794 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003795 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003796 << Base->getSourceRange(),
3797 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003798
Eli Friedman5f2987c2012-02-02 03:46:19 +00003799 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003800 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003801 }
3802
3803 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003804 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3805 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003806
3807 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003808 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003809
3810 // Ignore direct virtual bases.
3811 if (DirectVirtualBases.count(RT))
3812 continue;
3813
John McCall58e6f342010-03-16 05:22:47 +00003814 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003815 // If our base class is invalid, we probably can't get its dtor anyway.
3816 if (BaseClassDecl->isInvalidDecl())
3817 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003818 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003819 continue;
John McCall58e6f342010-03-16 05:22:47 +00003820
Douglas Gregordb89f282010-07-01 22:47:18 +00003821 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003822 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00003823 if (CheckDestructorAccess(
3824 ClassDecl->getLocation(), Dtor,
3825 PDiag(diag::err_access_dtor_vbase)
3826 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3827 Context.getTypeDeclType(ClassDecl)) ==
3828 AR_accessible) {
3829 CheckDerivedToBaseConversion(
3830 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3831 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3832 SourceRange(), DeclarationName(), 0);
3833 }
John McCall58e6f342010-03-16 05:22:47 +00003834
Eli Friedman5f2987c2012-02-02 03:46:19 +00003835 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003836 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003837 }
3838}
3839
John McCalld226f652010-08-21 09:40:31 +00003840void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003841 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003842 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003843
Mike Stump1eb44332009-09-09 15:08:12 +00003844 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003845 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003846 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003847}
3848
Mike Stump1eb44332009-09-09 15:08:12 +00003849bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003850 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003851 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3852 unsigned DiagID;
3853 AbstractDiagSelID SelID;
3854
3855 public:
3856 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3857 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3858
3859 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003860 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003861 if (SelID == -1)
3862 S.Diag(Loc, DiagID) << T;
3863 else
3864 S.Diag(Loc, DiagID) << SelID << T;
3865 }
3866 } Diagnoser(DiagID, SelID);
3867
3868 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003869}
3870
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003871bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003872 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003873 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003874 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003875
Anders Carlsson11f21a02009-03-23 19:10:31 +00003876 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003877 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003878
Ted Kremenek6217b802009-07-29 21:53:49 +00003879 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003880 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003881 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003882 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003883
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003884 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003885 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003886 }
Mike Stump1eb44332009-09-09 15:08:12 +00003887
Ted Kremenek6217b802009-07-29 21:53:49 +00003888 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003889 if (!RT)
3890 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003891
John McCall86ff3082010-02-04 22:26:26 +00003892 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003893
John McCall94c3b562010-08-18 09:41:07 +00003894 // We can't answer whether something is abstract until it has a
3895 // definition. If it's currently being defined, we'll walk back
3896 // over all the declarations when we have a full definition.
3897 const CXXRecordDecl *Def = RD->getDefinition();
3898 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003899 return false;
3900
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003901 if (!RD->isAbstract())
3902 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003903
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003904 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003905 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003906
John McCall94c3b562010-08-18 09:41:07 +00003907 return true;
3908}
3909
3910void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3911 // Check if we've already emitted the list of pure virtual functions
3912 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003913 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003914 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003915
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003916 CXXFinalOverriderMap FinalOverriders;
3917 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003918
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003919 // Keep a set of seen pure methods so we won't diagnose the same method
3920 // more than once.
3921 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3922
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003923 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3924 MEnd = FinalOverriders.end();
3925 M != MEnd;
3926 ++M) {
3927 for (OverridingMethods::iterator SO = M->second.begin(),
3928 SOEnd = M->second.end();
3929 SO != SOEnd; ++SO) {
3930 // C++ [class.abstract]p4:
3931 // A class is abstract if it contains or inherits at least one
3932 // pure virtual function for which the final overrider is pure
3933 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003934
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003935 //
3936 if (SO->second.size() != 1)
3937 continue;
3938
3939 if (!SO->second.front().Method->isPure())
3940 continue;
3941
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003942 if (!SeenPureMethods.insert(SO->second.front().Method))
3943 continue;
3944
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003945 Diag(SO->second.front().Method->getLocation(),
3946 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003947 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003948 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003949 }
3950
3951 if (!PureVirtualClassDiagSet)
3952 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3953 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003954}
3955
Anders Carlsson8211eff2009-03-24 01:19:16 +00003956namespace {
John McCall94c3b562010-08-18 09:41:07 +00003957struct AbstractUsageInfo {
3958 Sema &S;
3959 CXXRecordDecl *Record;
3960 CanQualType AbstractType;
3961 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003962
John McCall94c3b562010-08-18 09:41:07 +00003963 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3964 : S(S), Record(Record),
3965 AbstractType(S.Context.getCanonicalType(
3966 S.Context.getTypeDeclType(Record))),
3967 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003968
John McCall94c3b562010-08-18 09:41:07 +00003969 void DiagnoseAbstractType() {
3970 if (Invalid) return;
3971 S.DiagnoseAbstractType(Record);
3972 Invalid = true;
3973 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003974
John McCall94c3b562010-08-18 09:41:07 +00003975 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3976};
3977
3978struct CheckAbstractUsage {
3979 AbstractUsageInfo &Info;
3980 const NamedDecl *Ctx;
3981
3982 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3983 : Info(Info), Ctx(Ctx) {}
3984
3985 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3986 switch (TL.getTypeLocClass()) {
3987#define ABSTRACT_TYPELOC(CLASS, PARENT)
3988#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003989 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003990#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003991 }
John McCall94c3b562010-08-18 09:41:07 +00003992 }
Mike Stump1eb44332009-09-09 15:08:12 +00003993
John McCall94c3b562010-08-18 09:41:07 +00003994 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3995 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3996 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003997 if (!TL.getArg(I))
3998 continue;
3999
John McCall94c3b562010-08-18 09:41:07 +00004000 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4001 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004002 }
John McCall94c3b562010-08-18 09:41:07 +00004003 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004004
John McCall94c3b562010-08-18 09:41:07 +00004005 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4006 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4007 }
Mike Stump1eb44332009-09-09 15:08:12 +00004008
John McCall94c3b562010-08-18 09:41:07 +00004009 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4010 // Visit the type parameters from a permissive context.
4011 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4012 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4013 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4014 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4015 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4016 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004017 }
John McCall94c3b562010-08-18 09:41:07 +00004018 }
Mike Stump1eb44332009-09-09 15:08:12 +00004019
John McCall94c3b562010-08-18 09:41:07 +00004020 // Visit pointee types from a permissive context.
4021#define CheckPolymorphic(Type) \
4022 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4023 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4024 }
4025 CheckPolymorphic(PointerTypeLoc)
4026 CheckPolymorphic(ReferenceTypeLoc)
4027 CheckPolymorphic(MemberPointerTypeLoc)
4028 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004029 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004030
John McCall94c3b562010-08-18 09:41:07 +00004031 /// Handle all the types we haven't given a more specific
4032 /// implementation for above.
4033 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4034 // Every other kind of type that we haven't called out already
4035 // that has an inner type is either (1) sugar or (2) contains that
4036 // inner type in some way as a subobject.
4037 if (TypeLoc Next = TL.getNextTypeLoc())
4038 return Visit(Next, Sel);
4039
4040 // If there's no inner type and we're in a permissive context,
4041 // don't diagnose.
4042 if (Sel == Sema::AbstractNone) return;
4043
4044 // Check whether the type matches the abstract type.
4045 QualType T = TL.getType();
4046 if (T->isArrayType()) {
4047 Sel = Sema::AbstractArrayType;
4048 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004049 }
John McCall94c3b562010-08-18 09:41:07 +00004050 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4051 if (CT != Info.AbstractType) return;
4052
4053 // It matched; do some magic.
4054 if (Sel == Sema::AbstractArrayType) {
4055 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4056 << T << TL.getSourceRange();
4057 } else {
4058 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4059 << Sel << T << TL.getSourceRange();
4060 }
4061 Info.DiagnoseAbstractType();
4062 }
4063};
4064
4065void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4066 Sema::AbstractDiagSelID Sel) {
4067 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4068}
4069
4070}
4071
4072/// Check for invalid uses of an abstract type in a method declaration.
4073static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4074 CXXMethodDecl *MD) {
4075 // No need to do the check on definitions, which require that
4076 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004077 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004078 return;
4079
4080 // For safety's sake, just ignore it if we don't have type source
4081 // information. This should never happen for non-implicit methods,
4082 // but...
4083 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4084 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4085}
4086
4087/// Check for invalid uses of an abstract type within a class definition.
4088static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4089 CXXRecordDecl *RD) {
4090 for (CXXRecordDecl::decl_iterator
4091 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4092 Decl *D = *I;
4093 if (D->isImplicit()) continue;
4094
4095 // Methods and method templates.
4096 if (isa<CXXMethodDecl>(D)) {
4097 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4098 } else if (isa<FunctionTemplateDecl>(D)) {
4099 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4100 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4101
4102 // Fields and static variables.
4103 } else if (isa<FieldDecl>(D)) {
4104 FieldDecl *FD = cast<FieldDecl>(D);
4105 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4106 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4107 } else if (isa<VarDecl>(D)) {
4108 VarDecl *VD = cast<VarDecl>(D);
4109 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4110 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4111
4112 // Nested classes and class templates.
4113 } else if (isa<CXXRecordDecl>(D)) {
4114 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4115 } else if (isa<ClassTemplateDecl>(D)) {
4116 CheckAbstractClassUsage(Info,
4117 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4118 }
4119 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004120}
4121
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004122/// \brief Perform semantic checks on a class definition that has been
4123/// completing, introducing implicitly-declared members, checking for
4124/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004125void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004126 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004127 return;
4128
John McCall94c3b562010-08-18 09:41:07 +00004129 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4130 AbstractUsageInfo Info(*this, Record);
4131 CheckAbstractClassUsage(Info, Record);
4132 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004133
4134 // If this is not an aggregate type and has no user-declared constructor,
4135 // complain about any non-static data members of reference or const scalar
4136 // type, since they will never get initializers.
4137 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004138 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4139 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004140 bool Complained = false;
4141 for (RecordDecl::field_iterator F = Record->field_begin(),
4142 FEnd = Record->field_end();
4143 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004144 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004145 continue;
4146
Douglas Gregor325e5932010-04-15 00:00:53 +00004147 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004148 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004149 if (!Complained) {
4150 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4151 << Record->getTagKind() << Record;
4152 Complained = true;
4153 }
4154
4155 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4156 << F->getType()->isReferenceType()
4157 << F->getDeclName();
4158 }
4159 }
4160 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004161
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004162 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004163 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004164
4165 if (Record->getIdentifier()) {
4166 // C++ [class.mem]p13:
4167 // If T is the name of a class, then each of the following shall have a
4168 // name different from T:
4169 // - every member of every anonymous union that is a member of class T.
4170 //
4171 // C++ [class.mem]p14:
4172 // In addition, if class T has a user-declared constructor (12.1), every
4173 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004174 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4175 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4176 ++I) {
4177 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004178 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4179 isa<IndirectFieldDecl>(D)) {
4180 Diag(D->getLocation(), diag::err_member_name_of_class)
4181 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004182 break;
4183 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004184 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004185 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004186
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004187 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004188 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004189 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004190 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004191 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4192 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4193 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004194
David Blaikieb6b5b972012-09-21 03:21:07 +00004195 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4196 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4197 DiagnoseAbstractType(Record);
4198 }
4199
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004200 if (!Record->isDependentType()) {
4201 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4202 MEnd = Record->method_end();
4203 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004204 // See if a method overloads virtual methods in a base
4205 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004206 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004207 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004208
4209 // Check whether the explicitly-defaulted special members are valid.
4210 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4211 CheckExplicitlyDefaultedSpecialMember(*M);
4212
4213 // For an explicitly defaulted or deleted special member, we defer
4214 // determining triviality until the class is complete. That time is now!
4215 if (!M->isImplicit() && !M->isUserProvided()) {
4216 CXXSpecialMember CSM = getSpecialMember(*M);
4217 if (CSM != CXXInvalid) {
4218 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4219
4220 // Inform the class that we've finished declaring this member.
4221 Record->finishedDefaultedOrDeletedMember(*M);
4222 }
4223 }
4224 }
4225 }
4226
4227 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4228 // function that is not a constructor declares that member function to be
4229 // const. [...] The class of which that function is a member shall be
4230 // a literal type.
4231 //
4232 // If the class has virtual bases, any constexpr members will already have
4233 // been diagnosed by the checks performed on the member declaration, so
4234 // suppress this (less useful) diagnostic.
4235 //
4236 // We delay this until we know whether an explicitly-defaulted (or deleted)
4237 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004238 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004239 !Record->isLiteral() && !Record->getNumVBases()) {
4240 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4241 MEnd = Record->method_end();
4242 M != MEnd; ++M) {
4243 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4244 switch (Record->getTemplateSpecializationKind()) {
4245 case TSK_ImplicitInstantiation:
4246 case TSK_ExplicitInstantiationDeclaration:
4247 case TSK_ExplicitInstantiationDefinition:
4248 // If a template instantiates to a non-literal type, but its members
4249 // instantiate to constexpr functions, the template is technically
4250 // ill-formed, but we allow it for sanity.
4251 continue;
4252
4253 case TSK_Undeclared:
4254 case TSK_ExplicitSpecialization:
4255 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4256 diag::err_constexpr_method_non_literal);
4257 break;
4258 }
4259
4260 // Only produce one error per class.
4261 break;
4262 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004263 }
4264 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004265
Richard Smith07b0fdc2013-03-18 21:12:30 +00004266 // Declare inheriting constructors. We do this eagerly here because:
4267 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004268 // constructors from different classes.
4269 // - The lazy declaration of the other implicit constructors is so as to not
4270 // waste space and performance on classes that are not meant to be
4271 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004272 // have inheriting constructors.
4273 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004274}
4275
Richard Smith7756afa2012-06-10 05:43:50 +00004276/// Is the special member function which would be selected to perform the
4277/// specified operation on the specified class type a constexpr constructor?
4278static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4279 Sema::CXXSpecialMember CSM,
4280 bool ConstArg) {
4281 Sema::SpecialMemberOverloadResult *SMOR =
4282 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4283 false, false, false, false);
4284 if (!SMOR || !SMOR->getMethod())
4285 // A constructor we wouldn't select can't be "involved in initializing"
4286 // anything.
4287 return true;
4288 return SMOR->getMethod()->isConstexpr();
4289}
4290
4291/// Determine whether the specified special member function would be constexpr
4292/// if it were implicitly defined.
4293static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4294 Sema::CXXSpecialMember CSM,
4295 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004296 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004297 return false;
4298
4299 // C++11 [dcl.constexpr]p4:
4300 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004301 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004302 switch (CSM) {
4303 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004304 // Since default constructor lookup is essentially trivial (and cannot
4305 // involve, for instance, template instantiation), we compute whether a
4306 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4307 //
4308 // This is important for performance; we need to know whether the default
4309 // constructor is constexpr to determine whether the type is a literal type.
4310 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4311
Richard Smith7756afa2012-06-10 05:43:50 +00004312 case Sema::CXXCopyConstructor:
4313 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004314 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004315 break;
4316
4317 case Sema::CXXCopyAssignment:
4318 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004319 if (!S.getLangOpts().CPlusPlus1y)
4320 return false;
4321 // In C++1y, we need to perform overload resolution.
4322 Ctor = false;
4323 break;
4324
Richard Smith7756afa2012-06-10 05:43:50 +00004325 case Sema::CXXDestructor:
4326 case Sema::CXXInvalid:
4327 return false;
4328 }
4329
4330 // -- if the class is a non-empty union, or for each non-empty anonymous
4331 // union member of a non-union class, exactly one non-static data member
4332 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004333 //
4334 // If we squint, this is guaranteed, since exactly one non-static data member
4335 // will be initialized (if the constructor isn't deleted), we just don't know
4336 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004337 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004338 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004339
4340 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004341 if (Ctor && ClassDecl->getNumVBases())
4342 return false;
4343
4344 // C++1y [class.copy]p26:
4345 // -- [the class] is a literal type, and
4346 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004347 return false;
4348
4349 // -- every constructor involved in initializing [...] base class
4350 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004351 // -- the assignment operator selected to copy/move each direct base
4352 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004353 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4354 BEnd = ClassDecl->bases_end();
4355 B != BEnd; ++B) {
4356 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4357 if (!BaseType) continue;
4358
4359 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4360 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4361 return false;
4362 }
4363
4364 // -- every constructor involved in initializing non-static data members
4365 // [...] shall be a constexpr constructor;
4366 // -- every non-static data member and base class sub-object shall be
4367 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004368 // -- for each non-stastic data member of X that is of class type (or array
4369 // thereof), the assignment operator selected to copy/move that member is
4370 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004371 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4372 FEnd = ClassDecl->field_end();
4373 F != FEnd; ++F) {
4374 if (F->isInvalidDecl())
4375 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004376 if (const RecordType *RecordTy =
4377 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004378 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4379 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4380 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004381 }
4382 }
4383
4384 // All OK, it's constexpr!
4385 return true;
4386}
4387
Richard Smithb9d0b762012-07-27 04:22:15 +00004388static Sema::ImplicitExceptionSpecification
4389computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4390 switch (S.getSpecialMember(MD)) {
4391 case Sema::CXXDefaultConstructor:
4392 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4393 case Sema::CXXCopyConstructor:
4394 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4395 case Sema::CXXCopyAssignment:
4396 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4397 case Sema::CXXMoveConstructor:
4398 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4399 case Sema::CXXMoveAssignment:
4400 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4401 case Sema::CXXDestructor:
4402 return S.ComputeDefaultedDtorExceptionSpec(MD);
4403 case Sema::CXXInvalid:
4404 break;
4405 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004406 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4407 "only special members have implicit exception specs");
4408 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004409}
4410
Richard Smithdd25e802012-07-30 23:48:14 +00004411static void
4412updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4413 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4414 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4415 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004416 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4417 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004418}
4419
Richard Smithb9d0b762012-07-27 04:22:15 +00004420void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4421 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4422 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4423 return;
4424
Richard Smithdd25e802012-07-30 23:48:14 +00004425 // Evaluate the exception specification.
4426 ImplicitExceptionSpecification ExceptSpec =
4427 computeImplicitExceptionSpec(*this, Loc, MD);
4428
4429 // Update the type of the special member to use it.
4430 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4431
4432 // A user-provided destructor can be defined outside the class. When that
4433 // happens, be sure to update the exception specification on both
4434 // declarations.
4435 const FunctionProtoType *CanonicalFPT =
4436 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4437 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4438 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4439 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004440}
4441
Richard Smith3003e1d2012-05-15 04:39:51 +00004442void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4443 CXXRecordDecl *RD = MD->getParent();
4444 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004445
Richard Smith3003e1d2012-05-15 04:39:51 +00004446 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4447 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004448
4449 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004450 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004451 bool First = MD == MD->getCanonicalDecl();
4452
4453 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004454
4455 // C++11 [dcl.fct.def.default]p1:
4456 // A function that is explicitly defaulted shall
4457 // -- be a special member function (checked elsewhere),
4458 // -- have the same type (except for ref-qualifiers, and except that a
4459 // copy operation can take a non-const reference) as an implicit
4460 // declaration, and
4461 // -- not have default arguments.
4462 unsigned ExpectedParams = 1;
4463 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4464 ExpectedParams = 0;
4465 if (MD->getNumParams() != ExpectedParams) {
4466 // This also checks for default arguments: a copy or move constructor with a
4467 // default argument is classified as a default constructor, and assignment
4468 // operations and destructors can't have default arguments.
4469 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4470 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004471 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004472 } else if (MD->isVariadic()) {
4473 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4474 << CSM << MD->getSourceRange();
4475 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004476 }
4477
Richard Smith3003e1d2012-05-15 04:39:51 +00004478 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004479
Richard Smith7756afa2012-06-10 05:43:50 +00004480 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004481 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004482 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004483 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004484 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004485
Richard Smith3003e1d2012-05-15 04:39:51 +00004486 QualType ReturnType = Context.VoidTy;
4487 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4488 // Check for return type matching.
4489 ReturnType = Type->getResultType();
4490 QualType ExpectedReturnType =
4491 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4492 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4493 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4494 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4495 HadError = true;
4496 }
4497
4498 // A defaulted special member cannot have cv-qualifiers.
4499 if (Type->getTypeQuals()) {
4500 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004501 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004502 HadError = true;
4503 }
4504 }
4505
4506 // Check for parameter type matching.
4507 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004508 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004509 if (ExpectedParams && ArgType->isReferenceType()) {
4510 // Argument must be reference to possibly-const T.
4511 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004512 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004513
4514 if (ReferentType.isVolatileQualified()) {
4515 Diag(MD->getLocation(),
4516 diag::err_defaulted_special_member_volatile_param) << CSM;
4517 HadError = true;
4518 }
4519
Richard Smith7756afa2012-06-10 05:43:50 +00004520 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004521 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4522 Diag(MD->getLocation(),
4523 diag::err_defaulted_special_member_copy_const_param)
4524 << (CSM == CXXCopyAssignment);
4525 // FIXME: Explain why this special member can't be const.
4526 } else {
4527 Diag(MD->getLocation(),
4528 diag::err_defaulted_special_member_move_const_param)
4529 << (CSM == CXXMoveAssignment);
4530 }
4531 HadError = true;
4532 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004533 } else if (ExpectedParams) {
4534 // A copy assignment operator can take its argument by value, but a
4535 // defaulted one cannot.
4536 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004537 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004538 HadError = true;
4539 }
Sean Huntbe631222011-05-17 20:44:43 +00004540
Richard Smith61802452011-12-22 02:22:31 +00004541 // C++11 [dcl.fct.def.default]p2:
4542 // An explicitly-defaulted function may be declared constexpr only if it
4543 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004544 // Do not apply this rule to members of class templates, since core issue 1358
4545 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004546 // functions which cannot be constexpr (for non-constructors in C++11 and for
4547 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004548 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4549 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004550 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4551 : isa<CXXConstructorDecl>(MD)) &&
4552 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004553 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4554 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004555 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004556 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004557 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004558
Richard Smith61802452011-12-22 02:22:31 +00004559 // and may have an explicit exception-specification only if it is compatible
4560 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004561 if (Type->hasExceptionSpec()) {
4562 // Delay the check if this is the first declaration of the special member,
4563 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004564 if (First) {
4565 // If the exception specification needs to be instantiated, do so now,
4566 // before we clobber it with an EST_Unevaluated specification below.
4567 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4568 InstantiateExceptionSpec(MD->getLocStart(), MD);
4569 Type = MD->getType()->getAs<FunctionProtoType>();
4570 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004571 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004572 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004573 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4574 }
Richard Smith61802452011-12-22 02:22:31 +00004575
4576 // If a function is explicitly defaulted on its first declaration,
4577 if (First) {
4578 // -- it is implicitly considered to be constexpr if the implicit
4579 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004580 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004581
Richard Smith3003e1d2012-05-15 04:39:51 +00004582 // -- it is implicitly considered to have the same exception-specification
4583 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004584 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4585 EPI.ExceptionSpecType = EST_Unevaluated;
4586 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004587 MD->setType(Context.getFunctionType(ReturnType,
4588 ArrayRef<QualType>(&ArgType,
4589 ExpectedParams),
4590 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004591 }
4592
Richard Smith3003e1d2012-05-15 04:39:51 +00004593 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004594 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004595 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004596 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004597 // C++11 [dcl.fct.def.default]p4:
4598 // [For a] user-provided explicitly-defaulted function [...] if such a
4599 // function is implicitly defined as deleted, the program is ill-formed.
4600 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4601 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004602 }
4603 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004604
Richard Smith3003e1d2012-05-15 04:39:51 +00004605 if (HadError)
4606 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004607}
4608
Richard Smith1d28caf2012-12-11 01:14:52 +00004609/// Check whether the exception specification provided for an
4610/// explicitly-defaulted special member matches the exception specification
4611/// that would have been generated for an implicit special member, per
4612/// C++11 [dcl.fct.def.default]p2.
4613void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4614 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4615 // Compute the implicit exception specification.
4616 FunctionProtoType::ExtProtoInfo EPI;
4617 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4618 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004619 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004620
4621 // Ensure that it matches.
4622 CheckEquivalentExceptionSpec(
4623 PDiag(diag::err_incorrect_defaulted_exception_spec)
4624 << getSpecialMember(MD), PDiag(),
4625 ImplicitType, SourceLocation(),
4626 SpecifiedType, MD->getLocation());
4627}
4628
4629void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4630 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4631 I != N; ++I)
4632 CheckExplicitlyDefaultedMemberExceptionSpec(
4633 DelayedDefaultedMemberExceptionSpecs[I].first,
4634 DelayedDefaultedMemberExceptionSpecs[I].second);
4635
4636 DelayedDefaultedMemberExceptionSpecs.clear();
4637}
4638
Richard Smith7d5088a2012-02-18 02:02:13 +00004639namespace {
4640struct SpecialMemberDeletionInfo {
4641 Sema &S;
4642 CXXMethodDecl *MD;
4643 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004644 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004645
4646 // Properties of the special member, computed for convenience.
4647 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4648 SourceLocation Loc;
4649
4650 bool AllFieldsAreConst;
4651
4652 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004653 Sema::CXXSpecialMember CSM, bool Diagnose)
4654 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004655 IsConstructor(false), IsAssignment(false), IsMove(false),
4656 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4657 AllFieldsAreConst(true) {
4658 switch (CSM) {
4659 case Sema::CXXDefaultConstructor:
4660 case Sema::CXXCopyConstructor:
4661 IsConstructor = true;
4662 break;
4663 case Sema::CXXMoveConstructor:
4664 IsConstructor = true;
4665 IsMove = true;
4666 break;
4667 case Sema::CXXCopyAssignment:
4668 IsAssignment = true;
4669 break;
4670 case Sema::CXXMoveAssignment:
4671 IsAssignment = true;
4672 IsMove = true;
4673 break;
4674 case Sema::CXXDestructor:
4675 break;
4676 case Sema::CXXInvalid:
4677 llvm_unreachable("invalid special member kind");
4678 }
4679
4680 if (MD->getNumParams()) {
4681 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4682 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4683 }
4684 }
4685
4686 bool inUnion() const { return MD->getParent()->isUnion(); }
4687
4688 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004689 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4690 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004691 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004692 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4693 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4694 Quals = 0;
4695 return S.LookupSpecialMember(Class, CSM,
4696 ConstArg || (Quals & Qualifiers::Const),
4697 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004698 MD->getRefQualifier() == RQ_RValue,
4699 TQ & Qualifiers::Const,
4700 TQ & Qualifiers::Volatile);
4701 }
4702
Richard Smith6c4c36c2012-03-30 20:53:28 +00004703 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004704
Richard Smith6c4c36c2012-03-30 20:53:28 +00004705 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004706 bool shouldDeleteForField(FieldDecl *FD);
4707 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004708
Richard Smith517bb842012-07-18 03:51:16 +00004709 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4710 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004711 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4712 Sema::SpecialMemberOverloadResult *SMOR,
4713 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004714
4715 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004716};
4717}
4718
John McCall12d8d802012-04-09 20:53:23 +00004719/// Is the given special member inaccessible when used on the given
4720/// sub-object.
4721bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4722 CXXMethodDecl *target) {
4723 /// If we're operating on a base class, the object type is the
4724 /// type of this special member.
4725 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004726 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004727 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4728 objectTy = S.Context.getTypeDeclType(MD->getParent());
4729 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4730
4731 // If we're operating on a field, the object type is the type of the field.
4732 } else {
4733 objectTy = S.Context.getTypeDeclType(target->getParent());
4734 }
4735
4736 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4737}
4738
Richard Smith6c4c36c2012-03-30 20:53:28 +00004739/// Check whether we should delete a special member due to the implicit
4740/// definition containing a call to a special member of a subobject.
4741bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4742 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4743 bool IsDtorCallInCtor) {
4744 CXXMethodDecl *Decl = SMOR->getMethod();
4745 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4746
4747 int DiagKind = -1;
4748
4749 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4750 DiagKind = !Decl ? 0 : 1;
4751 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4752 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004753 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004754 DiagKind = 3;
4755 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4756 !Decl->isTrivial()) {
4757 // A member of a union must have a trivial corresponding special member.
4758 // As a weird special case, a destructor call from a union's constructor
4759 // must be accessible and non-deleted, but need not be trivial. Such a
4760 // destructor is never actually called, but is semantically checked as
4761 // if it were.
4762 DiagKind = 4;
4763 }
4764
4765 if (DiagKind == -1)
4766 return false;
4767
4768 if (Diagnose) {
4769 if (Field) {
4770 S.Diag(Field->getLocation(),
4771 diag::note_deleted_special_member_class_subobject)
4772 << CSM << MD->getParent() << /*IsField*/true
4773 << Field << DiagKind << IsDtorCallInCtor;
4774 } else {
4775 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4776 S.Diag(Base->getLocStart(),
4777 diag::note_deleted_special_member_class_subobject)
4778 << CSM << MD->getParent() << /*IsField*/false
4779 << Base->getType() << DiagKind << IsDtorCallInCtor;
4780 }
4781
4782 if (DiagKind == 1)
4783 S.NoteDeletedFunction(Decl);
4784 // FIXME: Explain inaccessibility if DiagKind == 3.
4785 }
4786
4787 return true;
4788}
4789
Richard Smith9a561d52012-02-26 09:11:52 +00004790/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004791/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004792bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004793 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004794 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004795
4796 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004797 // -- any direct or virtual base class, or non-static data member with no
4798 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004799 // either M has no default constructor or overload resolution as applied
4800 // to M's default constructor results in an ambiguity or in a function
4801 // that is deleted or inaccessible
4802 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4803 // -- a direct or virtual base class B that cannot be copied/moved because
4804 // overload resolution, as applied to B's corresponding special member,
4805 // results in an ambiguity or a function that is deleted or inaccessible
4806 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004807 // C++11 [class.dtor]p5:
4808 // -- any direct or virtual base class [...] has a type with a destructor
4809 // that is deleted or inaccessible
4810 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004811 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004812 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004813 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004814
Richard Smith6c4c36c2012-03-30 20:53:28 +00004815 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4816 // -- any direct or virtual base class or non-static data member has a
4817 // type with a destructor that is deleted or inaccessible
4818 if (IsConstructor) {
4819 Sema::SpecialMemberOverloadResult *SMOR =
4820 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4821 false, false, false, false, false);
4822 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4823 return true;
4824 }
4825
Richard Smith9a561d52012-02-26 09:11:52 +00004826 return false;
4827}
4828
4829/// Check whether we should delete a special member function due to the class
4830/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004831bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004832 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004833 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004834}
4835
4836/// Check whether we should delete a special member function due to the class
4837/// having a particular non-static data member.
4838bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4839 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4840 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4841
4842 if (CSM == Sema::CXXDefaultConstructor) {
4843 // For a default constructor, all references must be initialized in-class
4844 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004845 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4846 if (Diagnose)
4847 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4848 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004849 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004850 }
Richard Smith79363f52012-02-27 06:07:25 +00004851 // C++11 [class.ctor]p5: any non-variant non-static data member of
4852 // const-qualified type (or array thereof) with no
4853 // brace-or-equal-initializer does not have a user-provided default
4854 // constructor.
4855 if (!inUnion() && FieldType.isConstQualified() &&
4856 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004857 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4858 if (Diagnose)
4859 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004860 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004861 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004862 }
4863
4864 if (inUnion() && !FieldType.isConstQualified())
4865 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004866 } else if (CSM == Sema::CXXCopyConstructor) {
4867 // For a copy constructor, data members must not be of rvalue reference
4868 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004869 if (FieldType->isRValueReferenceType()) {
4870 if (Diagnose)
4871 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4872 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004873 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004874 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004875 } else if (IsAssignment) {
4876 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004877 if (FieldType->isReferenceType()) {
4878 if (Diagnose)
4879 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4880 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004881 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004882 }
4883 if (!FieldRecord && FieldType.isConstQualified()) {
4884 // C++11 [class.copy]p23:
4885 // -- a non-static data member of const non-class type (or array thereof)
4886 if (Diagnose)
4887 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004888 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004889 return true;
4890 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004891 }
4892
4893 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004894 // Some additional restrictions exist on the variant members.
4895 if (!inUnion() && FieldRecord->isUnion() &&
4896 FieldRecord->isAnonymousStructOrUnion()) {
4897 bool AllVariantFieldsAreConst = true;
4898
Richard Smithdf8dc862012-03-29 19:00:10 +00004899 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004900 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4901 UE = FieldRecord->field_end();
4902 UI != UE; ++UI) {
4903 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004904
4905 if (!UnionFieldType.isConstQualified())
4906 AllVariantFieldsAreConst = false;
4907
Richard Smith9a561d52012-02-26 09:11:52 +00004908 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4909 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004910 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4911 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004912 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004913 }
4914
4915 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004916 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004917 FieldRecord->field_begin() != FieldRecord->field_end()) {
4918 if (Diagnose)
4919 S.Diag(FieldRecord->getLocation(),
4920 diag::note_deleted_default_ctor_all_const)
4921 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004922 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004923 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004924
Richard Smithdf8dc862012-03-29 19:00:10 +00004925 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004926 // This is technically non-conformant, but sanity demands it.
4927 return false;
4928 }
4929
Richard Smith517bb842012-07-18 03:51:16 +00004930 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4931 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004932 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004933 }
4934
4935 return false;
4936}
4937
4938/// C++11 [class.ctor] p5:
4939/// A defaulted default constructor for a class X is defined as deleted if
4940/// X is a union and all of its variant members are of const-qualified type.
4941bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004942 // This is a silly definition, because it gives an empty union a deleted
4943 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004944 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4945 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4946 if (Diagnose)
4947 S.Diag(MD->getParent()->getLocation(),
4948 diag::note_deleted_default_ctor_all_const)
4949 << MD->getParent() << /*not anonymous union*/0;
4950 return true;
4951 }
4952 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004953}
4954
4955/// Determine whether a defaulted special member function should be defined as
4956/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4957/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004958bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4959 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004960 if (MD->isInvalidDecl())
4961 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004962 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004963 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004964 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004965 return false;
4966
Richard Smith7d5088a2012-02-18 02:02:13 +00004967 // C++11 [expr.lambda.prim]p19:
4968 // The closure type associated with a lambda-expression has a
4969 // deleted (8.4.3) default constructor and a deleted copy
4970 // assignment operator.
4971 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004972 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4973 if (Diagnose)
4974 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004975 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004976 }
4977
Richard Smith5bdaac52012-04-02 20:59:25 +00004978 // For an anonymous struct or union, the copy and assignment special members
4979 // will never be used, so skip the check. For an anonymous union declared at
4980 // namespace scope, the constructor and destructor are used.
4981 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4982 RD->isAnonymousStructOrUnion())
4983 return false;
4984
Richard Smith6c4c36c2012-03-30 20:53:28 +00004985 // C++11 [class.copy]p7, p18:
4986 // If the class definition declares a move constructor or move assignment
4987 // operator, an implicitly declared copy constructor or copy assignment
4988 // operator is defined as deleted.
4989 if (MD->isImplicit() &&
4990 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4991 CXXMethodDecl *UserDeclaredMove = 0;
4992
4993 // In Microsoft mode, a user-declared move only causes the deletion of the
4994 // corresponding copy operation, not both copy operations.
4995 if (RD->hasUserDeclaredMoveConstructor() &&
4996 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4997 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004998
4999 // Find any user-declared move constructor.
5000 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5001 E = RD->ctor_end(); I != E; ++I) {
5002 if (I->isMoveConstructor()) {
5003 UserDeclaredMove = *I;
5004 break;
5005 }
5006 }
Richard Smith1c931be2012-04-02 18:40:40 +00005007 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005008 } else if (RD->hasUserDeclaredMoveAssignment() &&
5009 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5010 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005011
5012 // Find any user-declared move assignment operator.
5013 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5014 E = RD->method_end(); I != E; ++I) {
5015 if (I->isMoveAssignmentOperator()) {
5016 UserDeclaredMove = *I;
5017 break;
5018 }
5019 }
Richard Smith1c931be2012-04-02 18:40:40 +00005020 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005021 }
5022
5023 if (UserDeclaredMove) {
5024 Diag(UserDeclaredMove->getLocation(),
5025 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005026 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005027 << UserDeclaredMove->isMoveAssignmentOperator();
5028 return true;
5029 }
5030 }
Sean Hunte16da072011-10-10 06:18:57 +00005031
Richard Smith5bdaac52012-04-02 20:59:25 +00005032 // Do access control from the special member function
5033 ContextRAII MethodContext(*this, MD);
5034
Richard Smith9a561d52012-02-26 09:11:52 +00005035 // C++11 [class.dtor]p5:
5036 // -- for a virtual destructor, lookup of the non-array deallocation function
5037 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005038 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005039 FunctionDecl *OperatorDelete = 0;
5040 DeclarationName Name =
5041 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5042 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005043 OperatorDelete, false)) {
5044 if (Diagnose)
5045 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005046 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005047 }
Richard Smith9a561d52012-02-26 09:11:52 +00005048 }
5049
Richard Smith6c4c36c2012-03-30 20:53:28 +00005050 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005051
Sean Huntcdee3fe2011-05-11 22:34:38 +00005052 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005053 BE = RD->bases_end(); BI != BE; ++BI)
5054 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005055 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005056 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005057
5058 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005059 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005060 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005061 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005062
5063 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005064 FE = RD->field_end(); FI != FE; ++FI)
5065 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005066 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005067 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005068
Richard Smith7d5088a2012-02-18 02:02:13 +00005069 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005070 return true;
5071
5072 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005073}
5074
Richard Smithac713512012-12-08 02:53:02 +00005075/// Perform lookup for a special member of the specified kind, and determine
5076/// whether it is trivial. If the triviality can be determined without the
5077/// lookup, skip it. This is intended for use when determining whether a
5078/// special member of a containing object is trivial, and thus does not ever
5079/// perform overload resolution for default constructors.
5080///
5081/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5082/// member that was most likely to be intended to be trivial, if any.
5083static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5084 Sema::CXXSpecialMember CSM, unsigned Quals,
5085 CXXMethodDecl **Selected) {
5086 if (Selected)
5087 *Selected = 0;
5088
5089 switch (CSM) {
5090 case Sema::CXXInvalid:
5091 llvm_unreachable("not a special member");
5092
5093 case Sema::CXXDefaultConstructor:
5094 // C++11 [class.ctor]p5:
5095 // A default constructor is trivial if:
5096 // - all the [direct subobjects] have trivial default constructors
5097 //
5098 // Note, no overload resolution is performed in this case.
5099 if (RD->hasTrivialDefaultConstructor())
5100 return true;
5101
5102 if (Selected) {
5103 // If there's a default constructor which could have been trivial, dig it
5104 // out. Otherwise, if there's any user-provided default constructor, point
5105 // to that as an example of why there's not a trivial one.
5106 CXXConstructorDecl *DefCtor = 0;
5107 if (RD->needsImplicitDefaultConstructor())
5108 S.DeclareImplicitDefaultConstructor(RD);
5109 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5110 CE = RD->ctor_end(); CI != CE; ++CI) {
5111 if (!CI->isDefaultConstructor())
5112 continue;
5113 DefCtor = *CI;
5114 if (!DefCtor->isUserProvided())
5115 break;
5116 }
5117
5118 *Selected = DefCtor;
5119 }
5120
5121 return false;
5122
5123 case Sema::CXXDestructor:
5124 // C++11 [class.dtor]p5:
5125 // A destructor is trivial if:
5126 // - all the direct [subobjects] have trivial destructors
5127 if (RD->hasTrivialDestructor())
5128 return true;
5129
5130 if (Selected) {
5131 if (RD->needsImplicitDestructor())
5132 S.DeclareImplicitDestructor(RD);
5133 *Selected = RD->getDestructor();
5134 }
5135
5136 return false;
5137
5138 case Sema::CXXCopyConstructor:
5139 // C++11 [class.copy]p12:
5140 // A copy constructor is trivial if:
5141 // - the constructor selected to copy each direct [subobject] is trivial
5142 if (RD->hasTrivialCopyConstructor()) {
5143 if (Quals == Qualifiers::Const)
5144 // We must either select the trivial copy constructor or reach an
5145 // ambiguity; no need to actually perform overload resolution.
5146 return true;
5147 } else if (!Selected) {
5148 return false;
5149 }
5150 // In C++98, we are not supposed to perform overload resolution here, but we
5151 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5152 // cases like B as having a non-trivial copy constructor:
5153 // struct A { template<typename T> A(T&); };
5154 // struct B { mutable A a; };
5155 goto NeedOverloadResolution;
5156
5157 case Sema::CXXCopyAssignment:
5158 // C++11 [class.copy]p25:
5159 // A copy assignment operator is trivial if:
5160 // - the assignment operator selected to copy each direct [subobject] is
5161 // trivial
5162 if (RD->hasTrivialCopyAssignment()) {
5163 if (Quals == Qualifiers::Const)
5164 return true;
5165 } else if (!Selected) {
5166 return false;
5167 }
5168 // In C++98, we are not supposed to perform overload resolution here, but we
5169 // treat that as a language defect.
5170 goto NeedOverloadResolution;
5171
5172 case Sema::CXXMoveConstructor:
5173 case Sema::CXXMoveAssignment:
5174 NeedOverloadResolution:
5175 Sema::SpecialMemberOverloadResult *SMOR =
5176 S.LookupSpecialMember(RD, CSM,
5177 Quals & Qualifiers::Const,
5178 Quals & Qualifiers::Volatile,
5179 /*RValueThis*/false, /*ConstThis*/false,
5180 /*VolatileThis*/false);
5181
5182 // The standard doesn't describe how to behave if the lookup is ambiguous.
5183 // We treat it as not making the member non-trivial, just like the standard
5184 // mandates for the default constructor. This should rarely matter, because
5185 // the member will also be deleted.
5186 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5187 return true;
5188
5189 if (!SMOR->getMethod()) {
5190 assert(SMOR->getKind() ==
5191 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5192 return false;
5193 }
5194
5195 // We deliberately don't check if we found a deleted special member. We're
5196 // not supposed to!
5197 if (Selected)
5198 *Selected = SMOR->getMethod();
5199 return SMOR->getMethod()->isTrivial();
5200 }
5201
5202 llvm_unreachable("unknown special method kind");
5203}
5204
Benjamin Kramera574c892013-02-15 12:30:38 +00005205static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005206 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5207 CI != CE; ++CI)
5208 if (!CI->isImplicit())
5209 return *CI;
5210
5211 // Look for constructor templates.
5212 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5213 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5214 if (CXXConstructorDecl *CD =
5215 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5216 return CD;
5217 }
5218
5219 return 0;
5220}
5221
5222/// The kind of subobject we are checking for triviality. The values of this
5223/// enumeration are used in diagnostics.
5224enum TrivialSubobjectKind {
5225 /// The subobject is a base class.
5226 TSK_BaseClass,
5227 /// The subobject is a non-static data member.
5228 TSK_Field,
5229 /// The object is actually the complete object.
5230 TSK_CompleteObject
5231};
5232
5233/// Check whether the special member selected for a given type would be trivial.
5234static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5235 QualType SubType,
5236 Sema::CXXSpecialMember CSM,
5237 TrivialSubobjectKind Kind,
5238 bool Diagnose) {
5239 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5240 if (!SubRD)
5241 return true;
5242
5243 CXXMethodDecl *Selected;
5244 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5245 Diagnose ? &Selected : 0))
5246 return true;
5247
5248 if (Diagnose) {
5249 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5250 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5251 << Kind << SubType.getUnqualifiedType();
5252 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5253 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5254 } else if (!Selected)
5255 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5256 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5257 else if (Selected->isUserProvided()) {
5258 if (Kind == TSK_CompleteObject)
5259 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5260 << Kind << SubType.getUnqualifiedType() << CSM;
5261 else {
5262 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5263 << Kind << SubType.getUnqualifiedType() << CSM;
5264 S.Diag(Selected->getLocation(), diag::note_declared_at);
5265 }
5266 } else {
5267 if (Kind != TSK_CompleteObject)
5268 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5269 << Kind << SubType.getUnqualifiedType() << CSM;
5270
5271 // Explain why the defaulted or deleted special member isn't trivial.
5272 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5273 }
5274 }
5275
5276 return false;
5277}
5278
5279/// Check whether the members of a class type allow a special member to be
5280/// trivial.
5281static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5282 Sema::CXXSpecialMember CSM,
5283 bool ConstArg, bool Diagnose) {
5284 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5285 FE = RD->field_end(); FI != FE; ++FI) {
5286 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5287 continue;
5288
5289 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5290
5291 // Pretend anonymous struct or union members are members of this class.
5292 if (FI->isAnonymousStructOrUnion()) {
5293 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5294 CSM, ConstArg, Diagnose))
5295 return false;
5296 continue;
5297 }
5298
5299 // C++11 [class.ctor]p5:
5300 // A default constructor is trivial if [...]
5301 // -- no non-static data member of its class has a
5302 // brace-or-equal-initializer
5303 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5304 if (Diagnose)
5305 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5306 return false;
5307 }
5308
5309 // Objective C ARC 4.3.5:
5310 // [...] nontrivally ownership-qualified types are [...] not trivially
5311 // default constructible, copy constructible, move constructible, copy
5312 // assignable, move assignable, or destructible [...]
5313 if (S.getLangOpts().ObjCAutoRefCount &&
5314 FieldType.hasNonTrivialObjCLifetime()) {
5315 if (Diagnose)
5316 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5317 << RD << FieldType.getObjCLifetime();
5318 return false;
5319 }
5320
5321 if (ConstArg && !FI->isMutable())
5322 FieldType.addConst();
5323 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5324 TSK_Field, Diagnose))
5325 return false;
5326 }
5327
5328 return true;
5329}
5330
5331/// Diagnose why the specified class does not have a trivial special member of
5332/// the given kind.
5333void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5334 QualType Ty = Context.getRecordType(RD);
5335 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5336 Ty.addConst();
5337
5338 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5339 TSK_CompleteObject, /*Diagnose*/true);
5340}
5341
5342/// Determine whether a defaulted or deleted special member function is trivial,
5343/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5344/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5345bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5346 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005347 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5348
5349 CXXRecordDecl *RD = MD->getParent();
5350
5351 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005352
5353 // C++11 [class.copy]p12, p25:
5354 // A [special member] is trivial if its declared parameter type is the same
5355 // as if it had been implicitly declared [...]
5356 switch (CSM) {
5357 case CXXDefaultConstructor:
5358 case CXXDestructor:
5359 // Trivial default constructors and destructors cannot have parameters.
5360 break;
5361
5362 case CXXCopyConstructor:
5363 case CXXCopyAssignment: {
5364 // Trivial copy operations always have const, non-volatile parameter types.
5365 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005366 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005367 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5368 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5369 if (Diagnose)
5370 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5371 << Param0->getSourceRange() << Param0->getType()
5372 << Context.getLValueReferenceType(
5373 Context.getRecordType(RD).withConst());
5374 return false;
5375 }
5376 break;
5377 }
5378
5379 case CXXMoveConstructor:
5380 case CXXMoveAssignment: {
5381 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005382 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005383 const RValueReferenceType *RT =
5384 Param0->getType()->getAs<RValueReferenceType>();
5385 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5386 if (Diagnose)
5387 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5388 << Param0->getSourceRange() << Param0->getType()
5389 << Context.getRValueReferenceType(Context.getRecordType(RD));
5390 return false;
5391 }
5392 break;
5393 }
5394
5395 case CXXInvalid:
5396 llvm_unreachable("not a special member");
5397 }
5398
5399 // FIXME: We require that the parameter-declaration-clause is equivalent to
5400 // that of an implicit declaration, not just that the declared parameter type
5401 // matches, in order to prevent absuridities like a function simultaneously
5402 // being a trivial copy constructor and a non-trivial default constructor.
5403 // This issue has not yet been assigned a core issue number.
5404 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5405 if (Diagnose)
5406 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5407 diag::note_nontrivial_default_arg)
5408 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5409 return false;
5410 }
5411 if (MD->isVariadic()) {
5412 if (Diagnose)
5413 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5414 return false;
5415 }
5416
5417 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5418 // A copy/move [constructor or assignment operator] is trivial if
5419 // -- the [member] selected to copy/move each direct base class subobject
5420 // is trivial
5421 //
5422 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5423 // A [default constructor or destructor] is trivial if
5424 // -- all the direct base classes have trivial [default constructors or
5425 // destructors]
5426 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5427 BE = RD->bases_end(); BI != BE; ++BI)
5428 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5429 ConstArg ? BI->getType().withConst()
5430 : BI->getType(),
5431 CSM, TSK_BaseClass, Diagnose))
5432 return false;
5433
5434 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5435 // A copy/move [constructor or assignment operator] for a class X is
5436 // trivial if
5437 // -- for each non-static data member of X that is of class type (or array
5438 // thereof), the constructor selected to copy/move that member is
5439 // trivial
5440 //
5441 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5442 // A [default constructor or destructor] is trivial if
5443 // -- for all of the non-static data members of its class that are of class
5444 // type (or array thereof), each such class has a trivial [default
5445 // constructor or destructor]
5446 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5447 return false;
5448
5449 // C++11 [class.dtor]p5:
5450 // A destructor is trivial if [...]
5451 // -- the destructor is not virtual
5452 if (CSM == CXXDestructor && MD->isVirtual()) {
5453 if (Diagnose)
5454 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5455 return false;
5456 }
5457
5458 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5459 // A [special member] for class X is trivial if [...]
5460 // -- class X has no virtual functions and no virtual base classes
5461 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5462 if (!Diagnose)
5463 return false;
5464
5465 if (RD->getNumVBases()) {
5466 // Check for virtual bases. We already know that the corresponding
5467 // member in all bases is trivial, so vbases must all be direct.
5468 CXXBaseSpecifier &BS = *RD->vbases_begin();
5469 assert(BS.isVirtual());
5470 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5471 return false;
5472 }
5473
5474 // Must have a virtual method.
5475 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5476 ME = RD->method_end(); MI != ME; ++MI) {
5477 if (MI->isVirtual()) {
5478 SourceLocation MLoc = MI->getLocStart();
5479 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5480 return false;
5481 }
5482 }
5483
5484 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5485 }
5486
5487 // Looks like it's trivial!
5488 return true;
5489}
5490
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005491/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005492namespace {
5493 struct FindHiddenVirtualMethodData {
5494 Sema *S;
5495 CXXMethodDecl *Method;
5496 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005497 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005498 };
5499}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005500
David Blaikie5f750682012-10-19 00:53:08 +00005501/// \brief Check whether any most overriden method from MD in Methods
5502static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5503 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5504 if (MD->size_overridden_methods() == 0)
5505 return Methods.count(MD->getCanonicalDecl());
5506 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5507 E = MD->end_overridden_methods();
5508 I != E; ++I)
5509 if (CheckMostOverridenMethods(*I, Methods))
5510 return true;
5511 return false;
5512}
5513
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005514/// \brief Member lookup function that determines whether a given C++
5515/// method overloads virtual methods in a base class without overriding any,
5516/// to be used with CXXRecordDecl::lookupInBases().
5517static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5518 CXXBasePath &Path,
5519 void *UserData) {
5520 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5521
5522 FindHiddenVirtualMethodData &Data
5523 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5524
5525 DeclarationName Name = Data.Method->getDeclName();
5526 assert(Name.getNameKind() == DeclarationName::Identifier);
5527
5528 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005529 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005530 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005531 !Path.Decls.empty();
5532 Path.Decls = Path.Decls.slice(1)) {
5533 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005534 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005535 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005536 foundSameNameMethod = true;
5537 // Interested only in hidden virtual methods.
5538 if (!MD->isVirtual())
5539 continue;
5540 // If the method we are checking overrides a method from its base
5541 // don't warn about the other overloaded methods.
5542 if (!Data.S->IsOverload(Data.Method, MD, false))
5543 return true;
5544 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005545 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005546 overloadedMethods.push_back(MD);
5547 }
5548 }
5549
5550 if (foundSameNameMethod)
5551 Data.OverloadedMethods.append(overloadedMethods.begin(),
5552 overloadedMethods.end());
5553 return foundSameNameMethod;
5554}
5555
David Blaikie5f750682012-10-19 00:53:08 +00005556/// \brief Add the most overriden methods from MD to Methods
5557static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5558 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5559 if (MD->size_overridden_methods() == 0)
5560 Methods.insert(MD->getCanonicalDecl());
5561 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5562 E = MD->end_overridden_methods();
5563 I != E; ++I)
5564 AddMostOverridenMethods(*I, Methods);
5565}
5566
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005567/// \brief See if a method overloads virtual methods in a base class without
5568/// overriding any.
5569void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5570 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005571 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005572 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005573 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005574 return;
5575
5576 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5577 /*bool RecordPaths=*/false,
5578 /*bool DetectVirtual=*/false);
5579 FindHiddenVirtualMethodData Data;
5580 Data.Method = MD;
5581 Data.S = this;
5582
5583 // Keep the base methods that were overriden or introduced in the subclass
5584 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005585 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5586 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5587 NamedDecl *ND = *I;
5588 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005589 ND = shad->getTargetDecl();
5590 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5591 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005592 }
5593
5594 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5595 !Data.OverloadedMethods.empty()) {
5596 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5597 << MD << (Data.OverloadedMethods.size() > 1);
5598
5599 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5600 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005601 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005602 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005603 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5604 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005605 }
5606 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005607}
5608
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005609void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005610 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005611 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005612 SourceLocation RBrac,
5613 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005614 if (!TagDecl)
5615 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005616
Douglas Gregor42af25f2009-05-11 19:58:34 +00005617 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005618
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005619 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5620 if (l->getKind() != AttributeList::AT_Visibility)
5621 continue;
5622 l->setInvalid();
5623 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5624 l->getName();
5625 }
5626
David Blaikie77b6de02011-09-22 02:58:26 +00005627 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005628 // strict aliasing violation!
5629 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005630 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005631
Douglas Gregor23c94db2010-07-02 17:43:08 +00005632 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005633 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005634}
5635
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005636/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5637/// special functions, such as the default constructor, copy
5638/// constructor, or destructor, to the given C++ class (C++
5639/// [special]p1). This routine can only be executed just before the
5640/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005641void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005642 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005643 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005644
Richard Smithbc2a35d2012-12-08 08:32:28 +00005645 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005646 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005647
Richard Smithbc2a35d2012-12-08 08:32:28 +00005648 // If the properties or semantics of the copy constructor couldn't be
5649 // determined while the class was being declared, force a declaration
5650 // of it now.
5651 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5652 DeclareImplicitCopyConstructor(ClassDecl);
5653 }
5654
Richard Smith80ad52f2013-01-02 11:42:31 +00005655 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005656 ++ASTContext::NumImplicitMoveConstructors;
5657
Richard Smithbc2a35d2012-12-08 08:32:28 +00005658 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5659 DeclareImplicitMoveConstructor(ClassDecl);
5660 }
5661
Douglas Gregora376d102010-07-02 21:50:04 +00005662 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5663 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005664
5665 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005666 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005667 // it shows up in the right place in the vtable and that we diagnose
5668 // problems with the implicit exception specification.
5669 if (ClassDecl->isDynamicClass() ||
5670 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005671 DeclareImplicitCopyAssignment(ClassDecl);
5672 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005673
Richard Smith80ad52f2013-01-02 11:42:31 +00005674 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005675 ++ASTContext::NumImplicitMoveAssignmentOperators;
5676
5677 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005678 if (ClassDecl->isDynamicClass() ||
5679 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005680 DeclareImplicitMoveAssignment(ClassDecl);
5681 }
5682
Douglas Gregor4923aa22010-07-02 20:37:36 +00005683 if (!ClassDecl->hasUserDeclaredDestructor()) {
5684 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005685
5686 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005687 // have to declare the destructor immediately. This ensures that, e.g., it
5688 // shows up in the right place in the vtable and that we diagnose problems
5689 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005690 if (ClassDecl->isDynamicClass() ||
5691 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005692 DeclareImplicitDestructor(ClassDecl);
5693 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005694}
5695
Francois Pichet8387e2a2011-04-22 22:18:13 +00005696void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5697 if (!D)
5698 return;
5699
5700 int NumParamList = D->getNumTemplateParameterLists();
5701 for (int i = 0; i < NumParamList; i++) {
5702 TemplateParameterList* Params = D->getTemplateParameterList(i);
5703 for (TemplateParameterList::iterator Param = Params->begin(),
5704 ParamEnd = Params->end();
5705 Param != ParamEnd; ++Param) {
5706 NamedDecl *Named = cast<NamedDecl>(*Param);
5707 if (Named->getDeclName()) {
5708 S->AddDecl(Named);
5709 IdResolver.AddDecl(Named);
5710 }
5711 }
5712 }
5713}
5714
John McCalld226f652010-08-21 09:40:31 +00005715void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005716 if (!D)
5717 return;
5718
5719 TemplateParameterList *Params = 0;
5720 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5721 Params = Template->getTemplateParameters();
5722 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5723 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5724 Params = PartialSpec->getTemplateParameters();
5725 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005726 return;
5727
Douglas Gregor6569d682009-05-27 23:11:45 +00005728 for (TemplateParameterList::iterator Param = Params->begin(),
5729 ParamEnd = Params->end();
5730 Param != ParamEnd; ++Param) {
5731 NamedDecl *Named = cast<NamedDecl>(*Param);
5732 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005733 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005734 IdResolver.AddDecl(Named);
5735 }
5736 }
5737}
5738
John McCalld226f652010-08-21 09:40:31 +00005739void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005740 if (!RecordD) return;
5741 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005742 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005743 PushDeclContext(S, Record);
5744}
5745
John McCalld226f652010-08-21 09:40:31 +00005746void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005747 if (!RecordD) return;
5748 PopDeclContext();
5749}
5750
Douglas Gregor72b505b2008-12-16 21:30:33 +00005751/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5752/// parsing a top-level (non-nested) C++ class, and we are now
5753/// parsing those parts of the given Method declaration that could
5754/// not be parsed earlier (C++ [class.mem]p2), such as default
5755/// arguments. This action should enter the scope of the given
5756/// Method declaration as if we had just parsed the qualified method
5757/// name. However, it should not bring the parameters into scope;
5758/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005759void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005760}
5761
5762/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5763/// C++ method declaration. We're (re-)introducing the given
5764/// function parameter into scope for use in parsing later parts of
5765/// the method declaration. For example, we could see an
5766/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005767void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005768 if (!ParamD)
5769 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005770
John McCalld226f652010-08-21 09:40:31 +00005771 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005772
5773 // If this parameter has an unparsed default argument, clear it out
5774 // to make way for the parsed default argument.
5775 if (Param->hasUnparsedDefaultArg())
5776 Param->setDefaultArg(0);
5777
John McCalld226f652010-08-21 09:40:31 +00005778 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005779 if (Param->getDeclName())
5780 IdResolver.AddDecl(Param);
5781}
5782
5783/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5784/// processing the delayed method declaration for Method. The method
5785/// declaration is now considered finished. There may be a separate
5786/// ActOnStartOfFunctionDef action later (not necessarily
5787/// immediately!) for this method, if it was also defined inside the
5788/// class body.
John McCalld226f652010-08-21 09:40:31 +00005789void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005790 if (!MethodD)
5791 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005792
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005793 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005794
John McCalld226f652010-08-21 09:40:31 +00005795 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005796
5797 // Now that we have our default arguments, check the constructor
5798 // again. It could produce additional diagnostics or affect whether
5799 // the class has implicitly-declared destructors, among other
5800 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005801 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5802 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005803
5804 // Check the default arguments, which we may have added.
5805 if (!Method->isInvalidDecl())
5806 CheckCXXDefaultArguments(Method);
5807}
5808
Douglas Gregor42a552f2008-11-05 20:51:48 +00005809/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005810/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005811/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005812/// emit diagnostics and set the invalid bit to true. In any case, the type
5813/// will be updated to reflect a well-formed type for the constructor and
5814/// returned.
5815QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005816 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005817 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005818
5819 // C++ [class.ctor]p3:
5820 // A constructor shall not be virtual (10.3) or static (9.4). A
5821 // constructor can be invoked for a const, volatile or const
5822 // volatile object. A constructor shall not be declared const,
5823 // volatile, or const volatile (9.3.2).
5824 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005825 if (!D.isInvalidType())
5826 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5827 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5828 << SourceRange(D.getIdentifierLoc());
5829 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005830 }
John McCalld931b082010-08-26 03:08:43 +00005831 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005832 if (!D.isInvalidType())
5833 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5834 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5835 << SourceRange(D.getIdentifierLoc());
5836 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005837 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005838 }
Mike Stump1eb44332009-09-09 15:08:12 +00005839
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005840 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005841 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005842 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005843 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5844 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005845 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005846 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5847 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005848 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005849 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5850 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005851 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005852 }
Mike Stump1eb44332009-09-09 15:08:12 +00005853
Douglas Gregorc938c162011-01-26 05:01:58 +00005854 // C++0x [class.ctor]p4:
5855 // A constructor shall not be declared with a ref-qualifier.
5856 if (FTI.hasRefQualifier()) {
5857 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5858 << FTI.RefQualifierIsLValueRef
5859 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5860 D.setInvalidType();
5861 }
5862
Douglas Gregor42a552f2008-11-05 20:51:48 +00005863 // Rebuild the function type "R" without any type qualifiers (in
5864 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005865 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005866 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005867 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5868 return R;
5869
5870 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5871 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005872 EPI.RefQualifier = RQ_None;
5873
Richard Smith07b0fdc2013-03-18 21:12:30 +00005874 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005875}
5876
Douglas Gregor72b505b2008-12-16 21:30:33 +00005877/// CheckConstructor - Checks a fully-formed constructor for
5878/// well-formedness, issuing any diagnostics required. Returns true if
5879/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005880void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005881 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005882 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5883 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005884 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005885
5886 // C++ [class.copy]p3:
5887 // A declaration of a constructor for a class X is ill-formed if
5888 // its first parameter is of type (optionally cv-qualified) X and
5889 // either there are no other parameters or else all other
5890 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005891 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005892 ((Constructor->getNumParams() == 1) ||
5893 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005894 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5895 Constructor->getTemplateSpecializationKind()
5896 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005897 QualType ParamType = Constructor->getParamDecl(0)->getType();
5898 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5899 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005900 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005901 const char *ConstRef
5902 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5903 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005904 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005905 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005906
5907 // FIXME: Rather that making the constructor invalid, we should endeavor
5908 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005909 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005910 }
5911 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005912}
5913
John McCall15442822010-08-04 01:04:25 +00005914/// CheckDestructor - Checks a fully-formed destructor definition for
5915/// well-formedness, issuing any diagnostics required. Returns true
5916/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005917bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005918 CXXRecordDecl *RD = Destructor->getParent();
5919
Peter Collingbournef51cfb82013-05-20 14:12:25 +00005920 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005921 SourceLocation Loc;
5922
5923 if (!Destructor->isImplicit())
5924 Loc = Destructor->getLocation();
5925 else
5926 Loc = RD->getLocation();
5927
5928 // If we have a virtual destructor, look up the deallocation function
5929 FunctionDecl *OperatorDelete = 0;
5930 DeclarationName Name =
5931 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005932 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005933 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005934
Eli Friedman5f2987c2012-02-02 03:46:19 +00005935 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005936
5937 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005938 }
Anders Carlsson37909802009-11-30 21:24:50 +00005939
5940 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005941}
5942
Mike Stump1eb44332009-09-09 15:08:12 +00005943static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005944FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5945 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5946 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005947 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005948}
5949
Douglas Gregor42a552f2008-11-05 20:51:48 +00005950/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5951/// the well-formednes of the destructor declarator @p D with type @p
5952/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005953/// emit diagnostics and set the declarator to invalid. Even if this happens,
5954/// will be updated to reflect a well-formed type for the destructor and
5955/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005956QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005957 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005958 // C++ [class.dtor]p1:
5959 // [...] A typedef-name that names a class is a class-name
5960 // (7.1.3); however, a typedef-name that names a class shall not
5961 // be used as the identifier in the declarator for a destructor
5962 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005963 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005964 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005965 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005966 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005967 else if (const TemplateSpecializationType *TST =
5968 DeclaratorType->getAs<TemplateSpecializationType>())
5969 if (TST->isTypeAlias())
5970 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5971 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005972
5973 // C++ [class.dtor]p2:
5974 // A destructor is used to destroy objects of its class type. A
5975 // destructor takes no parameters, and no return type can be
5976 // specified for it (not even void). The address of a destructor
5977 // shall not be taken. A destructor shall not be static. A
5978 // destructor can be invoked for a const, volatile or const
5979 // volatile object. A destructor shall not be declared const,
5980 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005981 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005982 if (!D.isInvalidType())
5983 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5984 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005985 << SourceRange(D.getIdentifierLoc())
5986 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5987
John McCalld931b082010-08-26 03:08:43 +00005988 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005989 }
Chris Lattner65401802009-04-25 08:28:21 +00005990 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005991 // Destructors don't have return types, but the parser will
5992 // happily parse something like:
5993 //
5994 // class X {
5995 // float ~X();
5996 // };
5997 //
5998 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005999 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6000 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6001 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006002 }
Mike Stump1eb44332009-09-09 15:08:12 +00006003
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006004 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006005 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006006 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006007 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6008 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006009 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006010 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6011 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006012 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006013 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6014 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006015 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006016 }
6017
Douglas Gregorc938c162011-01-26 05:01:58 +00006018 // C++0x [class.dtor]p2:
6019 // A destructor shall not be declared with a ref-qualifier.
6020 if (FTI.hasRefQualifier()) {
6021 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6022 << FTI.RefQualifierIsLValueRef
6023 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6024 D.setInvalidType();
6025 }
6026
Douglas Gregor42a552f2008-11-05 20:51:48 +00006027 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006028 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006029 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6030
6031 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006032 FTI.freeArgs();
6033 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006034 }
6035
Mike Stump1eb44332009-09-09 15:08:12 +00006036 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006037 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006038 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006039 D.setInvalidType();
6040 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006041
6042 // Rebuild the function type "R" without any type qualifiers or
6043 // parameters (in case any of the errors above fired) and with
6044 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006045 // types.
John McCalle23cf432010-12-14 08:05:40 +00006046 if (!D.isInvalidType())
6047 return R;
6048
Douglas Gregord92ec472010-07-01 05:10:53 +00006049 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006050 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6051 EPI.Variadic = false;
6052 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006053 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006054 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006055}
6056
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006057/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6058/// well-formednes of the conversion function declarator @p D with
6059/// type @p R. If there are any errors in the declarator, this routine
6060/// will emit diagnostics and return true. Otherwise, it will return
6061/// false. Either way, the type @p R will be updated to reflect a
6062/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006063void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006064 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006065 // C++ [class.conv.fct]p1:
6066 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006067 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006068 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006069 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006070 if (!D.isInvalidType())
6071 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006072 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6073 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006074 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006075 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006076 }
John McCalla3f81372010-04-13 00:04:31 +00006077
6078 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6079
Chris Lattner6e475012009-04-25 08:35:12 +00006080 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006081 // Conversion functions don't have return types, but the parser will
6082 // happily parse something like:
6083 //
6084 // class X {
6085 // float operator bool();
6086 // };
6087 //
6088 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006089 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6090 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6091 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006092 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006093 }
6094
John McCalla3f81372010-04-13 00:04:31 +00006095 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6096
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006097 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006098 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006099 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6100
6101 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006102 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006103 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006104 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006105 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006106 D.setInvalidType();
6107 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006108
John McCalla3f81372010-04-13 00:04:31 +00006109 // Diagnose "&operator bool()" and other such nonsense. This
6110 // is actually a gcc extension which we don't support.
6111 if (Proto->getResultType() != ConvType) {
6112 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6113 << Proto->getResultType();
6114 D.setInvalidType();
6115 ConvType = Proto->getResultType();
6116 }
6117
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006118 // C++ [class.conv.fct]p4:
6119 // The conversion-type-id shall not represent a function type nor
6120 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006121 if (ConvType->isArrayType()) {
6122 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6123 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006124 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006125 } else if (ConvType->isFunctionType()) {
6126 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6127 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006128 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006129 }
6130
6131 // Rebuild the function type "R" without any parameters (in case any
6132 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006133 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006134 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006135 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006136
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006137 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006138 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006139 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006140 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006141 diag::warn_cxx98_compat_explicit_conversion_functions :
6142 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006143 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006144}
6145
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006146/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6147/// the declaration of the given C++ conversion function. This routine
6148/// is responsible for recording the conversion function in the C++
6149/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006150Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006151 assert(Conversion && "Expected to receive a conversion function declaration");
6152
Douglas Gregor9d350972008-12-12 08:25:50 +00006153 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006154
6155 // Make sure we aren't redeclaring the conversion function.
6156 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006157
6158 // C++ [class.conv.fct]p1:
6159 // [...] A conversion function is never used to convert a
6160 // (possibly cv-qualified) object to the (possibly cv-qualified)
6161 // same object type (or a reference to it), to a (possibly
6162 // cv-qualified) base class of that type (or a reference to it),
6163 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006164 // FIXME: Suppress this warning if the conversion function ends up being a
6165 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006166 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006167 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006168 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006169 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006170 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6171 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006172 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006173 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006174 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6175 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006176 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006177 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006178 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006179 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006180 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006181 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006182 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006183 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006184 }
6185
Douglas Gregore80622f2010-09-29 04:25:11 +00006186 if (FunctionTemplateDecl *ConversionTemplate
6187 = Conversion->getDescribedFunctionTemplate())
6188 return ConversionTemplate;
6189
John McCalld226f652010-08-21 09:40:31 +00006190 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006191}
6192
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006193//===----------------------------------------------------------------------===//
6194// Namespace Handling
6195//===----------------------------------------------------------------------===//
6196
Richard Smithd1a55a62012-10-04 22:13:39 +00006197/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6198/// reopened.
6199static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6200 SourceLocation Loc,
6201 IdentifierInfo *II, bool *IsInline,
6202 NamespaceDecl *PrevNS) {
6203 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006204
Richard Smithc969e6a2012-10-05 01:46:25 +00006205 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6206 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6207 // inline namespaces, with the intention of bringing names into namespace std.
6208 //
6209 // We support this just well enough to get that case working; this is not
6210 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006211 if (*IsInline && II && II->getName().startswith("__atomic") &&
6212 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006213 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006214 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6215 NS = NS->getPreviousDecl())
6216 NS->setInline(*IsInline);
6217 // Patch up the lookup table for the containing namespace. This isn't really
6218 // correct, but it's good enough for this particular case.
6219 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6220 E = PrevNS->decls_end(); I != E; ++I)
6221 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6222 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6223 return;
6224 }
6225
6226 if (PrevNS->isInline())
6227 // The user probably just forgot the 'inline', so suggest that it
6228 // be added back.
6229 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6230 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6231 else
6232 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6233 << IsInline;
6234
6235 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6236 *IsInline = PrevNS->isInline();
6237}
John McCallea318642010-08-26 09:15:37 +00006238
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006239/// ActOnStartNamespaceDef - This is called at the start of a namespace
6240/// definition.
John McCalld226f652010-08-21 09:40:31 +00006241Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006242 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006243 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006244 SourceLocation IdentLoc,
6245 IdentifierInfo *II,
6246 SourceLocation LBrace,
6247 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006248 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6249 // For anonymous namespace, take the location of the left brace.
6250 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006251 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006252 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006253 bool IsStd = false;
6254 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006255 Scope *DeclRegionScope = NamespcScope->getParent();
6256
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006257 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006258 if (II) {
6259 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006260 // The identifier in an original-namespace-definition shall not
6261 // have been previously defined in the declarative region in
6262 // which the original-namespace-definition appears. The
6263 // identifier in an original-namespace-definition is the name of
6264 // the namespace. Subsequently in that declarative region, it is
6265 // treated as an original-namespace-name.
6266 //
6267 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006268 // look through using directives, just look for any ordinary names.
6269
6270 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006271 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6272 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006273 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006274 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6275 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6276 ++I) {
6277 if ((*I)->getIdentifierNamespace() & IDNS) {
6278 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006279 break;
6280 }
6281 }
6282
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006283 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6284
6285 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006286 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006287 if (IsInline != PrevNS->isInline())
6288 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6289 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006290 } else if (PrevDecl) {
6291 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006292 Diag(Loc, diag::err_redefinition_different_kind)
6293 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006294 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006295 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006296 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006297 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006298 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006299 // This is the first "real" definition of the namespace "std", so update
6300 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006301 PrevNS = getStdNamespace();
6302 IsStd = true;
6303 AddToKnown = !IsInline;
6304 } else {
6305 // We've seen this namespace for the first time.
6306 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006307 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006308 } else {
John McCall9aeed322009-10-01 00:25:31 +00006309 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006310
6311 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006312 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006313 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006314 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006315 } else {
6316 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006317 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006318 }
6319
Richard Smithd1a55a62012-10-04 22:13:39 +00006320 if (PrevNS && IsInline != PrevNS->isInline())
6321 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6322 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006323 }
6324
6325 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6326 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006327 if (IsInvalid)
6328 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006329
6330 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006331
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006332 // FIXME: Should we be merging attributes?
6333 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006334 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006335
6336 if (IsStd)
6337 StdNamespace = Namespc;
6338 if (AddToKnown)
6339 KnownNamespaces[Namespc] = false;
6340
6341 if (II) {
6342 PushOnScopeChains(Namespc, DeclRegionScope);
6343 } else {
6344 // Link the anonymous namespace into its parent.
6345 DeclContext *Parent = CurContext->getRedeclContext();
6346 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6347 TU->setAnonymousNamespace(Namespc);
6348 } else {
6349 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006350 }
John McCall9aeed322009-10-01 00:25:31 +00006351
Douglas Gregora4181472010-03-24 00:46:35 +00006352 CurContext->addDecl(Namespc);
6353
John McCall9aeed322009-10-01 00:25:31 +00006354 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6355 // behaves as if it were replaced by
6356 // namespace unique { /* empty body */ }
6357 // using namespace unique;
6358 // namespace unique { namespace-body }
6359 // where all occurrences of 'unique' in a translation unit are
6360 // replaced by the same identifier and this identifier differs
6361 // from all other identifiers in the entire program.
6362
6363 // We just create the namespace with an empty name and then add an
6364 // implicit using declaration, just like the standard suggests.
6365 //
6366 // CodeGen enforces the "universally unique" aspect by giving all
6367 // declarations semantically contained within an anonymous
6368 // namespace internal linkage.
6369
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006370 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006371 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006372 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006373 /* 'using' */ LBrace,
6374 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006375 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006376 /* identifier */ SourceLocation(),
6377 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006378 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006379 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006380 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006381 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006382 }
6383
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006384 ActOnDocumentableDecl(Namespc);
6385
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006386 // Although we could have an invalid decl (i.e. the namespace name is a
6387 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006388 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6389 // for the namespace has the declarations that showed up in that particular
6390 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006391 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006392 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006393}
6394
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006395/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6396/// is a namespace alias, returns the namespace it points to.
6397static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6398 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6399 return AD->getNamespace();
6400 return dyn_cast_or_null<NamespaceDecl>(D);
6401}
6402
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006403/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6404/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006405void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006406 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6407 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006408 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006409 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006410 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006411 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006412}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006413
John McCall384aff82010-08-25 07:42:41 +00006414CXXRecordDecl *Sema::getStdBadAlloc() const {
6415 return cast_or_null<CXXRecordDecl>(
6416 StdBadAlloc.get(Context.getExternalSource()));
6417}
6418
6419NamespaceDecl *Sema::getStdNamespace() const {
6420 return cast_or_null<NamespaceDecl>(
6421 StdNamespace.get(Context.getExternalSource()));
6422}
6423
Douglas Gregor66992202010-06-29 17:53:46 +00006424/// \brief Retrieve the special "std" namespace, which may require us to
6425/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006426NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006427 if (!StdNamespace) {
6428 // The "std" namespace has not yet been defined, so build one implicitly.
6429 StdNamespace = NamespaceDecl::Create(Context,
6430 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006431 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006432 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006433 &PP.getIdentifierTable().get("std"),
6434 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006435 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006436 }
6437
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006438 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006439}
6440
Sebastian Redl395e04d2012-01-17 22:49:33 +00006441bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006442 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006443 "Looking for std::initializer_list outside of C++.");
6444
6445 // We're looking for implicit instantiations of
6446 // template <typename E> class std::initializer_list.
6447
6448 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6449 return false;
6450
Sebastian Redl84760e32012-01-17 22:49:58 +00006451 ClassTemplateDecl *Template = 0;
6452 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006453
Sebastian Redl84760e32012-01-17 22:49:58 +00006454 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006455
Sebastian Redl84760e32012-01-17 22:49:58 +00006456 ClassTemplateSpecializationDecl *Specialization =
6457 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6458 if (!Specialization)
6459 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006460
Sebastian Redl84760e32012-01-17 22:49:58 +00006461 Template = Specialization->getSpecializedTemplate();
6462 Arguments = Specialization->getTemplateArgs().data();
6463 } else if (const TemplateSpecializationType *TST =
6464 Ty->getAs<TemplateSpecializationType>()) {
6465 Template = dyn_cast_or_null<ClassTemplateDecl>(
6466 TST->getTemplateName().getAsTemplateDecl());
6467 Arguments = TST->getArgs();
6468 }
6469 if (!Template)
6470 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006471
6472 if (!StdInitializerList) {
6473 // Haven't recognized std::initializer_list yet, maybe this is it.
6474 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6475 if (TemplateClass->getIdentifier() !=
6476 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006477 !getStdNamespace()->InEnclosingNamespaceSetOf(
6478 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006479 return false;
6480 // This is a template called std::initializer_list, but is it the right
6481 // template?
6482 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006483 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006484 return false;
6485 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6486 return false;
6487
6488 // It's the right template.
6489 StdInitializerList = Template;
6490 }
6491
6492 if (Template != StdInitializerList)
6493 return false;
6494
6495 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006496 if (Element)
6497 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006498 return true;
6499}
6500
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006501static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6502 NamespaceDecl *Std = S.getStdNamespace();
6503 if (!Std) {
6504 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6505 return 0;
6506 }
6507
6508 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6509 Loc, Sema::LookupOrdinaryName);
6510 if (!S.LookupQualifiedName(Result, Std)) {
6511 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6512 return 0;
6513 }
6514 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6515 if (!Template) {
6516 Result.suppressDiagnostics();
6517 // We found something weird. Complain about the first thing we found.
6518 NamedDecl *Found = *Result.begin();
6519 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6520 return 0;
6521 }
6522
6523 // We found some template called std::initializer_list. Now verify that it's
6524 // correct.
6525 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006526 if (Params->getMinRequiredArguments() != 1 ||
6527 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006528 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6529 return 0;
6530 }
6531
6532 return Template;
6533}
6534
6535QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6536 if (!StdInitializerList) {
6537 StdInitializerList = LookupStdInitializerList(*this, Loc);
6538 if (!StdInitializerList)
6539 return QualType();
6540 }
6541
6542 TemplateArgumentListInfo Args(Loc, Loc);
6543 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6544 Context.getTrivialTypeSourceInfo(Element,
6545 Loc)));
6546 return Context.getCanonicalType(
6547 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6548}
6549
Sebastian Redl98d36062012-01-17 22:50:14 +00006550bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6551 // C++ [dcl.init.list]p2:
6552 // A constructor is an initializer-list constructor if its first parameter
6553 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6554 // std::initializer_list<E> for some type E, and either there are no other
6555 // parameters or else all other parameters have default arguments.
6556 if (Ctor->getNumParams() < 1 ||
6557 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6558 return false;
6559
6560 QualType ArgType = Ctor->getParamDecl(0)->getType();
6561 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6562 ArgType = RT->getPointeeType().getUnqualifiedType();
6563
6564 return isStdInitializerList(ArgType, 0);
6565}
6566
Douglas Gregor9172aa62011-03-26 22:25:30 +00006567/// \brief Determine whether a using statement is in a context where it will be
6568/// apply in all contexts.
6569static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6570 switch (CurContext->getDeclKind()) {
6571 case Decl::TranslationUnit:
6572 return true;
6573 case Decl::LinkageSpec:
6574 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6575 default:
6576 return false;
6577 }
6578}
6579
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006580namespace {
6581
6582// Callback to only accept typo corrections that are namespaces.
6583class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6584 public:
6585 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6586 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6587 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6588 }
6589 return false;
6590 }
6591};
6592
6593}
6594
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006595static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6596 CXXScopeSpec &SS,
6597 SourceLocation IdentLoc,
6598 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006599 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006600 R.clear();
6601 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006602 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006603 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006604 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6605 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006606 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6607 bool droppedSpecifier = Corrected.WillReplaceSpecifier() &&
6608 Ident->getName().equals(CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006609 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006610 << Ident << DC << droppedSpecifier << CorrectedQuotedStr
6611 << SS.getRange() << FixItHint::CreateReplacement(
6612 Corrected.getCorrectionRange(), CorrectedStr);
6613 } else {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006614 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6615 << Ident << CorrectedQuotedStr
6616 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006617 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006618
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006619 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6620 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006621
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006622 R.addDecl(Corrected.getCorrectionDecl());
6623 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006624 }
6625 return false;
6626}
6627
John McCalld226f652010-08-21 09:40:31 +00006628Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006629 SourceLocation UsingLoc,
6630 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006631 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006632 SourceLocation IdentLoc,
6633 IdentifierInfo *NamespcName,
6634 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006635 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6636 assert(NamespcName && "Invalid NamespcName.");
6637 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006638
6639 // This can only happen along a recovery path.
6640 while (S->getFlags() & Scope::TemplateParamScope)
6641 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006642 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006643
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006644 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006645 NestedNameSpecifier *Qualifier = 0;
6646 if (SS.isSet())
6647 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6648
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006649 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006650 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6651 LookupParsedName(R, S, &SS);
6652 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006653 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006654
Douglas Gregor66992202010-06-29 17:53:46 +00006655 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006656 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006657 // Allow "using namespace std;" or "using namespace ::std;" even if
6658 // "std" hasn't been defined yet, for GCC compatibility.
6659 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6660 NamespcName->isStr("std")) {
6661 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006662 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006663 R.resolveKind();
6664 }
6665 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006666 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006667 }
6668
John McCallf36e02d2009-10-09 21:13:30 +00006669 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006670 NamedDecl *Named = R.getFoundDecl();
6671 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6672 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006673 // C++ [namespace.udir]p1:
6674 // A using-directive specifies that the names in the nominated
6675 // namespace can be used in the scope in which the
6676 // using-directive appears after the using-directive. During
6677 // unqualified name lookup (3.4.1), the names appear as if they
6678 // were declared in the nearest enclosing namespace which
6679 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006680 // namespace. [Note: in this context, "contains" means "contains
6681 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006682
6683 // Find enclosing context containing both using-directive and
6684 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006685 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006686 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6687 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6688 CommonAncestor = CommonAncestor->getParent();
6689
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006690 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006691 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006692 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006693
Douglas Gregor9172aa62011-03-26 22:25:30 +00006694 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006695 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006696 Diag(IdentLoc, diag::warn_using_directive_in_header);
6697 }
6698
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006699 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006700 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006701 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006702 }
6703
Richard Smith6b3d3e52013-02-20 19:22:51 +00006704 if (UDir)
6705 ProcessDeclAttributeList(S, UDir, AttrList);
6706
John McCalld226f652010-08-21 09:40:31 +00006707 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006708}
6709
6710void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006711 // If the scope has an associated entity and the using directive is at
6712 // namespace or translation unit scope, add the UsingDirectiveDecl into
6713 // its lookup structure so qualified name lookup can find it.
6714 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6715 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006716 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006717 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006718 // Otherwise, it is at block sope. The using-directives will affect lookup
6719 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006720 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006721}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006722
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006723
John McCalld226f652010-08-21 09:40:31 +00006724Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006725 AccessSpecifier AS,
6726 bool HasUsingKeyword,
6727 SourceLocation UsingLoc,
6728 CXXScopeSpec &SS,
6729 UnqualifiedId &Name,
6730 AttributeList *AttrList,
6731 bool IsTypeName,
6732 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006733 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006734
Douglas Gregor12c118a2009-11-04 16:30:06 +00006735 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006736 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006737 case UnqualifiedId::IK_Identifier:
6738 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006739 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006740 case UnqualifiedId::IK_ConversionFunctionId:
6741 break;
6742
6743 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006744 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006745 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006746 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006747 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006748 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006749 diag::err_using_decl_constructor)
6750 << SS.getRange();
6751
Richard Smith80ad52f2013-01-02 11:42:31 +00006752 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006753
John McCalld226f652010-08-21 09:40:31 +00006754 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006755
6756 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006757 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006758 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006759 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006760
6761 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006762 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006763 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006764 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006765 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006766
6767 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6768 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006769 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006770 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006771
Richard Smith07b0fdc2013-03-18 21:12:30 +00006772 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006773 // TODO: store that the declaration was written without 'using' and
6774 // talk about access decls instead of using decls in the
6775 // diagnostics.
6776 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006777 UsingLoc = Name.getLocStart();
Richard Smith1b2209f2013-06-13 02:12:17 +00006778
6779 Diag(UsingLoc,
6780 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6781 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006782 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006783 }
6784
Douglas Gregor56c04582010-12-16 00:46:58 +00006785 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6786 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6787 return 0;
6788
John McCall9488ea12009-11-17 05:59:44 +00006789 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006790 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006791 /* IsInstantiation */ false,
6792 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006793 if (UD)
6794 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006795
John McCalld226f652010-08-21 09:40:31 +00006796 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006797}
6798
Douglas Gregor09acc982010-07-07 23:08:52 +00006799/// \brief Determine whether a using declaration considers the given
6800/// declarations as "equivalent", e.g., if they are redeclarations of
6801/// the same entity or are both typedefs of the same type.
6802static bool
6803IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6804 bool &SuppressRedeclaration) {
6805 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6806 SuppressRedeclaration = false;
6807 return true;
6808 }
6809
Richard Smith162e1c12011-04-15 14:24:37 +00006810 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6811 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006812 SuppressRedeclaration = true;
6813 return Context.hasSameType(TD1->getUnderlyingType(),
6814 TD2->getUnderlyingType());
6815 }
6816
6817 return false;
6818}
6819
6820
John McCall9f54ad42009-12-10 09:41:52 +00006821/// Determines whether to create a using shadow decl for a particular
6822/// decl, given the set of decls existing prior to this using lookup.
6823bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6824 const LookupResult &Previous) {
6825 // Diagnose finding a decl which is not from a base class of the
6826 // current class. We do this now because there are cases where this
6827 // function will silently decide not to build a shadow decl, which
6828 // will pre-empt further diagnostics.
6829 //
6830 // We don't need to do this in C++0x because we do the check once on
6831 // the qualifier.
6832 //
6833 // FIXME: diagnose the following if we care enough:
6834 // struct A { int foo; };
6835 // struct B : A { using A::foo; };
6836 // template <class T> struct C : A {};
6837 // template <class T> struct D : C<T> { using B::foo; } // <---
6838 // This is invalid (during instantiation) in C++03 because B::foo
6839 // resolves to the using decl in B, which is not a base class of D<T>.
6840 // We can't diagnose it immediately because C<T> is an unknown
6841 // specialization. The UsingShadowDecl in D<T> then points directly
6842 // to A::foo, which will look well-formed when we instantiate.
6843 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006844 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006845 DeclContext *OrigDC = Orig->getDeclContext();
6846
6847 // Handle enums and anonymous structs.
6848 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6849 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6850 while (OrigRec->isAnonymousStructOrUnion())
6851 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6852
6853 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6854 if (OrigDC == CurContext) {
6855 Diag(Using->getLocation(),
6856 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006857 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006858 Diag(Orig->getLocation(), diag::note_using_decl_target);
6859 return true;
6860 }
6861
Douglas Gregordc355712011-02-25 00:36:19 +00006862 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006863 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006864 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006865 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006866 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006867 Diag(Orig->getLocation(), diag::note_using_decl_target);
6868 return true;
6869 }
6870 }
6871
6872 if (Previous.empty()) return false;
6873
6874 NamedDecl *Target = Orig;
6875 if (isa<UsingShadowDecl>(Target))
6876 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6877
John McCalld7533ec2009-12-11 02:33:26 +00006878 // If the target happens to be one of the previous declarations, we
6879 // don't have a conflict.
6880 //
6881 // FIXME: but we might be increasing its access, in which case we
6882 // should redeclare it.
6883 NamedDecl *NonTag = 0, *Tag = 0;
6884 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6885 I != E; ++I) {
6886 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006887 bool Result;
6888 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6889 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006890
6891 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6892 }
6893
John McCall9f54ad42009-12-10 09:41:52 +00006894 if (Target->isFunctionOrFunctionTemplate()) {
6895 FunctionDecl *FD;
6896 if (isa<FunctionTemplateDecl>(Target))
6897 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6898 else
6899 FD = cast<FunctionDecl>(Target);
6900
6901 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006902 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006903 case Ovl_Overload:
6904 return false;
6905
6906 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006907 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006908 break;
6909
6910 // We found a decl with the exact signature.
6911 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006912 // If we're in a record, we want to hide the target, so we
6913 // return true (without a diagnostic) to tell the caller not to
6914 // build a shadow decl.
6915 if (CurContext->isRecord())
6916 return true;
6917
6918 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006919 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006920 break;
6921 }
6922
6923 Diag(Target->getLocation(), diag::note_using_decl_target);
6924 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6925 return true;
6926 }
6927
6928 // Target is not a function.
6929
John McCall9f54ad42009-12-10 09:41:52 +00006930 if (isa<TagDecl>(Target)) {
6931 // No conflict between a tag and a non-tag.
6932 if (!Tag) return false;
6933
John McCall41ce66f2009-12-10 19:51:03 +00006934 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006935 Diag(Target->getLocation(), diag::note_using_decl_target);
6936 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6937 return true;
6938 }
6939
6940 // No conflict between a tag and a non-tag.
6941 if (!NonTag) return false;
6942
John McCall41ce66f2009-12-10 19:51:03 +00006943 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006944 Diag(Target->getLocation(), diag::note_using_decl_target);
6945 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6946 return true;
6947}
6948
John McCall9488ea12009-11-17 05:59:44 +00006949/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006950UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006951 UsingDecl *UD,
6952 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006953
6954 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006955 NamedDecl *Target = Orig;
6956 if (isa<UsingShadowDecl>(Target)) {
6957 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6958 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006959 }
6960
6961 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006962 = UsingShadowDecl::Create(Context, CurContext,
6963 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006964 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006965
6966 Shadow->setAccess(UD->getAccess());
6967 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6968 Shadow->setInvalidDecl();
6969
John McCall9488ea12009-11-17 05:59:44 +00006970 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006971 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006972 else
John McCall604e7f12009-12-08 07:46:18 +00006973 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006974
John McCall604e7f12009-12-08 07:46:18 +00006975
John McCall9f54ad42009-12-10 09:41:52 +00006976 return Shadow;
6977}
John McCall604e7f12009-12-08 07:46:18 +00006978
John McCall9f54ad42009-12-10 09:41:52 +00006979/// Hides a using shadow declaration. This is required by the current
6980/// using-decl implementation when a resolvable using declaration in a
6981/// class is followed by a declaration which would hide or override
6982/// one or more of the using decl's targets; for example:
6983///
6984/// struct Base { void foo(int); };
6985/// struct Derived : Base {
6986/// using Base::foo;
6987/// void foo(int);
6988/// };
6989///
6990/// The governing language is C++03 [namespace.udecl]p12:
6991///
6992/// When a using-declaration brings names from a base class into a
6993/// derived class scope, member functions in the derived class
6994/// override and/or hide member functions with the same name and
6995/// parameter types in a base class (rather than conflicting).
6996///
6997/// There are two ways to implement this:
6998/// (1) optimistically create shadow decls when they're not hidden
6999/// by existing declarations, or
7000/// (2) don't create any shadow decls (or at least don't make them
7001/// visible) until we've fully parsed/instantiated the class.
7002/// The problem with (1) is that we might have to retroactively remove
7003/// a shadow decl, which requires several O(n) operations because the
7004/// decl structures are (very reasonably) not designed for removal.
7005/// (2) avoids this but is very fiddly and phase-dependent.
7006void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007007 if (Shadow->getDeclName().getNameKind() ==
7008 DeclarationName::CXXConversionFunctionName)
7009 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7010
John McCall9f54ad42009-12-10 09:41:52 +00007011 // Remove it from the DeclContext...
7012 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007013
John McCall9f54ad42009-12-10 09:41:52 +00007014 // ...and the scope, if applicable...
7015 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007016 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007017 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007018 }
7019
John McCall9f54ad42009-12-10 09:41:52 +00007020 // ...and the using decl.
7021 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7022
7023 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007024 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007025}
7026
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007027class UsingValidatorCCC : public CorrectionCandidateCallback {
7028public:
7029 UsingValidatorCCC(bool IsTypeName, bool IsInstantiation)
7030 : IsTypeName(IsTypeName), IsInstantiation(IsInstantiation) {}
7031
7032 virtual bool ValidateCandidate(const TypoCorrection &Candidate) {
7033 if (NamedDecl *ND = Candidate.getCorrectionDecl()) {
7034 if (isa<NamespaceDecl>(ND))
7035 return false;
7036 // Completely unqualified names are invalid for a 'using' declaration.
7037 bool droppedSpecifier = Candidate.WillReplaceSpecifier() &&
7038 !Candidate.getCorrectionSpecifier();
7039 if (droppedSpecifier)
7040 return false;
7041 else if (isa<TypeDecl>(ND))
7042 return IsTypeName || !IsInstantiation;
7043 else
7044 return !IsTypeName;
7045 } else {
7046 // Keywords are not valid here.
7047 return false;
7048 }
7049 }
7050
7051private:
7052 bool IsTypeName;
7053 bool IsInstantiation;
7054};
7055
John McCall7ba107a2009-11-18 02:36:19 +00007056/// Builds a using declaration.
7057///
7058/// \param IsInstantiation - Whether this call arises from an
7059/// instantiation of an unresolved using declaration. We treat
7060/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007061NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7062 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007063 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007064 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007065 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007066 bool IsInstantiation,
7067 bool IsTypeName,
7068 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007069 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007070 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007071 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007072
Anders Carlsson550b14b2009-08-28 05:49:21 +00007073 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007074
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007075 if (SS.isEmpty()) {
7076 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007077 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007078 }
Mike Stump1eb44332009-09-09 15:08:12 +00007079
John McCall9f54ad42009-12-10 09:41:52 +00007080 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007081 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007082 ForRedeclaration);
7083 Previous.setHideTags(false);
7084 if (S) {
7085 LookupName(Previous, S);
7086
7087 // It is really dumb that we have to do this.
7088 LookupResult::Filter F = Previous.makeFilter();
7089 while (F.hasNext()) {
7090 NamedDecl *D = F.next();
7091 if (!isDeclInScope(D, CurContext, S))
7092 F.erase();
7093 }
7094 F.done();
7095 } else {
7096 assert(IsInstantiation && "no scope in non-instantiation");
7097 assert(CurContext->isRecord() && "scope not record in instantiation");
7098 LookupQualifiedName(Previous, CurContext);
7099 }
7100
John McCall9f54ad42009-12-10 09:41:52 +00007101 // Check for invalid redeclarations.
7102 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7103 return 0;
7104
7105 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007106 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7107 return 0;
7108
John McCallaf8e6ed2009-11-12 03:15:40 +00007109 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007110 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007111 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007112 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00007113 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00007114 // FIXME: not all declaration name kinds are legal here
7115 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7116 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007117 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007118 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007119 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007120 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7121 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007122 }
John McCalled976492009-12-04 22:46:56 +00007123 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007124 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7125 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007126 }
John McCalled976492009-12-04 22:46:56 +00007127 D->setAccess(AS);
7128 CurContext->addDecl(D);
7129
7130 if (!LookupContext) return D;
7131 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007132
John McCall77bb1aa2010-05-01 00:40:08 +00007133 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007134 UD->setInvalidDecl();
7135 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007136 }
7137
Richard Smithc5a89a12012-04-02 01:30:27 +00007138 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007139 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007140 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007141 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007142 return UD;
7143 }
7144
7145 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007146
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007147 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007148
John McCall604e7f12009-12-08 07:46:18 +00007149 // Unlike most lookups, we don't always want to hide tag
7150 // declarations: tag names are visible through the using declaration
7151 // even if hidden by ordinary names, *except* in a dependent context
7152 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007153 if (!IsInstantiation)
7154 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007155
John McCallb9abd8722012-04-07 03:04:20 +00007156 // For the purposes of this lookup, we have a base object type
7157 // equal to that of the current context.
7158 if (CurContext->isRecord()) {
7159 R.setBaseObjectType(
7160 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7161 }
7162
John McCalla24dc2e2009-11-17 02:14:36 +00007163 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007164
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007165 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007166 if (R.empty()) {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007167 UsingValidatorCCC CCC(IsTypeName, IsInstantiation);
7168 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7169 R.getLookupKind(), S, &SS, CCC)){
7170 // We reject any correction for which ND would be NULL.
7171 NamedDecl *ND = Corrected.getCorrectionDecl();
7172 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
7173 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
7174 R.setLookupName(Corrected.getCorrection());
7175 R.addDecl(ND);
7176 // We reject candidates where droppedSpecifier == true, hence the
7177 // literal '0' below.
7178 Diag(R.getNameLoc(), diag::err_no_member_suggest)
7179 << NameInfo.getName() << LookupContext << 0
7180 << CorrectedQuotedStr << SS.getRange()
7181 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
7182 CorrectedStr);
7183 Diag(ND->getLocation(), diag::note_previous_decl)
7184 << CorrectedQuotedStr;
7185 } else {
7186 Diag(IdentLoc, diag::err_no_member)
7187 << NameInfo.getName() << LookupContext << SS.getRange();
7188 UD->setInvalidDecl();
7189 return UD;
7190 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007191 }
7192
John McCalled976492009-12-04 22:46:56 +00007193 if (R.isAmbiguous()) {
7194 UD->setInvalidDecl();
7195 return UD;
7196 }
Mike Stump1eb44332009-09-09 15:08:12 +00007197
John McCall7ba107a2009-11-18 02:36:19 +00007198 if (IsTypeName) {
7199 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007200 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007201 Diag(IdentLoc, diag::err_using_typename_non_type);
7202 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7203 Diag((*I)->getUnderlyingDecl()->getLocation(),
7204 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007205 UD->setInvalidDecl();
7206 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007207 }
7208 } else {
7209 // If we asked for a non-typename and we got a type, error out,
7210 // but only if this is an instantiation of an unresolved using
7211 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007212 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007213 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7214 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007215 UD->setInvalidDecl();
7216 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007217 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007218 }
7219
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007220 // C++0x N2914 [namespace.udecl]p6:
7221 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007222 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007223 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7224 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007225 UD->setInvalidDecl();
7226 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007227 }
Mike Stump1eb44332009-09-09 15:08:12 +00007228
John McCall9f54ad42009-12-10 09:41:52 +00007229 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7230 if (!CheckUsingShadowDecl(UD, *I, Previous))
7231 BuildUsingShadowDecl(S, UD, *I);
7232 }
John McCall9488ea12009-11-17 05:59:44 +00007233
7234 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007235}
7236
Sebastian Redlf677ea32011-02-05 19:23:19 +00007237/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007238bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7239 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007240
Douglas Gregordc355712011-02-25 00:36:19 +00007241 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007242 assert(SourceType &&
7243 "Using decl naming constructor doesn't have type in scope spec.");
7244 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7245
7246 // Check whether the named type is a direct base class.
7247 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7248 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7249 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7250 BaseIt != BaseE; ++BaseIt) {
7251 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7252 if (CanonicalSourceType == BaseType)
7253 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007254 if (BaseIt->getType()->isDependentType())
7255 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007256 }
7257
7258 if (BaseIt == BaseE) {
7259 // Did not find SourceType in the bases.
7260 Diag(UD->getUsingLocation(),
7261 diag::err_using_decl_constructor_not_in_direct_base)
7262 << UD->getNameInfo().getSourceRange()
7263 << QualType(SourceType, 0) << TargetClass;
7264 return true;
7265 }
7266
Richard Smithc5a89a12012-04-02 01:30:27 +00007267 if (!CurContext->isDependentContext())
7268 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007269
7270 return false;
7271}
7272
John McCall9f54ad42009-12-10 09:41:52 +00007273/// Checks that the given using declaration is not an invalid
7274/// redeclaration. Note that this is checking only for the using decl
7275/// itself, not for any ill-formedness among the UsingShadowDecls.
7276bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7277 bool isTypeName,
7278 const CXXScopeSpec &SS,
7279 SourceLocation NameLoc,
7280 const LookupResult &Prev) {
7281 // C++03 [namespace.udecl]p8:
7282 // C++0x [namespace.udecl]p10:
7283 // A using-declaration is a declaration and can therefore be used
7284 // repeatedly where (and only where) multiple declarations are
7285 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007286 //
John McCall8a726212010-11-29 18:01:58 +00007287 // That's in non-member contexts.
7288 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007289 return false;
7290
7291 NestedNameSpecifier *Qual
7292 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7293
7294 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7295 NamedDecl *D = *I;
7296
7297 bool DTypename;
7298 NestedNameSpecifier *DQual;
7299 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7300 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007301 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007302 } else if (UnresolvedUsingValueDecl *UD
7303 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7304 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007305 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007306 } else if (UnresolvedUsingTypenameDecl *UD
7307 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7308 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007309 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007310 } else continue;
7311
7312 // using decls differ if one says 'typename' and the other doesn't.
7313 // FIXME: non-dependent using decls?
7314 if (isTypeName != DTypename) continue;
7315
7316 // using decls differ if they name different scopes (but note that
7317 // template instantiation can cause this check to trigger when it
7318 // didn't before instantiation).
7319 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7320 Context.getCanonicalNestedNameSpecifier(DQual))
7321 continue;
7322
7323 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007324 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007325 return true;
7326 }
7327
7328 return false;
7329}
7330
John McCall604e7f12009-12-08 07:46:18 +00007331
John McCalled976492009-12-04 22:46:56 +00007332/// Checks that the given nested-name qualifier used in a using decl
7333/// in the current context is appropriately related to the current
7334/// scope. If an error is found, diagnoses it and returns true.
7335bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7336 const CXXScopeSpec &SS,
7337 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007338 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007339
John McCall604e7f12009-12-08 07:46:18 +00007340 if (!CurContext->isRecord()) {
7341 // C++03 [namespace.udecl]p3:
7342 // C++0x [namespace.udecl]p8:
7343 // A using-declaration for a class member shall be a member-declaration.
7344
7345 // If we weren't able to compute a valid scope, it must be a
7346 // dependent class scope.
7347 if (!NamedContext || NamedContext->isRecord()) {
7348 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7349 << SS.getRange();
7350 return true;
7351 }
7352
7353 // Otherwise, everything is known to be fine.
7354 return false;
7355 }
7356
7357 // The current scope is a record.
7358
7359 // If the named context is dependent, we can't decide much.
7360 if (!NamedContext) {
7361 // FIXME: in C++0x, we can diagnose if we can prove that the
7362 // nested-name-specifier does not refer to a base class, which is
7363 // still possible in some cases.
7364
7365 // Otherwise we have to conservatively report that things might be
7366 // okay.
7367 return false;
7368 }
7369
7370 if (!NamedContext->isRecord()) {
7371 // Ideally this would point at the last name in the specifier,
7372 // but we don't have that level of source info.
7373 Diag(SS.getRange().getBegin(),
7374 diag::err_using_decl_nested_name_specifier_is_not_class)
7375 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7376 return true;
7377 }
7378
Douglas Gregor6fb07292010-12-21 07:41:49 +00007379 if (!NamedContext->isDependentContext() &&
7380 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7381 return true;
7382
Richard Smith80ad52f2013-01-02 11:42:31 +00007383 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007384 // C++0x [namespace.udecl]p3:
7385 // In a using-declaration used as a member-declaration, the
7386 // nested-name-specifier shall name a base class of the class
7387 // being defined.
7388
7389 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7390 cast<CXXRecordDecl>(NamedContext))) {
7391 if (CurContext == NamedContext) {
7392 Diag(NameLoc,
7393 diag::err_using_decl_nested_name_specifier_is_current_class)
7394 << SS.getRange();
7395 return true;
7396 }
7397
7398 Diag(SS.getRange().getBegin(),
7399 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7400 << (NestedNameSpecifier*) SS.getScopeRep()
7401 << cast<CXXRecordDecl>(CurContext)
7402 << SS.getRange();
7403 return true;
7404 }
7405
7406 return false;
7407 }
7408
7409 // C++03 [namespace.udecl]p4:
7410 // A using-declaration used as a member-declaration shall refer
7411 // to a member of a base class of the class being defined [etc.].
7412
7413 // Salient point: SS doesn't have to name a base class as long as
7414 // lookup only finds members from base classes. Therefore we can
7415 // diagnose here only if we can prove that that can't happen,
7416 // i.e. if the class hierarchies provably don't intersect.
7417
7418 // TODO: it would be nice if "definitely valid" results were cached
7419 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7420 // need to be repeated.
7421
7422 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007423 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007424
7425 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7426 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7427 Data->Bases.insert(Base);
7428 return true;
7429 }
7430
7431 bool hasDependentBases(const CXXRecordDecl *Class) {
7432 return !Class->forallBases(collect, this);
7433 }
7434
7435 /// Returns true if the base is dependent or is one of the
7436 /// accumulated base classes.
7437 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7438 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7439 return !Data->Bases.count(Base);
7440 }
7441
7442 bool mightShareBases(const CXXRecordDecl *Class) {
7443 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7444 }
7445 };
7446
7447 UserData Data;
7448
7449 // Returns false if we find a dependent base.
7450 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7451 return false;
7452
7453 // Returns false if the class has a dependent base or if it or one
7454 // of its bases is present in the base set of the current context.
7455 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7456 return false;
7457
7458 Diag(SS.getRange().getBegin(),
7459 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7460 << (NestedNameSpecifier*) SS.getScopeRep()
7461 << cast<CXXRecordDecl>(CurContext)
7462 << SS.getRange();
7463
7464 return true;
John McCalled976492009-12-04 22:46:56 +00007465}
7466
Richard Smith162e1c12011-04-15 14:24:37 +00007467Decl *Sema::ActOnAliasDeclaration(Scope *S,
7468 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007469 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007470 SourceLocation UsingLoc,
7471 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007472 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007473 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007474 // Skip up to the relevant declaration scope.
7475 while (S->getFlags() & Scope::TemplateParamScope)
7476 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007477 assert((S->getFlags() & Scope::DeclScope) &&
7478 "got alias-declaration outside of declaration scope");
7479
7480 if (Type.isInvalid())
7481 return 0;
7482
7483 bool Invalid = false;
7484 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7485 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007486 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007487
7488 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7489 return 0;
7490
7491 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007492 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007493 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007494 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7495 TInfo->getTypeLoc().getBeginLoc());
7496 }
Richard Smith162e1c12011-04-15 14:24:37 +00007497
7498 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7499 LookupName(Previous, S);
7500
7501 // Warn about shadowing the name of a template parameter.
7502 if (Previous.isSingleResult() &&
7503 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007504 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007505 Previous.clear();
7506 }
7507
7508 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7509 "name in alias declaration must be an identifier");
7510 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7511 Name.StartLocation,
7512 Name.Identifier, TInfo);
7513
7514 NewTD->setAccess(AS);
7515
7516 if (Invalid)
7517 NewTD->setInvalidDecl();
7518
Richard Smith6b3d3e52013-02-20 19:22:51 +00007519 ProcessDeclAttributeList(S, NewTD, AttrList);
7520
Richard Smith3e4c6c42011-05-05 21:57:07 +00007521 CheckTypedefForVariablyModifiedType(S, NewTD);
7522 Invalid |= NewTD->isInvalidDecl();
7523
Richard Smith162e1c12011-04-15 14:24:37 +00007524 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007525
7526 NamedDecl *NewND;
7527 if (TemplateParamLists.size()) {
7528 TypeAliasTemplateDecl *OldDecl = 0;
7529 TemplateParameterList *OldTemplateParams = 0;
7530
7531 if (TemplateParamLists.size() != 1) {
7532 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007533 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7534 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007535 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007536 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007537
7538 // Only consider previous declarations in the same scope.
7539 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7540 /*ExplicitInstantiationOrSpecialization*/false);
7541 if (!Previous.empty()) {
7542 Redeclaration = true;
7543
7544 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7545 if (!OldDecl && !Invalid) {
7546 Diag(UsingLoc, diag::err_redefinition_different_kind)
7547 << Name.Identifier;
7548
7549 NamedDecl *OldD = Previous.getRepresentativeDecl();
7550 if (OldD->getLocation().isValid())
7551 Diag(OldD->getLocation(), diag::note_previous_definition);
7552
7553 Invalid = true;
7554 }
7555
7556 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7557 if (TemplateParameterListsAreEqual(TemplateParams,
7558 OldDecl->getTemplateParameters(),
7559 /*Complain=*/true,
7560 TPL_TemplateMatch))
7561 OldTemplateParams = OldDecl->getTemplateParameters();
7562 else
7563 Invalid = true;
7564
7565 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7566 if (!Invalid &&
7567 !Context.hasSameType(OldTD->getUnderlyingType(),
7568 NewTD->getUnderlyingType())) {
7569 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7570 // but we can't reasonably accept it.
7571 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7572 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7573 if (OldTD->getLocation().isValid())
7574 Diag(OldTD->getLocation(), diag::note_previous_definition);
7575 Invalid = true;
7576 }
7577 }
7578 }
7579
7580 // Merge any previous default template arguments into our parameters,
7581 // and check the parameter list.
7582 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7583 TPC_TypeAliasTemplate))
7584 return 0;
7585
7586 TypeAliasTemplateDecl *NewDecl =
7587 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7588 Name.Identifier, TemplateParams,
7589 NewTD);
7590
7591 NewDecl->setAccess(AS);
7592
7593 if (Invalid)
7594 NewDecl->setInvalidDecl();
7595 else if (OldDecl)
7596 NewDecl->setPreviousDeclaration(OldDecl);
7597
7598 NewND = NewDecl;
7599 } else {
7600 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7601 NewND = NewTD;
7602 }
Richard Smith162e1c12011-04-15 14:24:37 +00007603
7604 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007605 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007606
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007607 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007608 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007609}
7610
John McCalld226f652010-08-21 09:40:31 +00007611Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007612 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007613 SourceLocation AliasLoc,
7614 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007615 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007616 SourceLocation IdentLoc,
7617 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007618
Anders Carlsson81c85c42009-03-28 23:53:49 +00007619 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007620 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7621 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007622
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007623 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007624 NamedDecl *PrevDecl
7625 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7626 ForRedeclaration);
7627 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7628 PrevDecl = 0;
7629
7630 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007631 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007632 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007633 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007634 // FIXME: At some point, we'll want to create the (redundant)
7635 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007636 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007637 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007638 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007639 }
Mike Stump1eb44332009-09-09 15:08:12 +00007640
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007641 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7642 diag::err_redefinition_different_kind;
7643 Diag(AliasLoc, DiagID) << Alias;
7644 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007645 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007646 }
7647
John McCalla24dc2e2009-11-17 02:14:36 +00007648 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007649 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007650
John McCallf36e02d2009-10-09 21:13:30 +00007651 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007652 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007653 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007654 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007655 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007656 }
Mike Stump1eb44332009-09-09 15:08:12 +00007657
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007658 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007659 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007660 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007661 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007662
John McCall3dbd3d52010-02-16 06:53:13 +00007663 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007664 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007665}
7666
Sean Hunt001cad92011-05-10 00:49:42 +00007667Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007668Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7669 CXXMethodDecl *MD) {
7670 CXXRecordDecl *ClassDecl = MD->getParent();
7671
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007672 // C++ [except.spec]p14:
7673 // An implicitly declared special member function (Clause 12) shall have an
7674 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007675 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007676 if (ClassDecl->isInvalidDecl())
7677 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007678
Sebastian Redl60618fa2011-03-12 11:50:43 +00007679 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007680 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7681 BEnd = ClassDecl->bases_end();
7682 B != BEnd; ++B) {
7683 if (B->isVirtual()) // Handled below.
7684 continue;
7685
Douglas Gregor18274032010-07-03 00:47:00 +00007686 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7687 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007688 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7689 // If this is a deleted function, add it anyway. This might be conformant
7690 // with the standard. This might not. I'm not sure. It might not matter.
7691 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007692 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007693 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007694 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007695
7696 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007697 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7698 BEnd = ClassDecl->vbases_end();
7699 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007700 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7701 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007702 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7703 // If this is a deleted function, add it anyway. This might be conformant
7704 // with the standard. This might not. I'm not sure. It might not matter.
7705 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007706 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007707 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007708 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007709
7710 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007711 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7712 FEnd = ClassDecl->field_end();
7713 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007714 if (F->hasInClassInitializer()) {
7715 if (Expr *E = F->getInClassInitializer())
7716 ExceptSpec.CalledExpr(E);
7717 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007718 // DR1351:
7719 // If the brace-or-equal-initializer of a non-static data member
7720 // invokes a defaulted default constructor of its class or of an
7721 // enclosing class in a potentially evaluated subexpression, the
7722 // program is ill-formed.
7723 //
7724 // This resolution is unworkable: the exception specification of the
7725 // default constructor can be needed in an unevaluated context, in
7726 // particular, in the operand of a noexcept-expression, and we can be
7727 // unable to compute an exception specification for an enclosed class.
7728 //
7729 // We do not allow an in-class initializer to require the evaluation
7730 // of the exception specification for any in-class initializer whose
7731 // definition is not lexically complete.
7732 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007733 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007734 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007735 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7736 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7737 // If this is a deleted function, add it anyway. This might be conformant
7738 // with the standard. This might not. I'm not sure. It might not matter.
7739 // In particular, the problem is that this function never gets called. It
7740 // might just be ill-formed because this function attempts to refer to
7741 // a deleted function here.
7742 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007743 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007744 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007745 }
John McCalle23cf432010-12-14 08:05:40 +00007746
Sean Hunt001cad92011-05-10 00:49:42 +00007747 return ExceptSpec;
7748}
7749
Richard Smith07b0fdc2013-03-18 21:12:30 +00007750Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007751Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7752 CXXRecordDecl *ClassDecl = CD->getParent();
7753
7754 // C++ [except.spec]p14:
7755 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007756 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007757 if (ClassDecl->isInvalidDecl())
7758 return ExceptSpec;
7759
7760 // Inherited constructor.
7761 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7762 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7763 // FIXME: Copying or moving the parameters could add extra exceptions to the
7764 // set, as could the default arguments for the inherited constructor. This
7765 // will be addressed when we implement the resolution of core issue 1351.
7766 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7767
7768 // Direct base-class constructors.
7769 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7770 BEnd = ClassDecl->bases_end();
7771 B != BEnd; ++B) {
7772 if (B->isVirtual()) // Handled below.
7773 continue;
7774
7775 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7776 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7777 if (BaseClassDecl == InheritedDecl)
7778 continue;
7779 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7780 if (Constructor)
7781 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7782 }
7783 }
7784
7785 // Virtual base-class constructors.
7786 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7787 BEnd = ClassDecl->vbases_end();
7788 B != BEnd; ++B) {
7789 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7790 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7791 if (BaseClassDecl == InheritedDecl)
7792 continue;
7793 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7794 if (Constructor)
7795 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7796 }
7797 }
7798
7799 // Field constructors.
7800 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7801 FEnd = ClassDecl->field_end();
7802 F != FEnd; ++F) {
7803 if (F->hasInClassInitializer()) {
7804 if (Expr *E = F->getInClassInitializer())
7805 ExceptSpec.CalledExpr(E);
7806 else if (!F->isInvalidDecl())
7807 Diag(CD->getLocation(),
7808 diag::err_in_class_initializer_references_def_ctor) << CD;
7809 } else if (const RecordType *RecordTy
7810 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7811 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7812 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7813 if (Constructor)
7814 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7815 }
7816 }
7817
Richard Smith07b0fdc2013-03-18 21:12:30 +00007818 return ExceptSpec;
7819}
7820
Richard Smithafb49182012-11-29 01:34:07 +00007821namespace {
7822/// RAII object to register a special member as being currently declared.
7823struct DeclaringSpecialMember {
7824 Sema &S;
7825 Sema::SpecialMemberDecl D;
7826 bool WasAlreadyBeingDeclared;
7827
7828 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7829 : S(S), D(RD, CSM) {
7830 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7831 if (WasAlreadyBeingDeclared)
7832 // This almost never happens, but if it does, ensure that our cache
7833 // doesn't contain a stale result.
7834 S.SpecialMemberCache.clear();
7835
7836 // FIXME: Register a note to be produced if we encounter an error while
7837 // declaring the special member.
7838 }
7839 ~DeclaringSpecialMember() {
7840 if (!WasAlreadyBeingDeclared)
7841 S.SpecialMembersBeingDeclared.erase(D);
7842 }
7843
7844 /// \brief Are we already trying to declare this special member?
7845 bool isAlreadyBeingDeclared() const {
7846 return WasAlreadyBeingDeclared;
7847 }
7848};
7849}
7850
Sean Hunt001cad92011-05-10 00:49:42 +00007851CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7852 CXXRecordDecl *ClassDecl) {
7853 // C++ [class.ctor]p5:
7854 // A default constructor for a class X is a constructor of class X
7855 // that can be called without an argument. If there is no
7856 // user-declared constructor for class X, a default constructor is
7857 // implicitly declared. An implicitly-declared default constructor
7858 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007859 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007860 "Should not build implicit default constructor!");
7861
Richard Smithafb49182012-11-29 01:34:07 +00007862 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7863 if (DSM.isAlreadyBeingDeclared())
7864 return 0;
7865
Richard Smith7756afa2012-06-10 05:43:50 +00007866 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7867 CXXDefaultConstructor,
7868 false);
7869
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007870 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007871 CanQualType ClassType
7872 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007873 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007874 DeclarationName Name
7875 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007876 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007877 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007878 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007879 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007880 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007881 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007882 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007883 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007884
7885 // Build an exception specification pointing back at this constructor.
7886 FunctionProtoType::ExtProtoInfo EPI;
7887 EPI.ExceptionSpecType = EST_Unevaluated;
7888 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007889 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007890
Richard Smithbc2a35d2012-12-08 08:32:28 +00007891 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7892 // constructors is easy to compute.
7893 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7894
7895 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007896 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007897
Douglas Gregor18274032010-07-03 00:47:00 +00007898 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007899 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007900
Douglas Gregor23c94db2010-07-02 17:43:08 +00007901 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007902 PushOnScopeChains(DefaultCon, S, false);
7903 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007904
Douglas Gregor32df23e2010-07-01 22:02:46 +00007905 return DefaultCon;
7906}
7907
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007908void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7909 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007910 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007911 !Constructor->doesThisDeclarationHaveABody() &&
7912 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007913 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007914
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007915 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007916 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007917
Eli Friedman9a14db32012-10-18 20:14:08 +00007918 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007919 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007920 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007921 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007922 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007923 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007924 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007925 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007926 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007927
7928 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007929 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007930
7931 Constructor->setUsed();
7932 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007933
7934 if (ASTMutationListener *L = getASTMutationListener()) {
7935 L->CompletedImplicitDefinition(Constructor);
7936 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007937}
7938
Richard Smith7a614d82011-06-11 17:19:42 +00007939void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007940 // Check that any explicitly-defaulted methods have exception specifications
7941 // compatible with their implicit exception specifications.
7942 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007943}
7944
Richard Smith4841ca52013-04-10 05:48:59 +00007945namespace {
7946/// Information on inheriting constructors to declare.
7947class InheritingConstructorInfo {
7948public:
7949 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7950 : SemaRef(SemaRef), Derived(Derived) {
7951 // Mark the constructors that we already have in the derived class.
7952 //
7953 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7954 // unless there is a user-declared constructor with the same signature in
7955 // the class where the using-declaration appears.
7956 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7957 }
7958
7959 void inheritAll(CXXRecordDecl *RD) {
7960 visitAll(RD, &InheritingConstructorInfo::inherit);
7961 }
7962
7963private:
7964 /// Information about an inheriting constructor.
7965 struct InheritingConstructor {
7966 InheritingConstructor()
7967 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7968
7969 /// If \c true, a constructor with this signature is already declared
7970 /// in the derived class.
7971 bool DeclaredInDerived;
7972
7973 /// The constructor which is inherited.
7974 const CXXConstructorDecl *BaseCtor;
7975
7976 /// The derived constructor we declared.
7977 CXXConstructorDecl *DerivedCtor;
7978 };
7979
7980 /// Inheriting constructors with a given canonical type. There can be at
7981 /// most one such non-template constructor, and any number of templated
7982 /// constructors.
7983 struct InheritingConstructorsForType {
7984 InheritingConstructor NonTemplate;
7985 llvm::SmallVector<
7986 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7987
7988 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7989 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7990 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7991 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7992 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7993 false, S.TPL_TemplateMatch))
7994 return Templates[I].second;
7995 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7996 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007997 }
Richard Smith4841ca52013-04-10 05:48:59 +00007998
7999 return NonTemplate;
8000 }
8001 };
8002
8003 /// Get or create the inheriting constructor record for a constructor.
8004 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8005 QualType CtorType) {
8006 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8007 .getEntry(SemaRef, Ctor);
8008 }
8009
8010 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8011
8012 /// Process all constructors for a class.
8013 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8014 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8015 CtorE = RD->ctor_end();
8016 CtorIt != CtorE; ++CtorIt)
8017 (this->*Callback)(*CtorIt);
8018 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8019 I(RD->decls_begin()), E(RD->decls_end());
8020 I != E; ++I) {
8021 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8022 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8023 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008024 }
8025 }
Richard Smith4841ca52013-04-10 05:48:59 +00008026
8027 /// Note that a constructor (or constructor template) was declared in Derived.
8028 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8029 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8030 }
8031
8032 /// Inherit a single constructor.
8033 void inherit(const CXXConstructorDecl *Ctor) {
8034 const FunctionProtoType *CtorType =
8035 Ctor->getType()->castAs<FunctionProtoType>();
8036 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8037 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8038
8039 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8040
8041 // Core issue (no number yet): the ellipsis is always discarded.
8042 if (EPI.Variadic) {
8043 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8044 SemaRef.Diag(Ctor->getLocation(),
8045 diag::note_using_decl_constructor_ellipsis);
8046 EPI.Variadic = false;
8047 }
8048
8049 // Declare a constructor for each number of parameters.
8050 //
8051 // C++11 [class.inhctor]p1:
8052 // The candidate set of inherited constructors from the class X named in
8053 // the using-declaration consists of [... modulo defects ...] for each
8054 // constructor or constructor template of X, the set of constructors or
8055 // constructor templates that results from omitting any ellipsis parameter
8056 // specification and successively omitting parameters with a default
8057 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008058 unsigned MinParams = minParamsToInherit(Ctor);
8059 unsigned Params = Ctor->getNumParams();
8060 if (Params >= MinParams) {
8061 do
8062 declareCtor(UsingLoc, Ctor,
8063 SemaRef.Context.getFunctionType(
8064 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8065 while (Params > MinParams &&
8066 Ctor->getParamDecl(--Params)->hasDefaultArg());
8067 }
Richard Smith4841ca52013-04-10 05:48:59 +00008068 }
8069
8070 /// Find the using-declaration which specified that we should inherit the
8071 /// constructors of \p Base.
8072 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8073 // No fancy lookup required; just look for the base constructor name
8074 // directly within the derived class.
8075 ASTContext &Context = SemaRef.Context;
8076 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8077 Context.getCanonicalType(Context.getRecordType(Base)));
8078 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8079 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8080 }
8081
8082 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8083 // C++11 [class.inhctor]p3:
8084 // [F]or each constructor template in the candidate set of inherited
8085 // constructors, a constructor template is implicitly declared
8086 if (Ctor->getDescribedFunctionTemplate())
8087 return 0;
8088
8089 // For each non-template constructor in the candidate set of inherited
8090 // constructors other than a constructor having no parameters or a
8091 // copy/move constructor having a single parameter, a constructor is
8092 // implicitly declared [...]
8093 if (Ctor->getNumParams() == 0)
8094 return 1;
8095 if (Ctor->isCopyOrMoveConstructor())
8096 return 2;
8097
8098 // Per discussion on core reflector, never inherit a constructor which
8099 // would become a default, copy, or move constructor of Derived either.
8100 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8101 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8102 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8103 }
8104
8105 /// Declare a single inheriting constructor, inheriting the specified
8106 /// constructor, with the given type.
8107 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8108 QualType DerivedType) {
8109 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8110
8111 // C++11 [class.inhctor]p3:
8112 // ... a constructor is implicitly declared with the same constructor
8113 // characteristics unless there is a user-declared constructor with
8114 // the same signature in the class where the using-declaration appears
8115 if (Entry.DeclaredInDerived)
8116 return;
8117
8118 // C++11 [class.inhctor]p7:
8119 // If two using-declarations declare inheriting constructors with the
8120 // same signature, the program is ill-formed
8121 if (Entry.DerivedCtor) {
8122 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8123 // Only diagnose this once per constructor.
8124 if (Entry.DerivedCtor->isInvalidDecl())
8125 return;
8126 Entry.DerivedCtor->setInvalidDecl();
8127
8128 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8129 SemaRef.Diag(BaseCtor->getLocation(),
8130 diag::note_using_decl_constructor_conflict_current_ctor);
8131 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8132 diag::note_using_decl_constructor_conflict_previous_ctor);
8133 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8134 diag::note_using_decl_constructor_conflict_previous_using);
8135 } else {
8136 // Core issue (no number): if the same inheriting constructor is
8137 // produced by multiple base class constructors from the same base
8138 // class, the inheriting constructor is defined as deleted.
8139 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8140 }
8141
8142 return;
8143 }
8144
8145 ASTContext &Context = SemaRef.Context;
8146 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8147 Context.getCanonicalType(Context.getRecordType(Derived)));
8148 DeclarationNameInfo NameInfo(Name, UsingLoc);
8149
8150 TemplateParameterList *TemplateParams = 0;
8151 if (const FunctionTemplateDecl *FTD =
8152 BaseCtor->getDescribedFunctionTemplate()) {
8153 TemplateParams = FTD->getTemplateParameters();
8154 // We're reusing template parameters from a different DeclContext. This
8155 // is questionable at best, but works out because the template depth in
8156 // both places is guaranteed to be 0.
8157 // FIXME: Rebuild the template parameters in the new context, and
8158 // transform the function type to refer to them.
8159 }
8160
8161 // Build type source info pointing at the using-declaration. This is
8162 // required by template instantiation.
8163 TypeSourceInfo *TInfo =
8164 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8165 FunctionProtoTypeLoc ProtoLoc =
8166 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8167
8168 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8169 Context, Derived, UsingLoc, NameInfo, DerivedType,
8170 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8171 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8172
8173 // Build an unevaluated exception specification for this constructor.
8174 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8175 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8176 EPI.ExceptionSpecType = EST_Unevaluated;
8177 EPI.ExceptionSpecDecl = DerivedCtor;
8178 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8179 FPT->getArgTypes(), EPI));
8180
8181 // Build the parameter declarations.
8182 SmallVector<ParmVarDecl *, 16> ParamDecls;
8183 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8184 TypeSourceInfo *TInfo =
8185 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8186 ParmVarDecl *PD = ParmVarDecl::Create(
8187 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8188 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8189 PD->setScopeInfo(0, I);
8190 PD->setImplicit();
8191 ParamDecls.push_back(PD);
8192 ProtoLoc.setArg(I, PD);
8193 }
8194
8195 // Set up the new constructor.
8196 DerivedCtor->setAccess(BaseCtor->getAccess());
8197 DerivedCtor->setParams(ParamDecls);
8198 DerivedCtor->setInheritedConstructor(BaseCtor);
8199 if (BaseCtor->isDeleted())
8200 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8201
8202 // If this is a constructor template, build the template declaration.
8203 if (TemplateParams) {
8204 FunctionTemplateDecl *DerivedTemplate =
8205 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8206 TemplateParams, DerivedCtor);
8207 DerivedTemplate->setAccess(BaseCtor->getAccess());
8208 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8209 Derived->addDecl(DerivedTemplate);
8210 } else {
8211 Derived->addDecl(DerivedCtor);
8212 }
8213
8214 Entry.BaseCtor = BaseCtor;
8215 Entry.DerivedCtor = DerivedCtor;
8216 }
8217
8218 Sema &SemaRef;
8219 CXXRecordDecl *Derived;
8220 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8221 MapType Map;
8222};
8223}
8224
8225void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8226 // Defer declaring the inheriting constructors until the class is
8227 // instantiated.
8228 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008229 return;
8230
Richard Smith4841ca52013-04-10 05:48:59 +00008231 // Find base classes from which we might inherit constructors.
8232 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8233 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8234 BaseE = ClassDecl->bases_end();
8235 BaseIt != BaseE; ++BaseIt)
8236 if (BaseIt->getInheritConstructors())
8237 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008238
Richard Smith4841ca52013-04-10 05:48:59 +00008239 // Go no further if we're not inheriting any constructors.
8240 if (InheritedBases.empty())
8241 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008242
Richard Smith4841ca52013-04-10 05:48:59 +00008243 // Declare the inherited constructors.
8244 InheritingConstructorInfo ICI(*this, ClassDecl);
8245 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8246 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008247}
8248
Richard Smith07b0fdc2013-03-18 21:12:30 +00008249void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8250 CXXConstructorDecl *Constructor) {
8251 CXXRecordDecl *ClassDecl = Constructor->getParent();
8252 assert(Constructor->getInheritedConstructor() &&
8253 !Constructor->doesThisDeclarationHaveABody() &&
8254 !Constructor->isDeleted());
8255
8256 SynthesizedFunctionScope Scope(*this, Constructor);
8257 DiagnosticErrorTrap Trap(Diags);
8258 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8259 Trap.hasErrorOccurred()) {
8260 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8261 << Context.getTagDeclType(ClassDecl);
8262 Constructor->setInvalidDecl();
8263 return;
8264 }
8265
8266 SourceLocation Loc = Constructor->getLocation();
8267 Constructor->setBody(new (Context) CompoundStmt(Loc));
8268
8269 Constructor->setUsed();
8270 MarkVTableUsed(CurrentLocation, ClassDecl);
8271
8272 if (ASTMutationListener *L = getASTMutationListener()) {
8273 L->CompletedImplicitDefinition(Constructor);
8274 }
8275}
8276
8277
Sean Huntcb45a0f2011-05-12 22:46:25 +00008278Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008279Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8280 CXXRecordDecl *ClassDecl = MD->getParent();
8281
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008282 // C++ [except.spec]p14:
8283 // An implicitly declared special member function (Clause 12) shall have
8284 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008285 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008286 if (ClassDecl->isInvalidDecl())
8287 return ExceptSpec;
8288
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008289 // Direct base-class destructors.
8290 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8291 BEnd = ClassDecl->bases_end();
8292 B != BEnd; ++B) {
8293 if (B->isVirtual()) // Handled below.
8294 continue;
8295
8296 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008297 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008298 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008299 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008300
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008301 // Virtual base-class destructors.
8302 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8303 BEnd = ClassDecl->vbases_end();
8304 B != BEnd; ++B) {
8305 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008306 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008307 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008308 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008309
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008310 // Field destructors.
8311 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8312 FEnd = ClassDecl->field_end();
8313 F != FEnd; ++F) {
8314 if (const RecordType *RecordTy
8315 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008316 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008317 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008318 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008319
Sean Huntcb45a0f2011-05-12 22:46:25 +00008320 return ExceptSpec;
8321}
8322
8323CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8324 // C++ [class.dtor]p2:
8325 // If a class has no user-declared destructor, a destructor is
8326 // declared implicitly. An implicitly-declared destructor is an
8327 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008328 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008329
Richard Smithafb49182012-11-29 01:34:07 +00008330 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8331 if (DSM.isAlreadyBeingDeclared())
8332 return 0;
8333
Douglas Gregor4923aa22010-07-02 20:37:36 +00008334 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008335 CanQualType ClassType
8336 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008337 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008338 DeclarationName Name
8339 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008340 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008341 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008342 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8343 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008344 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008345 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008346 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008347 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008348
8349 // Build an exception specification pointing back at this destructor.
8350 FunctionProtoType::ExtProtoInfo EPI;
8351 EPI.ExceptionSpecType = EST_Unevaluated;
8352 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008353 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008354
Richard Smithbc2a35d2012-12-08 08:32:28 +00008355 AddOverriddenMethods(ClassDecl, Destructor);
8356
8357 // We don't need to use SpecialMemberIsTrivial here; triviality for
8358 // destructors is easy to compute.
8359 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8360
8361 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008362 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008363
Douglas Gregor4923aa22010-07-02 20:37:36 +00008364 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008365 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008366
Douglas Gregor4923aa22010-07-02 20:37:36 +00008367 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008368 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008369 PushOnScopeChains(Destructor, S, false);
8370 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008371
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008372 return Destructor;
8373}
8374
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008375void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008376 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008377 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008378 !Destructor->doesThisDeclarationHaveABody() &&
8379 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008380 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008381 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008382 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008383
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008384 if (Destructor->isInvalidDecl())
8385 return;
8386
Eli Friedman9a14db32012-10-18 20:14:08 +00008387 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008388
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008389 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008390 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8391 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008392
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008393 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008394 Diag(CurrentLocation, diag::note_member_synthesized_at)
8395 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8396
8397 Destructor->setInvalidDecl();
8398 return;
8399 }
8400
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008401 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008402 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008403 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008404 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008405 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008406
8407 if (ASTMutationListener *L = getASTMutationListener()) {
8408 L->CompletedImplicitDefinition(Destructor);
8409 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008410}
8411
Richard Smitha4156b82012-04-21 18:42:51 +00008412/// \brief Perform any semantic analysis which needs to be delayed until all
8413/// pending class member declarations have been parsed.
8414void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008415 // If the context is an invalid C++ class, just suppress these checks.
8416 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8417 if (Record->isInvalidDecl()) {
8418 DelayedDestructorExceptionSpecChecks.clear();
8419 return;
8420 }
8421 }
8422
Richard Smitha4156b82012-04-21 18:42:51 +00008423 // Perform any deferred checking of exception specifications for virtual
8424 // destructors.
8425 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8426 i != e; ++i) {
8427 const CXXDestructorDecl *Dtor =
8428 DelayedDestructorExceptionSpecChecks[i].first;
8429 assert(!Dtor->getParent()->isDependentType() &&
8430 "Should not ever add destructors of templates into the list.");
8431 CheckOverridingFunctionExceptionSpec(Dtor,
8432 DelayedDestructorExceptionSpecChecks[i].second);
8433 }
8434 DelayedDestructorExceptionSpecChecks.clear();
8435}
8436
Richard Smithb9d0b762012-07-27 04:22:15 +00008437void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8438 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008439 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008440 "adjusting dtor exception specs was introduced in c++11");
8441
Sebastian Redl0ee33912011-05-19 05:13:44 +00008442 // C++11 [class.dtor]p3:
8443 // A declaration of a destructor that does not have an exception-
8444 // specification is implicitly considered to have the same exception-
8445 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008446 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008447 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008448 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008449 return;
8450
Chandler Carruth3f224b22011-09-20 04:55:26 +00008451 // Replace the destructor's type, building off the existing one. Fortunately,
8452 // the only thing of interest in the destructor type is its extended info.
8453 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008454 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8455 EPI.ExceptionSpecType = EST_Unevaluated;
8456 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008457 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008458
Sebastian Redl0ee33912011-05-19 05:13:44 +00008459 // FIXME: If the destructor has a body that could throw, and the newly created
8460 // spec doesn't allow exceptions, we should emit a warning, because this
8461 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008462 // However, we don't have a body or an exception specification yet, so it
8463 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008464}
8465
Richard Smith8c889532012-11-14 00:50:40 +00008466/// When generating a defaulted copy or move assignment operator, if a field
8467/// should be copied with __builtin_memcpy rather than via explicit assignments,
8468/// do so. This optimization only applies for arrays of scalars, and for arrays
8469/// of class type where the selected copy/move-assignment operator is trivial.
8470static StmtResult
8471buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8472 Expr *To, Expr *From) {
8473 // Compute the size of the memory buffer to be copied.
8474 QualType SizeType = S.Context.getSizeType();
8475 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8476 S.Context.getTypeSizeInChars(T).getQuantity());
8477
8478 // Take the address of the field references for "from" and "to". We
8479 // directly construct UnaryOperators here because semantic analysis
8480 // does not permit us to take the address of an xvalue.
8481 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8482 S.Context.getPointerType(From->getType()),
8483 VK_RValue, OK_Ordinary, Loc);
8484 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8485 S.Context.getPointerType(To->getType()),
8486 VK_RValue, OK_Ordinary, Loc);
8487
8488 const Type *E = T->getBaseElementTypeUnsafe();
8489 bool NeedsCollectableMemCpy =
8490 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8491
8492 // Create a reference to the __builtin_objc_memmove_collectable function
8493 StringRef MemCpyName = NeedsCollectableMemCpy ?
8494 "__builtin_objc_memmove_collectable" :
8495 "__builtin_memcpy";
8496 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8497 Sema::LookupOrdinaryName);
8498 S.LookupName(R, S.TUScope, true);
8499
8500 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8501 if (!MemCpy)
8502 // Something went horribly wrong earlier, and we will have complained
8503 // about it.
8504 return StmtError();
8505
8506 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8507 VK_RValue, Loc, 0);
8508 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8509
8510 Expr *CallArgs[] = {
8511 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8512 };
8513 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8514 Loc, CallArgs, Loc);
8515
8516 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8517 return S.Owned(Call.takeAs<Stmt>());
8518}
8519
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008520/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008521/// \c To.
8522///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008523/// This routine is used to copy/move the members of a class with an
8524/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008525/// copied are arrays, this routine builds for loops to copy them.
8526///
8527/// \param S The Sema object used for type-checking.
8528///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008529/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008530///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008531/// \param T The type of the expressions being copied/moved. Both expressions
8532/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008533///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008534/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008535///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008536/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008537///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008538/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008539/// Otherwise, it's a non-static member subobject.
8540///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008541/// \param Copying Whether we're copying or moving.
8542///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008543/// \param Depth Internal parameter recording the depth of the recursion.
8544///
Richard Smith8c889532012-11-14 00:50:40 +00008545/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8546/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008547static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008548buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8549 Expr *To, Expr *From,
8550 bool CopyingBaseSubobject, bool Copying,
8551 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008552 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008553 // Each subobject is assigned in the manner appropriate to its type:
8554 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008555 // - if the subobject is of class type, as if by a call to operator= with
8556 // the subobject as the object expression and the corresponding
8557 // subobject of x as a single function argument (as if by explicit
8558 // qualification; that is, ignoring any possible virtual overriding
8559 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008560 //
8561 // C++03 [class.copy]p13:
8562 // - if the subobject is of class type, the copy assignment operator for
8563 // the class is used (as if by explicit qualification; that is,
8564 // ignoring any possible virtual overriding functions in more derived
8565 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008566 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8567 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008568
Douglas Gregor06a9f362010-05-01 20:49:11 +00008569 // Look for operator=.
8570 DeclarationName Name
8571 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8572 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8573 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008574
Richard Smith044c8aa2012-11-13 00:54:12 +00008575 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8576 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008577 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008578 LookupResult::Filter F = OpLookup.makeFilter();
8579 while (F.hasNext()) {
8580 NamedDecl *D = F.next();
8581 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8582 if (Method->isCopyAssignmentOperator() ||
8583 (!Copying && Method->isMoveAssignmentOperator()))
8584 continue;
8585
8586 F.erase();
8587 }
8588 F.done();
John McCallb0207482010-03-16 06:11:48 +00008589 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008590
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008591 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008592 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008593 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008594 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008595 // ambiguities), we need to cast "this" to that subobject type; to
8596 // ensure that we don't go through the virtual call mechanism, we need
8597 // to qualify the operator= name with the base class (see below). However,
8598 // this means that if the base class has a protected copy assignment
8599 // operator, the protected member access check will fail. So, we
8600 // rewrite "protected" access to "public" access in this case, since we
8601 // know by construction that we're calling from a derived class.
8602 if (CopyingBaseSubobject) {
8603 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8604 L != LEnd; ++L) {
8605 if (L.getAccess() == AS_protected)
8606 L.setAccess(AS_public);
8607 }
8608 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008609
Douglas Gregor06a9f362010-05-01 20:49:11 +00008610 // Create the nested-name-specifier that will be used to qualify the
8611 // reference to operator=; this is required to suppress the virtual
8612 // call mechanism.
8613 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008614 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008615 SS.MakeTrivial(S.Context,
8616 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008617 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008618 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008619
Douglas Gregor06a9f362010-05-01 20:49:11 +00008620 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008621 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008622 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008623 /*TemplateKWLoc=*/SourceLocation(),
8624 /*FirstQualifierInScope=*/0,
8625 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008626 /*TemplateArgs=*/0,
8627 /*SuppressQualifierCheck=*/true);
8628 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008629 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008630
Douglas Gregor06a9f362010-05-01 20:49:11 +00008631 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008632
Richard Smith044c8aa2012-11-13 00:54:12 +00008633 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008634 OpEqualRef.takeAs<Expr>(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00008635 Loc, From, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008636 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008637 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008638
Richard Smith8c889532012-11-14 00:50:40 +00008639 // If we built a call to a trivial 'operator=' while copying an array,
8640 // bail out. We'll replace the whole shebang with a memcpy.
8641 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8642 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8643 return StmtResult((Stmt*)0);
8644
Richard Smith044c8aa2012-11-13 00:54:12 +00008645 // Convert to an expression-statement, and clean up any produced
8646 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008647 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008648 }
John McCallb0207482010-03-16 06:11:48 +00008649
Richard Smith044c8aa2012-11-13 00:54:12 +00008650 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008651 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008652 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008653 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008654 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008655 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008656 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008657 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008658 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008659
8660 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008661 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008662
Douglas Gregor06a9f362010-05-01 20:49:11 +00008663 // Construct a loop over the array bounds, e.g.,
8664 //
8665 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8666 //
8667 // that will copy each of the array elements.
8668 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008669
Douglas Gregor06a9f362010-05-01 20:49:11 +00008670 // Create the iteration variable.
8671 IdentifierInfo *IterationVarName = 0;
8672 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008673 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008674 llvm::raw_svector_ostream OS(Str);
8675 OS << "__i" << Depth;
8676 IterationVarName = &S.Context.Idents.get(OS.str());
8677 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008678 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008679 IterationVarName, SizeType,
8680 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008681 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008682
Douglas Gregor06a9f362010-05-01 20:49:11 +00008683 // Initialize the iteration variable to zero.
8684 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008685 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008686
8687 // Create a reference to the iteration variable; we'll use this several
8688 // times throughout.
8689 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008690 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008691 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008692 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8693 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8694
Douglas Gregor06a9f362010-05-01 20:49:11 +00008695 // Create the DeclStmt that holds the iteration variable.
8696 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008697
Douglas Gregor06a9f362010-05-01 20:49:11 +00008698 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008699 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008700 IterationVarRefRVal,
8701 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008702 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008703 IterationVarRefRVal,
8704 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008705 if (!Copying) // Cast to rvalue
8706 From = CastForMoving(S, From);
8707
8708 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008709 StmtResult Copy =
8710 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8711 To, From, CopyingBaseSubobject,
8712 Copying, Depth + 1);
8713 // Bail out if copying fails or if we determined that we should use memcpy.
8714 if (Copy.isInvalid() || !Copy.get())
8715 return Copy;
8716
8717 // Create the comparison against the array bound.
8718 llvm::APInt Upper
8719 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8720 Expr *Comparison
8721 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8722 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8723 BO_NE, S.Context.BoolTy,
8724 VK_RValue, OK_Ordinary, Loc, false);
8725
8726 // Create the pre-increment of the iteration variable.
8727 Expr *Increment
8728 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8729 VK_LValue, OK_Ordinary, Loc);
8730
Douglas Gregor06a9f362010-05-01 20:49:11 +00008731 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008732 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008733 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008734 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008735 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008736}
8737
Richard Smith8c889532012-11-14 00:50:40 +00008738static StmtResult
8739buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8740 Expr *To, Expr *From,
8741 bool CopyingBaseSubobject, bool Copying) {
8742 // Maybe we should use a memcpy?
8743 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8744 T.isTriviallyCopyableType(S.Context))
8745 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8746
8747 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8748 CopyingBaseSubobject,
8749 Copying, 0));
8750
8751 // If we ended up picking a trivial assignment operator for an array of a
8752 // non-trivially-copyable class type, just emit a memcpy.
8753 if (!Result.isInvalid() && !Result.get())
8754 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8755
8756 return Result;
8757}
8758
Richard Smithb9d0b762012-07-27 04:22:15 +00008759Sema::ImplicitExceptionSpecification
8760Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8761 CXXRecordDecl *ClassDecl = MD->getParent();
8762
8763 ImplicitExceptionSpecification ExceptSpec(*this);
8764 if (ClassDecl->isInvalidDecl())
8765 return ExceptSpec;
8766
8767 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8768 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8769 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8770
Douglas Gregorb87786f2010-07-01 17:48:08 +00008771 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008772 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008773 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008774
8775 // It is unspecified whether or not an implicit copy assignment operator
8776 // attempts to deduplicate calls to assignment operators of virtual bases are
8777 // made. As such, this exception specification is effectively unspecified.
8778 // Based on a similar decision made for constness in C++0x, we're erring on
8779 // the side of assuming such calls to be made regardless of whether they
8780 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008781 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8782 BaseEnd = ClassDecl->bases_end();
8783 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008784 if (Base->isVirtual())
8785 continue;
8786
Douglas Gregora376d102010-07-02 21:50:04 +00008787 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008788 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008789 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8790 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008791 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008792 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008793
8794 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8795 BaseEnd = ClassDecl->vbases_end();
8796 Base != BaseEnd; ++Base) {
8797 CXXRecordDecl *BaseClassDecl
8798 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8799 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8800 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008801 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008802 }
8803
Douglas Gregorb87786f2010-07-01 17:48:08 +00008804 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8805 FieldEnd = ClassDecl->field_end();
8806 Field != FieldEnd;
8807 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008808 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008809 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8810 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008811 LookupCopyingAssignment(FieldClassDecl,
8812 ArgQuals | FieldType.getCVRQualifiers(),
8813 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008814 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008815 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008816 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008817
Richard Smithb9d0b762012-07-27 04:22:15 +00008818 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008819}
8820
8821CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8822 // Note: The following rules are largely analoguous to the copy
8823 // constructor rules. Note that virtual bases are not taken into account
8824 // for determining the argument type of the operator. Note also that
8825 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008826 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008827
Richard Smithafb49182012-11-29 01:34:07 +00008828 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8829 if (DSM.isAlreadyBeingDeclared())
8830 return 0;
8831
Sean Hunt30de05c2011-05-14 05:23:20 +00008832 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8833 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008834 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8835 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008836 ArgType = ArgType.withConst();
8837 ArgType = Context.getLValueReferenceType(ArgType);
8838
Richard Smitha8942d72013-05-07 03:19:20 +00008839 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8840 CXXCopyAssignment,
8841 Const);
8842
Douglas Gregord3c35902010-07-01 16:36:15 +00008843 // An implicitly-declared copy assignment operator is an inline public
8844 // member of its class.
8845 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008846 SourceLocation ClassLoc = ClassDecl->getLocation();
8847 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00008848 CXXMethodDecl *CopyAssignment =
8849 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8850 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8851 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008852 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008853 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008854 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008855
8856 // Build an exception specification pointing back at this member.
8857 FunctionProtoType::ExtProtoInfo EPI;
8858 EPI.ExceptionSpecType = EST_Unevaluated;
8859 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008860 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008861
Douglas Gregord3c35902010-07-01 16:36:15 +00008862 // Add the parameter to the operator.
8863 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008864 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008865 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008866 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008867 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008868
Richard Smithbc2a35d2012-12-08 08:32:28 +00008869 AddOverriddenMethods(ClassDecl, CopyAssignment);
8870
8871 CopyAssignment->setTrivial(
8872 ClassDecl->needsOverloadResolutionForCopyAssignment()
8873 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8874 : ClassDecl->hasTrivialCopyAssignment());
8875
Richard Smitha8942d72013-05-07 03:19:20 +00008876 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00008877 // .... If the class definition does not explicitly declare a copy
8878 // assignment operator, there is no user-declared move constructor, and
8879 // there is no user-declared move assignment operator, a copy assignment
8880 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008881 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008882 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008883
Richard Smithbc2a35d2012-12-08 08:32:28 +00008884 // Note that we have added this copy-assignment operator.
8885 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8886
8887 if (Scope *S = getScopeForContext(ClassDecl))
8888 PushOnScopeChains(CopyAssignment, S, false);
8889 ClassDecl->addDecl(CopyAssignment);
8890
Douglas Gregord3c35902010-07-01 16:36:15 +00008891 return CopyAssignment;
8892}
8893
Richard Smith36155c12013-06-13 03:23:42 +00008894/// Diagnose an implicit copy operation for a class which is odr-used, but
8895/// which is deprecated because the class has a user-declared copy constructor,
8896/// copy assignment operator, or destructor.
8897static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
8898 SourceLocation UseLoc) {
8899 assert(CopyOp->isImplicit());
8900
8901 CXXRecordDecl *RD = CopyOp->getParent();
8902 CXXMethodDecl *UserDeclaredOperation = 0;
8903
8904 // In Microsoft mode, assignment operations don't affect constructors and
8905 // vice versa.
8906 if (RD->hasUserDeclaredDestructor()) {
8907 UserDeclaredOperation = RD->getDestructor();
8908 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
8909 RD->hasUserDeclaredCopyConstructor() &&
8910 !S.getLangOpts().MicrosoftMode) {
8911 // Find any user-declared copy constructor.
8912 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
8913 E = RD->ctor_end(); I != E; ++I) {
8914 if (I->isCopyConstructor()) {
8915 UserDeclaredOperation = *I;
8916 break;
8917 }
8918 }
8919 assert(UserDeclaredOperation);
8920 } else if (isa<CXXConstructorDecl>(CopyOp) &&
8921 RD->hasUserDeclaredCopyAssignment() &&
8922 !S.getLangOpts().MicrosoftMode) {
8923 // Find any user-declared move assignment operator.
8924 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
8925 E = RD->method_end(); I != E; ++I) {
8926 if (I->isCopyAssignmentOperator()) {
8927 UserDeclaredOperation = *I;
8928 break;
8929 }
8930 }
8931 assert(UserDeclaredOperation);
8932 }
8933
8934 if (UserDeclaredOperation) {
8935 S.Diag(UserDeclaredOperation->getLocation(),
8936 diag::warn_deprecated_copy_operation)
8937 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
8938 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
8939 S.Diag(UseLoc, diag::note_member_synthesized_at)
8940 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
8941 : Sema::CXXCopyAssignment)
8942 << RD;
8943 }
8944}
8945
Douglas Gregor06a9f362010-05-01 20:49:11 +00008946void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8947 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008948 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008949 CopyAssignOperator->isOverloadedOperator() &&
8950 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008951 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8952 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008953 "DefineImplicitCopyAssignment called for wrong function");
8954
8955 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8956
8957 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8958 CopyAssignOperator->setInvalidDecl();
8959 return;
8960 }
Richard Smith36155c12013-06-13 03:23:42 +00008961
8962 // C++11 [class.copy]p18:
8963 // The [definition of an implicitly declared copy assignment operator] is
8964 // deprecated if the class has a user-declared copy constructor or a
8965 // user-declared destructor.
8966 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
8967 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
8968
Douglas Gregor06a9f362010-05-01 20:49:11 +00008969 CopyAssignOperator->setUsed();
8970
Eli Friedman9a14db32012-10-18 20:14:08 +00008971 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008972 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008973
8974 // C++0x [class.copy]p30:
8975 // The implicitly-defined or explicitly-defaulted copy assignment operator
8976 // for a non-union class X performs memberwise copy assignment of its
8977 // subobjects. The direct base classes of X are assigned first, in the
8978 // order of their declaration in the base-specifier-list, and then the
8979 // immediate non-static data members of X are assigned, in the order in
8980 // which they were declared in the class definition.
8981
8982 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008983 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008984
8985 // The parameter for the "other" object, which we are copying from.
8986 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8987 Qualifiers OtherQuals = Other->getType().getQualifiers();
8988 QualType OtherRefType = Other->getType();
8989 if (const LValueReferenceType *OtherRef
8990 = OtherRefType->getAs<LValueReferenceType>()) {
8991 OtherRefType = OtherRef->getPointeeType();
8992 OtherQuals = OtherRefType.getQualifiers();
8993 }
8994
8995 // Our location for everything implicitly-generated.
8996 SourceLocation Loc = CopyAssignOperator->getLocation();
8997
8998 // Construct a reference to the "other" object. We'll be using this
8999 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00009000 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00009001 assert(OtherRef && "Reference to parameter cannot fail!");
9002
9003 // Construct the "this" pointer. We'll be using this throughout the generated
9004 // ASTs.
9005 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9006 assert(This && "Reference to this cannot fail!");
9007
9008 // Assign base classes.
9009 bool Invalid = false;
9010 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9011 E = ClassDecl->bases_end(); Base != E; ++Base) {
9012 // Form the assignment:
9013 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9014 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009015 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009016 Invalid = true;
9017 continue;
9018 }
9019
John McCallf871d0c2010-08-07 06:22:56 +00009020 CXXCastPath BasePath;
9021 BasePath.push_back(Base);
9022
Douglas Gregor06a9f362010-05-01 20:49:11 +00009023 // Construct the "from" expression, which is an implicit cast to the
9024 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00009025 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00009026 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
9027 CK_UncheckedDerivedToBase,
9028 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00009029
9030 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00009031 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009032
9033 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00009034 To = ImpCastExprToType(To.take(),
9035 Context.getCVRQualifiedType(BaseType,
9036 CopyAssignOperator->getTypeQualifiers()),
9037 CK_UncheckedDerivedToBase,
9038 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009039
9040 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009041 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00009042 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009043 /*CopyingBaseSubobject=*/true,
9044 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009045 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009046 Diag(CurrentLocation, diag::note_member_synthesized_at)
9047 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9048 CopyAssignOperator->setInvalidDecl();
9049 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009050 }
9051
9052 // Success! Record the copy.
9053 Statements.push_back(Copy.takeAs<Expr>());
9054 }
9055
Douglas Gregor06a9f362010-05-01 20:49:11 +00009056 // Assign non-static members.
9057 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9058 FieldEnd = ClassDecl->field_end();
9059 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009060 if (Field->isUnnamedBitfield())
9061 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009062
9063 if (Field->isInvalidDecl()) {
9064 Invalid = true;
9065 continue;
9066 }
9067
Douglas Gregor06a9f362010-05-01 20:49:11 +00009068 // Check for members of reference type; we can't copy those.
9069 if (Field->getType()->isReferenceType()) {
9070 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9071 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9072 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009073 Diag(CurrentLocation, diag::note_member_synthesized_at)
9074 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009075 Invalid = true;
9076 continue;
9077 }
9078
9079 // Check for members of const-qualified, non-class type.
9080 QualType BaseType = Context.getBaseElementType(Field->getType());
9081 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9082 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9083 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9084 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009085 Diag(CurrentLocation, diag::note_member_synthesized_at)
9086 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009087 Invalid = true;
9088 continue;
9089 }
John McCallb77115d2011-06-17 00:18:42 +00009090
9091 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009092 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9093 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009094
9095 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009096 if (FieldType->isIncompleteArrayType()) {
9097 assert(ClassDecl->hasFlexibleArrayMember() &&
9098 "Incomplete array type is not valid");
9099 continue;
9100 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009101
9102 // Build references to the field in the object we're copying from and to.
9103 CXXScopeSpec SS; // Intentionally empty
9104 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9105 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009106 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009107 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00009108 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00009109 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009110 SS, SourceLocation(), 0,
9111 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009112 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00009113 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009114 SS, SourceLocation(), 0,
9115 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009116 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9117 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00009118
Douglas Gregor06a9f362010-05-01 20:49:11 +00009119 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009120 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009121 To.get(), From.get(),
9122 /*CopyingBaseSubobject=*/false,
9123 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009124 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009125 Diag(CurrentLocation, diag::note_member_synthesized_at)
9126 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9127 CopyAssignOperator->setInvalidDecl();
9128 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009129 }
9130
9131 // Success! Record the copy.
9132 Statements.push_back(Copy.takeAs<Stmt>());
9133 }
9134
9135 if (!Invalid) {
9136 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00009137 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009138
John McCall60d7b3a2010-08-24 06:29:42 +00009139 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009140 if (Return.isInvalid())
9141 Invalid = true;
9142 else {
9143 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009144
9145 if (Trap.hasErrorOccurred()) {
9146 Diag(CurrentLocation, diag::note_member_synthesized_at)
9147 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9148 Invalid = true;
9149 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009150 }
9151 }
9152
9153 if (Invalid) {
9154 CopyAssignOperator->setInvalidDecl();
9155 return;
9156 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009157
9158 StmtResult Body;
9159 {
9160 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009161 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009162 /*isStmtExpr=*/false);
9163 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9164 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009165 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009166
9167 if (ASTMutationListener *L = getASTMutationListener()) {
9168 L->CompletedImplicitDefinition(CopyAssignOperator);
9169 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009170}
9171
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009172Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009173Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9174 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009175
Richard Smithb9d0b762012-07-27 04:22:15 +00009176 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009177 if (ClassDecl->isInvalidDecl())
9178 return ExceptSpec;
9179
9180 // C++0x [except.spec]p14:
9181 // An implicitly declared special member function (Clause 12) shall have an
9182 // exception-specification. [...]
9183
9184 // It is unspecified whether or not an implicit move assignment operator
9185 // attempts to deduplicate calls to assignment operators of virtual bases are
9186 // made. As such, this exception specification is effectively unspecified.
9187 // Based on a similar decision made for constness in C++0x, we're erring on
9188 // the side of assuming such calls to be made regardless of whether they
9189 // actually happen.
9190 // Note that a move constructor is not implicitly declared when there are
9191 // virtual bases, but it can still be user-declared and explicitly defaulted.
9192 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9193 BaseEnd = ClassDecl->bases_end();
9194 Base != BaseEnd; ++Base) {
9195 if (Base->isVirtual())
9196 continue;
9197
9198 CXXRecordDecl *BaseClassDecl
9199 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9200 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009201 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009202 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009203 }
9204
9205 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9206 BaseEnd = ClassDecl->vbases_end();
9207 Base != BaseEnd; ++Base) {
9208 CXXRecordDecl *BaseClassDecl
9209 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9210 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009211 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009212 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009213 }
9214
9215 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9216 FieldEnd = ClassDecl->field_end();
9217 Field != FieldEnd;
9218 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009219 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009220 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009221 if (CXXMethodDecl *MoveAssign =
9222 LookupMovingAssignment(FieldClassDecl,
9223 FieldType.getCVRQualifiers(),
9224 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009225 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009226 }
9227 }
9228
9229 return ExceptSpec;
9230}
9231
Richard Smith1c931be2012-04-02 18:40:40 +00009232/// Determine whether the class type has any direct or indirect virtual base
9233/// classes which have a non-trivial move assignment operator.
9234static bool
9235hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9236 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9237 BaseEnd = ClassDecl->vbases_end();
9238 Base != BaseEnd; ++Base) {
9239 CXXRecordDecl *BaseClass =
9240 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9241
9242 // Try to declare the move assignment. If it would be deleted, then the
9243 // class does not have a non-trivial move assignment.
9244 if (BaseClass->needsImplicitMoveAssignment())
9245 S.DeclareImplicitMoveAssignment(BaseClass);
9246
Richard Smith426391c2012-11-16 00:53:38 +00009247 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009248 return true;
9249 }
9250
9251 return false;
9252}
9253
9254/// Determine whether the given type either has a move constructor or is
9255/// trivially copyable.
9256static bool
9257hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9258 Type = S.Context.getBaseElementType(Type);
9259
9260 // FIXME: Technically, non-trivially-copyable non-class types, such as
9261 // reference types, are supposed to return false here, but that appears
9262 // to be a standard defect.
9263 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009264 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009265 return true;
9266
9267 if (Type.isTriviallyCopyableType(S.Context))
9268 return true;
9269
9270 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009271 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9272 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009273 if (ClassDecl->needsImplicitMoveConstructor())
9274 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009275 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009276 }
9277
Richard Smithe5411b72012-12-01 02:35:44 +00009278 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9279 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009280 if (ClassDecl->needsImplicitMoveAssignment())
9281 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009282 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009283}
9284
9285/// Determine whether all non-static data members and direct or virtual bases
9286/// of class \p ClassDecl have either a move operation, or are trivially
9287/// copyable.
9288static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9289 bool IsConstructor) {
9290 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9291 BaseEnd = ClassDecl->bases_end();
9292 Base != BaseEnd; ++Base) {
9293 if (Base->isVirtual())
9294 continue;
9295
9296 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9297 return false;
9298 }
9299
9300 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9301 BaseEnd = ClassDecl->vbases_end();
9302 Base != BaseEnd; ++Base) {
9303 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9304 return false;
9305 }
9306
9307 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9308 FieldEnd = ClassDecl->field_end();
9309 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009310 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009311 return false;
9312 }
9313
9314 return true;
9315}
9316
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009317CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009318 // C++11 [class.copy]p20:
9319 // If the definition of a class X does not explicitly declare a move
9320 // assignment operator, one will be implicitly declared as defaulted
9321 // if and only if:
9322 //
9323 // - [first 4 bullets]
9324 assert(ClassDecl->needsImplicitMoveAssignment());
9325
Richard Smithafb49182012-11-29 01:34:07 +00009326 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9327 if (DSM.isAlreadyBeingDeclared())
9328 return 0;
9329
Richard Smith1c931be2012-04-02 18:40:40 +00009330 // [Checked after we build the declaration]
9331 // - the move assignment operator would not be implicitly defined as
9332 // deleted,
9333
9334 // [DR1402]:
9335 // - X has no direct or indirect virtual base class with a non-trivial
9336 // move assignment operator, and
9337 // - each of X's non-static data members and direct or virtual base classes
9338 // has a type that either has a move assignment operator or is trivially
9339 // copyable.
9340 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9341 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9342 ClassDecl->setFailedImplicitMoveAssignment();
9343 return 0;
9344 }
9345
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009346 // Note: The following rules are largely analoguous to the move
9347 // constructor rules.
9348
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009349 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9350 QualType RetType = Context.getLValueReferenceType(ArgType);
9351 ArgType = Context.getRValueReferenceType(ArgType);
9352
Richard Smitha8942d72013-05-07 03:19:20 +00009353 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9354 CXXMoveAssignment,
9355 false);
9356
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009357 // An implicitly-declared move assignment operator is an inline public
9358 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009359 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9360 SourceLocation ClassLoc = ClassDecl->getLocation();
9361 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009362 CXXMethodDecl *MoveAssignment =
9363 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9364 /*TInfo=*/0, /*StorageClass=*/SC_None,
9365 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009366 MoveAssignment->setAccess(AS_public);
9367 MoveAssignment->setDefaulted();
9368 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009369
Richard Smithb9d0b762012-07-27 04:22:15 +00009370 // Build an exception specification pointing back at this member.
9371 FunctionProtoType::ExtProtoInfo EPI;
9372 EPI.ExceptionSpecType = EST_Unevaluated;
9373 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009374 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009375
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009376 // Add the parameter to the operator.
9377 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9378 ClassLoc, ClassLoc, /*Id=*/0,
9379 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009380 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009381 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009382
Richard Smithbc2a35d2012-12-08 08:32:28 +00009383 AddOverriddenMethods(ClassDecl, MoveAssignment);
9384
9385 MoveAssignment->setTrivial(
9386 ClassDecl->needsOverloadResolutionForMoveAssignment()
9387 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9388 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009389
9390 // C++0x [class.copy]p9:
9391 // If the definition of a class X does not explicitly declare a move
9392 // assignment operator, one will be implicitly declared as defaulted if and
9393 // only if:
9394 // [...]
9395 // - the move assignment operator would not be implicitly defined as
9396 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009397 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009398 // Cache this result so that we don't try to generate this over and over
9399 // on every lookup, leaking memory and wasting time.
9400 ClassDecl->setFailedImplicitMoveAssignment();
9401 return 0;
9402 }
9403
Richard Smithbc2a35d2012-12-08 08:32:28 +00009404 // Note that we have added this copy-assignment operator.
9405 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9406
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009407 if (Scope *S = getScopeForContext(ClassDecl))
9408 PushOnScopeChains(MoveAssignment, S, false);
9409 ClassDecl->addDecl(MoveAssignment);
9410
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009411 return MoveAssignment;
9412}
9413
9414void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9415 CXXMethodDecl *MoveAssignOperator) {
9416 assert((MoveAssignOperator->isDefaulted() &&
9417 MoveAssignOperator->isOverloadedOperator() &&
9418 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009419 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9420 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009421 "DefineImplicitMoveAssignment called for wrong function");
9422
9423 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9424
9425 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9426 MoveAssignOperator->setInvalidDecl();
9427 return;
9428 }
9429
9430 MoveAssignOperator->setUsed();
9431
Eli Friedman9a14db32012-10-18 20:14:08 +00009432 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009433 DiagnosticErrorTrap Trap(Diags);
9434
9435 // C++0x [class.copy]p28:
9436 // The implicitly-defined or move assignment operator for a non-union class
9437 // X performs memberwise move assignment of its subobjects. The direct base
9438 // classes of X are assigned first, in the order of their declaration in the
9439 // base-specifier-list, and then the immediate non-static data members of X
9440 // are assigned, in the order in which they were declared in the class
9441 // definition.
9442
9443 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009444 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009445
9446 // The parameter for the "other" object, which we are move from.
9447 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9448 QualType OtherRefType = Other->getType()->
9449 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009450 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009451 "Bad argument type of defaulted move assignment");
9452
9453 // Our location for everything implicitly-generated.
9454 SourceLocation Loc = MoveAssignOperator->getLocation();
9455
9456 // Construct a reference to the "other" object. We'll be using this
9457 // throughout the generated ASTs.
9458 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9459 assert(OtherRef && "Reference to parameter cannot fail!");
9460 // Cast to rvalue.
9461 OtherRef = CastForMoving(*this, OtherRef);
9462
9463 // Construct the "this" pointer. We'll be using this throughout the generated
9464 // ASTs.
9465 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9466 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009467
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009468 // Assign base classes.
9469 bool Invalid = false;
9470 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9471 E = ClassDecl->bases_end(); Base != E; ++Base) {
9472 // Form the assignment:
9473 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9474 QualType BaseType = Base->getType().getUnqualifiedType();
9475 if (!BaseType->isRecordType()) {
9476 Invalid = true;
9477 continue;
9478 }
9479
9480 CXXCastPath BasePath;
9481 BasePath.push_back(Base);
9482
9483 // Construct the "from" expression, which is an implicit cast to the
9484 // appropriately-qualified base type.
9485 Expr *From = OtherRef;
9486 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009487 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009488
9489 // Dereference "this".
9490 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9491
9492 // Implicitly cast "this" to the appropriately-qualified base type.
9493 To = ImpCastExprToType(To.take(),
9494 Context.getCVRQualifiedType(BaseType,
9495 MoveAssignOperator->getTypeQualifiers()),
9496 CK_UncheckedDerivedToBase,
9497 VK_LValue, &BasePath);
9498
9499 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009500 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009501 To.get(), From,
9502 /*CopyingBaseSubobject=*/true,
9503 /*Copying=*/false);
9504 if (Move.isInvalid()) {
9505 Diag(CurrentLocation, diag::note_member_synthesized_at)
9506 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9507 MoveAssignOperator->setInvalidDecl();
9508 return;
9509 }
9510
9511 // Success! Record the move.
9512 Statements.push_back(Move.takeAs<Expr>());
9513 }
9514
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009515 // Assign non-static members.
9516 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9517 FieldEnd = ClassDecl->field_end();
9518 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009519 if (Field->isUnnamedBitfield())
9520 continue;
9521
Eli Friedman8150da32013-06-07 01:48:56 +00009522 if (Field->isInvalidDecl()) {
9523 Invalid = true;
9524 continue;
9525 }
9526
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009527 // Check for members of reference type; we can't move those.
9528 if (Field->getType()->isReferenceType()) {
9529 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9530 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9531 Diag(Field->getLocation(), diag::note_declared_at);
9532 Diag(CurrentLocation, diag::note_member_synthesized_at)
9533 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9534 Invalid = true;
9535 continue;
9536 }
9537
9538 // Check for members of const-qualified, non-class type.
9539 QualType BaseType = Context.getBaseElementType(Field->getType());
9540 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9541 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9542 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9543 Diag(Field->getLocation(), diag::note_declared_at);
9544 Diag(CurrentLocation, diag::note_member_synthesized_at)
9545 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9546 Invalid = true;
9547 continue;
9548 }
9549
9550 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009551 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9552 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009553
9554 QualType FieldType = Field->getType().getNonReferenceType();
9555 if (FieldType->isIncompleteArrayType()) {
9556 assert(ClassDecl->hasFlexibleArrayMember() &&
9557 "Incomplete array type is not valid");
9558 continue;
9559 }
9560
9561 // Build references to the field in the object we're copying from and to.
9562 CXXScopeSpec SS; // Intentionally empty
9563 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9564 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009565 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009566 MemberLookup.resolveKind();
9567 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9568 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009569 SS, SourceLocation(), 0,
9570 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009571 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9572 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009573 SS, SourceLocation(), 0,
9574 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009575 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9576 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9577
9578 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9579 "Member reference with rvalue base must be rvalue except for reference "
9580 "members, which aren't allowed for move assignment.");
9581
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009582 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009583 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009584 To.get(), From.get(),
9585 /*CopyingBaseSubobject=*/false,
9586 /*Copying=*/false);
9587 if (Move.isInvalid()) {
9588 Diag(CurrentLocation, diag::note_member_synthesized_at)
9589 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9590 MoveAssignOperator->setInvalidDecl();
9591 return;
9592 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009593
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009594 // Success! Record the copy.
9595 Statements.push_back(Move.takeAs<Stmt>());
9596 }
9597
9598 if (!Invalid) {
9599 // Add a "return *this;"
9600 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9601
9602 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9603 if (Return.isInvalid())
9604 Invalid = true;
9605 else {
9606 Statements.push_back(Return.takeAs<Stmt>());
9607
9608 if (Trap.hasErrorOccurred()) {
9609 Diag(CurrentLocation, diag::note_member_synthesized_at)
9610 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9611 Invalid = true;
9612 }
9613 }
9614 }
9615
9616 if (Invalid) {
9617 MoveAssignOperator->setInvalidDecl();
9618 return;
9619 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009620
9621 StmtResult Body;
9622 {
9623 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009624 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009625 /*isStmtExpr=*/false);
9626 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9627 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009628 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9629
9630 if (ASTMutationListener *L = getASTMutationListener()) {
9631 L->CompletedImplicitDefinition(MoveAssignOperator);
9632 }
9633}
9634
Richard Smithb9d0b762012-07-27 04:22:15 +00009635Sema::ImplicitExceptionSpecification
9636Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9637 CXXRecordDecl *ClassDecl = MD->getParent();
9638
9639 ImplicitExceptionSpecification ExceptSpec(*this);
9640 if (ClassDecl->isInvalidDecl())
9641 return ExceptSpec;
9642
9643 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9644 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9645 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9646
Douglas Gregor0d405db2010-07-01 20:59:04 +00009647 // C++ [except.spec]p14:
9648 // An implicitly declared special member function (Clause 12) shall have an
9649 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009650 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9651 BaseEnd = ClassDecl->bases_end();
9652 Base != BaseEnd;
9653 ++Base) {
9654 // Virtual bases are handled below.
9655 if (Base->isVirtual())
9656 continue;
9657
Douglas Gregor22584312010-07-02 23:41:54 +00009658 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009659 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009660 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009661 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009662 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009663 }
9664 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9665 BaseEnd = ClassDecl->vbases_end();
9666 Base != BaseEnd;
9667 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009668 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009669 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009670 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009671 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009672 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009673 }
9674 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9675 FieldEnd = ClassDecl->field_end();
9676 Field != FieldEnd;
9677 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009678 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009679 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9680 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009681 LookupCopyingConstructor(FieldClassDecl,
9682 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009683 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009684 }
9685 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009686
Richard Smithb9d0b762012-07-27 04:22:15 +00009687 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009688}
9689
9690CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9691 CXXRecordDecl *ClassDecl) {
9692 // C++ [class.copy]p4:
9693 // If the class definition does not explicitly declare a copy
9694 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009695 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009696
Richard Smithafb49182012-11-29 01:34:07 +00009697 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9698 if (DSM.isAlreadyBeingDeclared())
9699 return 0;
9700
Sean Hunt49634cf2011-05-13 06:10:58 +00009701 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9702 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009703 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009704 if (Const)
9705 ArgType = ArgType.withConst();
9706 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009707
Richard Smith7756afa2012-06-10 05:43:50 +00009708 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9709 CXXCopyConstructor,
9710 Const);
9711
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009712 DeclarationName Name
9713 = Context.DeclarationNames.getCXXConstructorName(
9714 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009715 SourceLocation ClassLoc = ClassDecl->getLocation();
9716 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009717
9718 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009719 // member of its class.
9720 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009721 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009722 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009723 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009724 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009725 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009726
Richard Smithb9d0b762012-07-27 04:22:15 +00009727 // Build an exception specification pointing back at this member.
9728 FunctionProtoType::ExtProtoInfo EPI;
9729 EPI.ExceptionSpecType = EST_Unevaluated;
9730 EPI.ExceptionSpecDecl = CopyConstructor;
9731 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009732 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009733
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009734 // Add the parameter to the constructor.
9735 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009736 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009737 /*IdentifierInfo=*/0,
9738 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009739 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009740 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009741
Richard Smithbc2a35d2012-12-08 08:32:28 +00009742 CopyConstructor->setTrivial(
9743 ClassDecl->needsOverloadResolutionForCopyConstructor()
9744 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9745 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009746
Nico Weberafcc96a2012-01-23 03:19:29 +00009747 // C++11 [class.copy]p8:
9748 // ... If the class definition does not explicitly declare a copy
9749 // constructor, there is no user-declared move constructor, and there is no
9750 // user-declared move assignment operator, a copy constructor is implicitly
9751 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009752 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009753 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009754
Richard Smithbc2a35d2012-12-08 08:32:28 +00009755 // Note that we have declared this constructor.
9756 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9757
9758 if (Scope *S = getScopeForContext(ClassDecl))
9759 PushOnScopeChains(CopyConstructor, S, false);
9760 ClassDecl->addDecl(CopyConstructor);
9761
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009762 return CopyConstructor;
9763}
9764
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009765void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009766 CXXConstructorDecl *CopyConstructor) {
9767 assert((CopyConstructor->isDefaulted() &&
9768 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009769 !CopyConstructor->doesThisDeclarationHaveABody() &&
9770 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009771 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009772
Anders Carlsson63010a72010-04-23 16:24:12 +00009773 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009774 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009775
Richard Smith36155c12013-06-13 03:23:42 +00009776 // C++11 [class.copy]p7:
9777 // The [definition of an implicitly declared copy constructro] is
9778 // deprecated if the class has a user-declared copy assignment operator
9779 // or a user-declared destructor.
9780 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9781 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9782
Eli Friedman9a14db32012-10-18 20:14:08 +00009783 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009784 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009785
David Blaikie93c86172013-01-17 05:26:25 +00009786 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009787 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009788 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009789 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009790 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009791 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009792 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009793 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9794 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009795 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009796 /*isStmtExpr=*/false)
9797 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009798 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009799 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009800
9801 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009802 if (ASTMutationListener *L = getASTMutationListener()) {
9803 L->CompletedImplicitDefinition(CopyConstructor);
9804 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009805}
9806
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009807Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009808Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9809 CXXRecordDecl *ClassDecl = MD->getParent();
9810
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009811 // C++ [except.spec]p14:
9812 // An implicitly declared special member function (Clause 12) shall have an
9813 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009814 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009815 if (ClassDecl->isInvalidDecl())
9816 return ExceptSpec;
9817
9818 // Direct base-class constructors.
9819 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9820 BEnd = ClassDecl->bases_end();
9821 B != BEnd; ++B) {
9822 if (B->isVirtual()) // Handled below.
9823 continue;
9824
9825 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9826 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009827 CXXConstructorDecl *Constructor =
9828 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009829 // If this is a deleted function, add it anyway. This might be conformant
9830 // with the standard. This might not. I'm not sure. It might not matter.
9831 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009832 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009833 }
9834 }
9835
9836 // Virtual base-class constructors.
9837 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9838 BEnd = ClassDecl->vbases_end();
9839 B != BEnd; ++B) {
9840 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9841 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009842 CXXConstructorDecl *Constructor =
9843 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009844 // If this is a deleted function, add it anyway. This might be conformant
9845 // with the standard. This might not. I'm not sure. It might not matter.
9846 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009847 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009848 }
9849 }
9850
9851 // Field constructors.
9852 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9853 FEnd = ClassDecl->field_end();
9854 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009855 QualType FieldType = Context.getBaseElementType(F->getType());
9856 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9857 CXXConstructorDecl *Constructor =
9858 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009859 // If this is a deleted function, add it anyway. This might be conformant
9860 // with the standard. This might not. I'm not sure. It might not matter.
9861 // In particular, the problem is that this function never gets called. It
9862 // might just be ill-formed because this function attempts to refer to
9863 // a deleted function here.
9864 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009865 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009866 }
9867 }
9868
9869 return ExceptSpec;
9870}
9871
9872CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9873 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009874 // C++11 [class.copy]p9:
9875 // If the definition of a class X does not explicitly declare a move
9876 // constructor, one will be implicitly declared as defaulted if and only if:
9877 //
9878 // - [first 4 bullets]
9879 assert(ClassDecl->needsImplicitMoveConstructor());
9880
Richard Smithafb49182012-11-29 01:34:07 +00009881 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9882 if (DSM.isAlreadyBeingDeclared())
9883 return 0;
9884
Richard Smith1c931be2012-04-02 18:40:40 +00009885 // [Checked after we build the declaration]
9886 // - the move assignment operator would not be implicitly defined as
9887 // deleted,
9888
9889 // [DR1402]:
9890 // - each of X's non-static data members and direct or virtual base classes
9891 // has a type that either has a move constructor or is trivially copyable.
9892 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9893 ClassDecl->setFailedImplicitMoveConstructor();
9894 return 0;
9895 }
9896
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009897 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9898 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009899
Richard Smith7756afa2012-06-10 05:43:50 +00009900 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9901 CXXMoveConstructor,
9902 false);
9903
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009904 DeclarationName Name
9905 = Context.DeclarationNames.getCXXConstructorName(
9906 Context.getCanonicalType(ClassType));
9907 SourceLocation ClassLoc = ClassDecl->getLocation();
9908 DeclarationNameInfo NameInfo(Name, ClassLoc);
9909
Richard Smitha8942d72013-05-07 03:19:20 +00009910 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009911 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009912 // member of its class.
9913 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009914 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009915 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009916 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009917 MoveConstructor->setAccess(AS_public);
9918 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009919
Richard Smithb9d0b762012-07-27 04:22:15 +00009920 // Build an exception specification pointing back at this member.
9921 FunctionProtoType::ExtProtoInfo EPI;
9922 EPI.ExceptionSpecType = EST_Unevaluated;
9923 EPI.ExceptionSpecDecl = MoveConstructor;
9924 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009925 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009926
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009927 // Add the parameter to the constructor.
9928 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9929 ClassLoc, ClassLoc,
9930 /*IdentifierInfo=*/0,
9931 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009932 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009933 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009934
Richard Smithbc2a35d2012-12-08 08:32:28 +00009935 MoveConstructor->setTrivial(
9936 ClassDecl->needsOverloadResolutionForMoveConstructor()
9937 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9938 : ClassDecl->hasTrivialMoveConstructor());
9939
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009940 // C++0x [class.copy]p9:
9941 // If the definition of a class X does not explicitly declare a move
9942 // constructor, one will be implicitly declared as defaulted if and only if:
9943 // [...]
9944 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009945 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009946 // Cache this result so that we don't try to generate this over and over
9947 // on every lookup, leaking memory and wasting time.
9948 ClassDecl->setFailedImplicitMoveConstructor();
9949 return 0;
9950 }
9951
9952 // Note that we have declared this constructor.
9953 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9954
9955 if (Scope *S = getScopeForContext(ClassDecl))
9956 PushOnScopeChains(MoveConstructor, S, false);
9957 ClassDecl->addDecl(MoveConstructor);
9958
9959 return MoveConstructor;
9960}
9961
9962void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9963 CXXConstructorDecl *MoveConstructor) {
9964 assert((MoveConstructor->isDefaulted() &&
9965 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009966 !MoveConstructor->doesThisDeclarationHaveABody() &&
9967 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009968 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9969
9970 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9971 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9972
Eli Friedman9a14db32012-10-18 20:14:08 +00009973 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009974 DiagnosticErrorTrap Trap(Diags);
9975
David Blaikie93c86172013-01-17 05:26:25 +00009976 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009977 Trap.hasErrorOccurred()) {
9978 Diag(CurrentLocation, diag::note_member_synthesized_at)
9979 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9980 MoveConstructor->setInvalidDecl();
9981 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009982 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009983 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9984 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009985 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009986 /*isStmtExpr=*/false)
9987 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009988 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009989 }
9990
9991 MoveConstructor->setUsed();
9992
9993 if (ASTMutationListener *L = getASTMutationListener()) {
9994 L->CompletedImplicitDefinition(MoveConstructor);
9995 }
9996}
9997
Douglas Gregore4e68d42012-02-15 19:33:52 +00009998bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9999 return FD->isDeleted() &&
10000 (FD->isDefaulted() || FD->isImplicit()) &&
10001 isa<CXXMethodDecl>(FD);
10002}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010003
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010004/// \brief Mark the call operator of the given lambda closure type as "used".
10005static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
10006 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +000010007 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +000010008 Lambda->lookup(
10009 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010010 CallOperator->setReferenced();
10011 CallOperator->setUsed();
10012}
10013
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010014void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10015 SourceLocation CurrentLocation,
10016 CXXConversionDecl *Conv)
10017{
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010018 CXXRecordDecl *Lambda = Conv->getParent();
10019
10020 // Make sure that the lambda call operator is marked used.
10021 markLambdaCallOperatorUsed(*this, Lambda);
10022
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010023 Conv->setUsed();
10024
Eli Friedman9a14db32012-10-18 20:14:08 +000010025 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010026 DiagnosticErrorTrap Trap(Diags);
10027
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010028 // Return the address of the __invoke function.
10029 DeclarationName InvokeName = &Context.Idents.get("__invoke");
10030 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +000010031 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010032 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
10033 VK_LValue, Conv->getLocation()).take();
10034 assert(FunctionRef && "Can't refer to __invoke function?");
10035 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +000010036 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010037 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010038 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010039
10040 // Fill in the __invoke function with a dummy implementation. IR generation
10041 // will fill in the actual details.
10042 Invoke->setUsed();
10043 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +000010044 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010045
10046 if (ASTMutationListener *L = getASTMutationListener()) {
10047 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010048 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010049 }
10050}
10051
10052void Sema::DefineImplicitLambdaToBlockPointerConversion(
10053 SourceLocation CurrentLocation,
10054 CXXConversionDecl *Conv)
10055{
10056 Conv->setUsed();
10057
Eli Friedman9a14db32012-10-18 20:14:08 +000010058 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010059 DiagnosticErrorTrap Trap(Diags);
10060
Douglas Gregorac1303e2012-02-22 05:02:47 +000010061 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010062 Expr *This = ActOnCXXThis(CurrentLocation).take();
10063 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010064
Eli Friedman23f02672012-03-01 04:01:32 +000010065 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10066 Conv->getLocation(),
10067 Conv, DerefThis);
10068
10069 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10070 // behavior. Note that only the general conversion function does this
10071 // (since it's unusable otherwise); in the case where we inline the
10072 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010073 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010074 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10075 CK_CopyAndAutoreleaseBlockObject,
10076 BuildBlock.get(), 0, VK_RValue);
10077
10078 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010079 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010080 Conv->setInvalidDecl();
10081 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010082 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010083
Douglas Gregorac1303e2012-02-22 05:02:47 +000010084 // Create the return statement that returns the block from the conversion
10085 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010086 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010087 if (Return.isInvalid()) {
10088 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10089 Conv->setInvalidDecl();
10090 return;
10091 }
10092
10093 // Set the body of the conversion function.
10094 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010095 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010096 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010097 Conv->getLocation()));
10098
Douglas Gregorac1303e2012-02-22 05:02:47 +000010099 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010100 if (ASTMutationListener *L = getASTMutationListener()) {
10101 L->CompletedImplicitDefinition(Conv);
10102 }
10103}
10104
Douglas Gregorf52757d2012-03-10 06:53:13 +000010105/// \brief Determine whether the given list arguments contains exactly one
10106/// "real" (non-default) argument.
10107static bool hasOneRealArgument(MultiExprArg Args) {
10108 switch (Args.size()) {
10109 case 0:
10110 return false;
10111
10112 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010113 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010114 return false;
10115
10116 // fall through
10117 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010118 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010119 }
10120
10121 return false;
10122}
10123
John McCall60d7b3a2010-08-24 06:29:42 +000010124ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010125Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010126 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010127 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010128 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010129 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010130 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010131 unsigned ConstructKind,
10132 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010133 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010134
Douglas Gregor2f599792010-04-02 18:24:57 +000010135 // C++0x [class.copy]p34:
10136 // When certain criteria are met, an implementation is allowed to
10137 // omit the copy/move construction of a class object, even if the
10138 // copy/move constructor and/or destructor for the object have
10139 // side effects. [...]
10140 // - when a temporary class object that has not been bound to a
10141 // reference (12.2) would be copied/moved to a class object
10142 // with the same cv-unqualified type, the copy/move operation
10143 // can be omitted by constructing the temporary object
10144 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010145 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010146 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010147 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010148 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010149 }
Mike Stump1eb44332009-09-09 15:08:12 +000010150
10151 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010152 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010153 IsListInitialization, RequiresZeroInit,
10154 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010155}
10156
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010157/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10158/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010159ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010160Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10161 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010162 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010163 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010164 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010165 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010166 unsigned ConstructKind,
10167 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010168 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010169 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010170 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010171 HadMultipleCandidates,
10172 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010173 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10174 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010175}
10176
John McCall68c6c9a2010-02-02 09:10:11 +000010177void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010178 if (VD->isInvalidDecl()) return;
10179
John McCall68c6c9a2010-02-02 09:10:11 +000010180 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010181 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010182 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010183 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010184
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010185 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010186 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010187 CheckDestructorAccess(VD->getLocation(), Destructor,
10188 PDiag(diag::err_access_dtor_var)
10189 << VD->getDeclName()
10190 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010191 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010192
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010193 if (!VD->hasGlobalStorage()) return;
10194
10195 // Emit warning for non-trivial dtor in global scope (a real global,
10196 // class-static, function-static).
10197 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10198
10199 // TODO: this should be re-enabled for static locals by !CXAAtExit
10200 if (!VD->isStaticLocal())
10201 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010202}
10203
Douglas Gregor39da0b82009-09-09 23:08:42 +000010204/// \brief Given a constructor and the set of arguments provided for the
10205/// constructor, convert the arguments and add any required default arguments
10206/// to form a proper call to this constructor.
10207///
10208/// \returns true if an error occurred, false otherwise.
10209bool
10210Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10211 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010212 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010213 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010214 bool AllowExplicit,
10215 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010216 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10217 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010218 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010219
10220 const FunctionProtoType *Proto
10221 = Constructor->getType()->getAs<FunctionProtoType>();
10222 assert(Proto && "Constructor without a prototype?");
10223 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010224
10225 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010226 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010227 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010228 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010229 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010230
10231 VariadicCallType CallType =
10232 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010233 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010234 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010235 Proto, 0,
10236 llvm::makeArrayRef(Args, NumArgs),
10237 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010238 CallType, AllowExplicit,
10239 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010240 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010241
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010242 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010243
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010244 CheckConstructorCall(Constructor,
10245 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10246 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010247 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010248
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010249 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010250}
10251
Anders Carlsson20d45d22009-12-12 00:32:00 +000010252static inline bool
10253CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10254 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010255 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010256 if (isa<NamespaceDecl>(DC)) {
10257 return SemaRef.Diag(FnDecl->getLocation(),
10258 diag::err_operator_new_delete_declared_in_namespace)
10259 << FnDecl->getDeclName();
10260 }
10261
10262 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010263 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010264 return SemaRef.Diag(FnDecl->getLocation(),
10265 diag::err_operator_new_delete_declared_static)
10266 << FnDecl->getDeclName();
10267 }
10268
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010269 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010270}
10271
Anders Carlsson156c78e2009-12-13 17:53:43 +000010272static inline bool
10273CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10274 CanQualType ExpectedResultType,
10275 CanQualType ExpectedFirstParamType,
10276 unsigned DependentParamTypeDiag,
10277 unsigned InvalidParamTypeDiag) {
10278 QualType ResultType =
10279 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10280
10281 // Check that the result type is not dependent.
10282 if (ResultType->isDependentType())
10283 return SemaRef.Diag(FnDecl->getLocation(),
10284 diag::err_operator_new_delete_dependent_result_type)
10285 << FnDecl->getDeclName() << ExpectedResultType;
10286
10287 // Check that the result type is what we expect.
10288 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10289 return SemaRef.Diag(FnDecl->getLocation(),
10290 diag::err_operator_new_delete_invalid_result_type)
10291 << FnDecl->getDeclName() << ExpectedResultType;
10292
10293 // A function template must have at least 2 parameters.
10294 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10295 return SemaRef.Diag(FnDecl->getLocation(),
10296 diag::err_operator_new_delete_template_too_few_parameters)
10297 << FnDecl->getDeclName();
10298
10299 // The function decl must have at least 1 parameter.
10300 if (FnDecl->getNumParams() == 0)
10301 return SemaRef.Diag(FnDecl->getLocation(),
10302 diag::err_operator_new_delete_too_few_parameters)
10303 << FnDecl->getDeclName();
10304
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010305 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010306 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10307 if (FirstParamType->isDependentType())
10308 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10309 << FnDecl->getDeclName() << ExpectedFirstParamType;
10310
10311 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010312 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010313 ExpectedFirstParamType)
10314 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10315 << FnDecl->getDeclName() << ExpectedFirstParamType;
10316
10317 return false;
10318}
10319
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010320static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010321CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010322 // C++ [basic.stc.dynamic.allocation]p1:
10323 // A program is ill-formed if an allocation function is declared in a
10324 // namespace scope other than global scope or declared static in global
10325 // scope.
10326 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10327 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010328
10329 CanQualType SizeTy =
10330 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10331
10332 // C++ [basic.stc.dynamic.allocation]p1:
10333 // The return type shall be void*. The first parameter shall have type
10334 // std::size_t.
10335 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10336 SizeTy,
10337 diag::err_operator_new_dependent_param_type,
10338 diag::err_operator_new_param_type))
10339 return true;
10340
10341 // C++ [basic.stc.dynamic.allocation]p1:
10342 // The first parameter shall not have an associated default argument.
10343 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010344 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010345 diag::err_operator_new_default_arg)
10346 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10347
10348 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010349}
10350
10351static bool
Richard Smith444d3842012-10-20 08:26:51 +000010352CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010353 // C++ [basic.stc.dynamic.deallocation]p1:
10354 // A program is ill-formed if deallocation functions are declared in a
10355 // namespace scope other than global scope or declared static in global
10356 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010357 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10358 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010359
10360 // C++ [basic.stc.dynamic.deallocation]p2:
10361 // Each deallocation function shall return void and its first parameter
10362 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010363 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10364 SemaRef.Context.VoidPtrTy,
10365 diag::err_operator_delete_dependent_param_type,
10366 diag::err_operator_delete_param_type))
10367 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010368
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010369 return false;
10370}
10371
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010372/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10373/// of this overloaded operator is well-formed. If so, returns false;
10374/// otherwise, emits appropriate diagnostics and returns true.
10375bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010376 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010377 "Expected an overloaded operator declaration");
10378
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010379 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10380
Mike Stump1eb44332009-09-09 15:08:12 +000010381 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010382 // The allocation and deallocation functions, operator new,
10383 // operator new[], operator delete and operator delete[], are
10384 // described completely in 3.7.3. The attributes and restrictions
10385 // found in the rest of this subclause do not apply to them unless
10386 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010387 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010388 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010389
Anders Carlssona3ccda52009-12-12 00:26:23 +000010390 if (Op == OO_New || Op == OO_Array_New)
10391 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010392
10393 // C++ [over.oper]p6:
10394 // An operator function shall either be a non-static member
10395 // function or be a non-member function and have at least one
10396 // parameter whose type is a class, a reference to a class, an
10397 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010398 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10399 if (MethodDecl->isStatic())
10400 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010401 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010402 } else {
10403 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010404 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10405 ParamEnd = FnDecl->param_end();
10406 Param != ParamEnd; ++Param) {
10407 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010408 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10409 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010410 ClassOrEnumParam = true;
10411 break;
10412 }
10413 }
10414
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010415 if (!ClassOrEnumParam)
10416 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010417 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010418 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010419 }
10420
10421 // C++ [over.oper]p8:
10422 // An operator function cannot have default arguments (8.3.6),
10423 // except where explicitly stated below.
10424 //
Mike Stump1eb44332009-09-09 15:08:12 +000010425 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010426 // (C++ [over.call]p1).
10427 if (Op != OO_Call) {
10428 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10429 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010430 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010431 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010432 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010433 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010434 }
10435 }
10436
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010437 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10438 { false, false, false }
10439#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10440 , { Unary, Binary, MemberOnly }
10441#include "clang/Basic/OperatorKinds.def"
10442 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010443
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010444 bool CanBeUnaryOperator = OperatorUses[Op][0];
10445 bool CanBeBinaryOperator = OperatorUses[Op][1];
10446 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010447
10448 // C++ [over.oper]p8:
10449 // [...] Operator functions cannot have more or fewer parameters
10450 // than the number required for the corresponding operator, as
10451 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010452 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010453 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010454 if (Op != OO_Call &&
10455 ((NumParams == 1 && !CanBeUnaryOperator) ||
10456 (NumParams == 2 && !CanBeBinaryOperator) ||
10457 (NumParams < 1) || (NumParams > 2))) {
10458 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010459 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010460 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010461 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010462 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010463 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010464 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010465 assert(CanBeBinaryOperator &&
10466 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010467 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010468 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010469
Chris Lattner416e46f2008-11-21 07:57:12 +000010470 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010471 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010472 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010473
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010474 // Overloaded operators other than operator() cannot be variadic.
10475 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010476 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010477 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010478 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010479 }
10480
10481 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010482 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10483 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010484 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010485 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010486 }
10487
10488 // C++ [over.inc]p1:
10489 // The user-defined function called operator++ implements the
10490 // prefix and postfix ++ operator. If this function is a member
10491 // function with no parameters, or a non-member function with one
10492 // parameter of class or enumeration type, it defines the prefix
10493 // increment operator ++ for objects of that type. If the function
10494 // is a member function with one parameter (which shall be of type
10495 // int) or a non-member function with two parameters (the second
10496 // of which shall be of type int), it defines the postfix
10497 // increment operator ++ for objects of that type.
10498 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10499 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10500 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010501 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010502 ParamIsInt = BT->getKind() == BuiltinType::Int;
10503
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010504 if (!ParamIsInt)
10505 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010506 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010507 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010508 }
10509
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010510 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010511}
Chris Lattner5a003a42008-12-17 07:09:26 +000010512
Sean Hunta6c058d2010-01-13 09:01:02 +000010513/// CheckLiteralOperatorDeclaration - Check whether the declaration
10514/// of this literal operator function is well-formed. If so, returns
10515/// false; otherwise, emits appropriate diagnostics and returns true.
10516bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010517 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010518 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10519 << FnDecl->getDeclName();
10520 return true;
10521 }
10522
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010523 if (FnDecl->isExternC()) {
10524 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10525 return true;
10526 }
10527
Sean Hunta6c058d2010-01-13 09:01:02 +000010528 bool Valid = false;
10529
Richard Smith36f5cfe2012-03-09 08:00:36 +000010530 // This might be the definition of a literal operator template.
10531 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10532 // This might be a specialization of a literal operator template.
10533 if (!TpDecl)
10534 TpDecl = FnDecl->getPrimaryTemplate();
10535
Sean Hunt216c2782010-04-07 23:11:06 +000010536 // template <char...> type operator "" name() is the only valid template
10537 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010538 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010539 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010540 // Must have only one template parameter
10541 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10542 if (Params->size() == 1) {
10543 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010544 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010545
Sean Hunt216c2782010-04-07 23:11:06 +000010546 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010547 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10548 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10549 Valid = true;
10550 }
10551 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010552 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010553 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010554 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10555
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010556 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010557
Sean Hunt30019c02010-04-07 22:57:35 +000010558 // unsigned long long int, long double, and any character type are allowed
10559 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010560 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10561 Context.hasSameType(T, Context.LongDoubleTy) ||
10562 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010563 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010564 Context.hasSameType(T, Context.Char16Ty) ||
10565 Context.hasSameType(T, Context.Char32Ty)) {
10566 if (++Param == FnDecl->param_end())
10567 Valid = true;
10568 goto FinishedParams;
10569 }
10570
Sean Hunt30019c02010-04-07 22:57:35 +000010571 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010572 const PointerType *PT = T->getAs<PointerType>();
10573 if (!PT)
10574 goto FinishedParams;
10575 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010576 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010577 goto FinishedParams;
10578 T = T.getUnqualifiedType();
10579
10580 // Move on to the second parameter;
10581 ++Param;
10582
10583 // If there is no second parameter, the first must be a const char *
10584 if (Param == FnDecl->param_end()) {
10585 if (Context.hasSameType(T, Context.CharTy))
10586 Valid = true;
10587 goto FinishedParams;
10588 }
10589
10590 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10591 // are allowed as the first parameter to a two-parameter function
10592 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010593 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010594 Context.hasSameType(T, Context.Char16Ty) ||
10595 Context.hasSameType(T, Context.Char32Ty)))
10596 goto FinishedParams;
10597
10598 // The second and final parameter must be an std::size_t
10599 T = (*Param)->getType().getUnqualifiedType();
10600 if (Context.hasSameType(T, Context.getSizeType()) &&
10601 ++Param == FnDecl->param_end())
10602 Valid = true;
10603 }
10604
10605 // FIXME: This diagnostic is absolutely terrible.
10606FinishedParams:
10607 if (!Valid) {
10608 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10609 << FnDecl->getDeclName();
10610 return true;
10611 }
10612
Richard Smitha9e88b22012-03-09 08:16:22 +000010613 // A parameter-declaration-clause containing a default argument is not
10614 // equivalent to any of the permitted forms.
10615 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10616 ParamEnd = FnDecl->param_end();
10617 Param != ParamEnd; ++Param) {
10618 if ((*Param)->hasDefaultArg()) {
10619 Diag((*Param)->getDefaultArgRange().getBegin(),
10620 diag::err_literal_operator_default_argument)
10621 << (*Param)->getDefaultArgRange();
10622 break;
10623 }
10624 }
10625
Richard Smith2fb4ae32012-03-08 02:39:21 +000010626 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010627 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10628 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010629 // C++11 [usrlit.suffix]p1:
10630 // Literal suffix identifiers that do not start with an underscore
10631 // are reserved for future standardization.
10632 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010633 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010634
Sean Hunta6c058d2010-01-13 09:01:02 +000010635 return false;
10636}
10637
Douglas Gregor074149e2009-01-05 19:45:36 +000010638/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10639/// linkage specification, including the language and (if present)
10640/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10641/// the location of the language string literal, which is provided
10642/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10643/// the '{' brace. Otherwise, this linkage specification does not
10644/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010645Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10646 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010647 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010648 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010649 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010650 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010651 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010652 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010653 Language = LinkageSpecDecl::lang_cxx;
10654 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010655 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010656 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010657 }
Mike Stump1eb44332009-09-09 15:08:12 +000010658
Chris Lattnercc98eac2008-12-17 07:13:27 +000010659 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010660
Douglas Gregor074149e2009-01-05 19:45:36 +000010661 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010662 ExternLoc, LangLoc, Language,
10663 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010664 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010665 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010666 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010667}
10668
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010669/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010670/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10671/// valid, it's the position of the closing '}' brace in a linkage
10672/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010673Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010674 Decl *LinkageSpec,
10675 SourceLocation RBraceLoc) {
10676 if (LinkageSpec) {
10677 if (RBraceLoc.isValid()) {
10678 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10679 LSDecl->setRBraceLoc(RBraceLoc);
10680 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010681 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010682 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010683 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010684}
10685
Michael Han684aa732013-02-22 17:15:32 +000010686Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10687 AttributeList *AttrList,
10688 SourceLocation SemiLoc) {
10689 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10690 // Attribute declarations appertain to empty declaration so we handle
10691 // them here.
10692 if (AttrList)
10693 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010694
Michael Han684aa732013-02-22 17:15:32 +000010695 CurContext->addDecl(ED);
10696 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010697}
10698
Douglas Gregord308e622009-05-18 20:51:54 +000010699/// \brief Perform semantic analysis for the variable declaration that
10700/// occurs within a C++ catch clause, returning the newly-created
10701/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010702VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010703 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010704 SourceLocation StartLoc,
10705 SourceLocation Loc,
10706 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010707 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010708 QualType ExDeclType = TInfo->getType();
10709
Sebastian Redl4b07b292008-12-22 19:15:10 +000010710 // Arrays and functions decay.
10711 if (ExDeclType->isArrayType())
10712 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10713 else if (ExDeclType->isFunctionType())
10714 ExDeclType = Context.getPointerType(ExDeclType);
10715
10716 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10717 // The exception-declaration shall not denote a pointer or reference to an
10718 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010719 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010720 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010721 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010722 Invalid = true;
10723 }
Douglas Gregord308e622009-05-18 20:51:54 +000010724
Sebastian Redl4b07b292008-12-22 19:15:10 +000010725 QualType BaseType = ExDeclType;
10726 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010727 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010728 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010729 BaseType = Ptr->getPointeeType();
10730 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010731 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010732 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010733 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010734 BaseType = Ref->getPointeeType();
10735 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010736 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010737 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010738 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010739 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010740 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010741
Mike Stump1eb44332009-09-09 15:08:12 +000010742 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010743 RequireNonAbstractType(Loc, ExDeclType,
10744 diag::err_abstract_type_in_decl,
10745 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010746 Invalid = true;
10747
John McCall5a180392010-07-24 00:37:23 +000010748 // Only the non-fragile NeXT runtime currently supports C++ catches
10749 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010750 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010751 QualType T = ExDeclType;
10752 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10753 T = RT->getPointeeType();
10754
10755 if (T->isObjCObjectType()) {
10756 Diag(Loc, diag::err_objc_object_catch);
10757 Invalid = true;
10758 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010759 // FIXME: should this be a test for macosx-fragile specifically?
10760 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010761 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010762 }
10763 }
10764
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010765 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010766 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010767 ExDecl->setExceptionVariable(true);
10768
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010769 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010770 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010771 Invalid = true;
10772
Douglas Gregorc41b8782011-07-06 18:14:43 +000010773 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010774 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010775 // Insulate this from anything else we might currently be parsing.
10776 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10777
Douglas Gregor6d182892010-03-05 23:38:39 +000010778 // C++ [except.handle]p16:
10779 // The object declared in an exception-declaration or, if the
10780 // exception-declaration does not specify a name, a temporary (12.2) is
10781 // copy-initialized (8.5) from the exception object. [...]
10782 // The object is destroyed when the handler exits, after the destruction
10783 // of any automatic objects initialized within the handler.
10784 //
10785 // We just pretend to initialize the object with itself, then make sure
10786 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010787 QualType initType = ExDeclType;
10788
10789 InitializedEntity entity =
10790 InitializedEntity::InitializeVariable(ExDecl);
10791 InitializationKind initKind =
10792 InitializationKind::CreateCopy(Loc, SourceLocation());
10793
10794 Expr *opaqueValue =
10795 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010796 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10797 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010798 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010799 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010800 else {
10801 // If the constructor used was non-trivial, set this as the
10802 // "initializer".
10803 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10804 if (!construct->getConstructor()->isTrivial()) {
10805 Expr *init = MaybeCreateExprWithCleanups(construct);
10806 ExDecl->setInit(init);
10807 }
10808
10809 // And make sure it's destructable.
10810 FinalizeVarWithDestructor(ExDecl, recordType);
10811 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010812 }
10813 }
10814
Douglas Gregord308e622009-05-18 20:51:54 +000010815 if (Invalid)
10816 ExDecl->setInvalidDecl();
10817
10818 return ExDecl;
10819}
10820
10821/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10822/// handler.
John McCalld226f652010-08-21 09:40:31 +000010823Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010824 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010825 bool Invalid = D.isInvalidType();
10826
10827 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010828 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10829 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010830 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10831 D.getIdentifierLoc());
10832 Invalid = true;
10833 }
10834
Sebastian Redl4b07b292008-12-22 19:15:10 +000010835 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010836 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010837 LookupOrdinaryName,
10838 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010839 // The scope should be freshly made just for us. There is just no way
10840 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010841 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010842 if (PrevDecl->isTemplateParameter()) {
10843 // Maybe we will complain about the shadowed template parameter.
10844 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010845 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010846 }
10847 }
10848
Chris Lattnereaaebc72009-04-25 08:06:05 +000010849 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010850 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10851 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010852 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010853 }
10854
Douglas Gregor83cb9422010-09-09 17:09:21 +000010855 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010856 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010857 D.getIdentifierLoc(),
10858 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010859 if (Invalid)
10860 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010861
Sebastian Redl4b07b292008-12-22 19:15:10 +000010862 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010863 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010864 PushOnScopeChains(ExDecl, S);
10865 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010866 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010867
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010868 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010869 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010870}
Anders Carlssonfb311762009-03-14 00:25:26 +000010871
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010872Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010873 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010874 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010875 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010876 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010877
Richard Smithe3f470a2012-07-11 22:37:56 +000010878 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10879 return 0;
10880
10881 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10882 AssertMessage, RParenLoc, false);
10883}
10884
10885Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10886 Expr *AssertExpr,
10887 StringLiteral *AssertMessage,
10888 SourceLocation RParenLoc,
10889 bool Failed) {
10890 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10891 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010892 // In a static_assert-declaration, the constant-expression shall be a
10893 // constant expression that can be contextually converted to bool.
10894 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10895 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010896 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010897
Richard Smithdaaefc52011-12-14 23:32:26 +000010898 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010899 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010900 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010901 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010902 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010903
Richard Smithe3f470a2012-07-11 22:37:56 +000010904 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010905 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010906 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010907 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010908 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010909 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010910 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010911 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010912 }
Mike Stump1eb44332009-09-09 15:08:12 +000010913
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010914 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010915 AssertExpr, AssertMessage, RParenLoc,
10916 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010917
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010918 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010919 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010920}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010921
Douglas Gregor1d869352010-04-07 16:53:43 +000010922/// \brief Perform semantic analysis of the given friend type declaration.
10923///
10924/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010925FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010926 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010927 TypeSourceInfo *TSInfo) {
10928 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10929
10930 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010931 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010932
Richard Smith6b130222011-10-18 21:39:00 +000010933 // C++03 [class.friend]p2:
10934 // An elaborated-type-specifier shall be used in a friend declaration
10935 // for a class.*
10936 //
10937 // * The class-key of the elaborated-type-specifier is required.
10938 if (!ActiveTemplateInstantiations.empty()) {
10939 // Do not complain about the form of friend template types during
10940 // template instantiation; we will already have complained when the
10941 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010942 } else {
10943 if (!T->isElaboratedTypeSpecifier()) {
10944 // If we evaluated the type to a record type, suggest putting
10945 // a tag in front.
10946 if (const RecordType *RT = T->getAs<RecordType>()) {
10947 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010948
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010949 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010950
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010951 Diag(TypeRange.getBegin(),
10952 getLangOpts().CPlusPlus11 ?
10953 diag::warn_cxx98_compat_unelaborated_friend_type :
10954 diag::ext_unelaborated_friend_type)
10955 << (unsigned) RD->getTagKind()
10956 << T
10957 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10958 InsertionText);
10959 } else {
10960 Diag(FriendLoc,
10961 getLangOpts().CPlusPlus11 ?
10962 diag::warn_cxx98_compat_nonclass_type_friend :
10963 diag::ext_nonclass_type_friend)
10964 << T
10965 << TypeRange;
10966 }
10967 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010968 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010969 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010970 diag::warn_cxx98_compat_enum_friend :
10971 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010972 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010973 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010974 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010975
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010976 // C++11 [class.friend]p3:
10977 // A friend declaration that does not declare a function shall have one
10978 // of the following forms:
10979 // friend elaborated-type-specifier ;
10980 // friend simple-type-specifier ;
10981 // friend typename-specifier ;
10982 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10983 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10984 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010985
Douglas Gregor06245bf2010-04-07 17:57:12 +000010986 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010987 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010988 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010989 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010990}
10991
John McCall9a34edb2010-10-19 01:40:49 +000010992/// Handle a friend tag declaration where the scope specifier was
10993/// templated.
10994Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10995 unsigned TagSpec, SourceLocation TagLoc,
10996 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010997 IdentifierInfo *Name,
10998 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010999 AttributeList *Attr,
11000 MultiTemplateParamsArg TempParamLists) {
11001 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11002
11003 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011004 bool Invalid = false;
11005
11006 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000011007 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011008 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000011009 TempParamLists.size(),
11010 /*friend*/ true,
11011 isExplicitSpecialization,
11012 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011013 if (TemplateParams->size() > 0) {
11014 // This is a declaration of a class template.
11015 if (Invalid)
11016 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011017
Eric Christopher4110e132011-07-21 05:34:24 +000011018 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11019 SS, Name, NameLoc, Attr,
11020 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011021 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011022 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011023 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011024 } else {
11025 // The "template<>" header is extraneous.
11026 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11027 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11028 isExplicitSpecialization = true;
11029 }
11030 }
11031
11032 if (Invalid) return 0;
11033
John McCall9a34edb2010-10-19 01:40:49 +000011034 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011035 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011036 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011037 isAllExplicitSpecializations = false;
11038 break;
11039 }
11040 }
11041
11042 // FIXME: don't ignore attributes.
11043
11044 // If it's explicit specializations all the way down, just forget
11045 // about the template header and build an appropriate non-templated
11046 // friend. TODO: for source fidelity, remember the headers.
11047 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011048 if (SS.isEmpty()) {
11049 bool Owned = false;
11050 bool IsDependent = false;
11051 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11052 Attr, AS_public,
11053 /*ModulePrivateLoc=*/SourceLocation(),
11054 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011055 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011056 /*ScopedEnumUsesClassTag=*/false,
11057 /*UnderlyingType=*/TypeResult());
11058 }
11059
Douglas Gregor2494dd02011-03-01 01:34:45 +000011060 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011061 ElaboratedTypeKeyword Keyword
11062 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011063 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011064 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011065 if (T.isNull())
11066 return 0;
11067
11068 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11069 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011070 DependentNameTypeLoc TL =
11071 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011072 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011073 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011074 TL.setNameLoc(NameLoc);
11075 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011076 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011077 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011078 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011079 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011080 }
11081
11082 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011083 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011084 Friend->setAccess(AS_public);
11085 CurContext->addDecl(Friend);
11086 return Friend;
11087 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011088
11089 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11090
11091
John McCall9a34edb2010-10-19 01:40:49 +000011092
11093 // Handle the case of a templated-scope friend class. e.g.
11094 // template <class T> class A<T>::B;
11095 // FIXME: we don't support these right now.
11096 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11097 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11098 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011099 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011100 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011101 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011102 TL.setNameLoc(NameLoc);
11103
11104 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011105 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011106 Friend->setAccess(AS_public);
11107 Friend->setUnsupportedFriend(true);
11108 CurContext->addDecl(Friend);
11109 return Friend;
11110}
11111
11112
John McCalldd4a3b02009-09-16 22:47:08 +000011113/// Handle a friend type declaration. This works in tandem with
11114/// ActOnTag.
11115///
11116/// Notes on friend class templates:
11117///
11118/// We generally treat friend class declarations as if they were
11119/// declaring a class. So, for example, the elaborated type specifier
11120/// in a friend declaration is required to obey the restrictions of a
11121/// class-head (i.e. no typedefs in the scope chain), template
11122/// parameters are required to match up with simple template-ids, &c.
11123/// However, unlike when declaring a template specialization, it's
11124/// okay to refer to a template specialization without an empty
11125/// template parameter declaration, e.g.
11126/// friend class A<T>::B<unsigned>;
11127/// We permit this as a special case; if there are any template
11128/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011129/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011130Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011131 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011132 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011133
11134 assert(DS.isFriendSpecified());
11135 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11136
John McCalldd4a3b02009-09-16 22:47:08 +000011137 // Try to convert the decl specifier to a type. This works for
11138 // friend templates because ActOnTag never produces a ClassTemplateDecl
11139 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011140 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011141 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11142 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011143 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011144 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011145
Douglas Gregor6ccab972010-12-16 01:14:37 +000011146 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11147 return 0;
11148
John McCalldd4a3b02009-09-16 22:47:08 +000011149 // This is definitely an error in C++98. It's probably meant to
11150 // be forbidden in C++0x, too, but the specification is just
11151 // poorly written.
11152 //
11153 // The problem is with declarations like the following:
11154 // template <T> friend A<T>::foo;
11155 // where deciding whether a class C is a friend or not now hinges
11156 // on whether there exists an instantiation of A that causes
11157 // 'foo' to equal C. There are restrictions on class-heads
11158 // (which we declare (by fiat) elaborated friend declarations to
11159 // be) that makes this tractable.
11160 //
11161 // FIXME: handle "template <> friend class A<T>;", which
11162 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011163 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011164 Diag(Loc, diag::err_tagless_friend_type_template)
11165 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011166 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011167 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011168
John McCall02cace72009-08-28 07:59:38 +000011169 // C++98 [class.friend]p1: A friend of a class is a function
11170 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011171 // This is fixed in DR77, which just barely didn't make the C++03
11172 // deadline. It's also a very silly restriction that seriously
11173 // affects inner classes and which nobody else seems to implement;
11174 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011175 //
11176 // But note that we could warn about it: it's always useless to
11177 // friend one of your own members (it's not, however, worthless to
11178 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011179
John McCalldd4a3b02009-09-16 22:47:08 +000011180 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011181 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011182 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011183 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011184 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011185 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011186 DS.getFriendSpecLoc());
11187 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011188 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011189
11190 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011191 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011192
John McCalldd4a3b02009-09-16 22:47:08 +000011193 D->setAccess(AS_public);
11194 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011195
John McCalld226f652010-08-21 09:40:31 +000011196 return D;
John McCall02cace72009-08-28 07:59:38 +000011197}
11198
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011199NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11200 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011201 const DeclSpec &DS = D.getDeclSpec();
11202
11203 assert(DS.isFriendSpecified());
11204 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11205
11206 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011207 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011208
11209 // C++ [class.friend]p1
11210 // A friend of a class is a function or class....
11211 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011212 // It *doesn't* see through dependent types, which is correct
11213 // according to [temp.arg.type]p3:
11214 // If a declaration acquires a function type through a
11215 // type dependent on a template-parameter and this causes
11216 // a declaration that does not use the syntactic form of a
11217 // function declarator to have a function type, the program
11218 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011219 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011220 Diag(Loc, diag::err_unexpected_friend);
11221
11222 // It might be worthwhile to try to recover by creating an
11223 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011224 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011225 }
11226
11227 // C++ [namespace.memdef]p3
11228 // - If a friend declaration in a non-local class first declares a
11229 // class or function, the friend class or function is a member
11230 // of the innermost enclosing namespace.
11231 // - The name of the friend is not found by simple name lookup
11232 // until a matching declaration is provided in that namespace
11233 // scope (either before or after the class declaration granting
11234 // friendship).
11235 // - If a friend function is called, its name may be found by the
11236 // name lookup that considers functions from namespaces and
11237 // classes associated with the types of the function arguments.
11238 // - When looking for a prior declaration of a class or a function
11239 // declared as a friend, scopes outside the innermost enclosing
11240 // namespace scope are not considered.
11241
John McCall337ec3d2010-10-12 23:13:28 +000011242 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011243 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11244 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011245 assert(Name);
11246
Douglas Gregor6ccab972010-12-16 01:14:37 +000011247 // Check for unexpanded parameter packs.
11248 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11249 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11250 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11251 return 0;
11252
John McCall67d1a672009-08-06 02:15:43 +000011253 // The context we found the declaration in, or in which we should
11254 // create the declaration.
11255 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011256 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011257 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011258 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011259
John McCall337ec3d2010-10-12 23:13:28 +000011260 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011261
John McCall337ec3d2010-10-12 23:13:28 +000011262 // There are four cases here.
11263 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011264 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011265 // there as appropriate.
11266 // Recover from invalid scope qualifiers as if they just weren't there.
11267 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011268 // C++0x [namespace.memdef]p3:
11269 // If the name in a friend declaration is neither qualified nor
11270 // a template-id and the declaration is a function or an
11271 // elaborated-type-specifier, the lookup to determine whether
11272 // the entity has been previously declared shall not consider
11273 // any scopes outside the innermost enclosing namespace.
11274 // C++0x [class.friend]p11:
11275 // If a friend declaration appears in a local class and the name
11276 // specified is an unqualified name, a prior declaration is
11277 // looked up without considering scopes that are outside the
11278 // innermost enclosing non-class scope. For a friend function
11279 // declaration, if there is no prior declaration, the program is
11280 // ill-formed.
11281 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011282 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011283
John McCall29ae6e52010-10-13 05:45:15 +000011284 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011285 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011286
Rafael Espindola11dc6342013-04-25 20:12:36 +000011287 // Skip class contexts. If someone can cite chapter and verse
11288 // for this behavior, that would be nice --- it's what GCC and
11289 // EDG do, and it seems like a reasonable intent, but the spec
11290 // really only says that checks for unqualified existing
11291 // declarations should stop at the nearest enclosing namespace,
11292 // not that they should only consider the nearest enclosing
11293 // namespace.
11294 while (DC->isRecord())
11295 DC = DC->getParent();
11296
11297 DeclContext *LookupDC = DC;
11298 while (LookupDC->isTransparentContext())
11299 LookupDC = LookupDC->getParent();
11300
11301 while (true) {
11302 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011303
11304 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011305 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011306 break;
John McCall29ae6e52010-10-13 05:45:15 +000011307
Rafael Espindola11dc6342013-04-25 20:12:36 +000011308 if (!Previous.empty()) {
11309 DC = LookupDC;
11310 break;
John McCall8a407372010-10-14 22:22:28 +000011311 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011312
11313 if (isTemplateId) {
11314 if (isa<TranslationUnitDecl>(LookupDC)) break;
11315 } else {
11316 if (LookupDC->isFileContext()) break;
11317 }
11318 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011319 }
11320
John McCall380aaa42010-10-13 06:22:15 +000011321 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011322
Douglas Gregor883af832011-10-10 01:11:59 +000011323 // C++ [class.friend]p6:
11324 // A function can be defined in a friend declaration of a class if and
11325 // only if the class is a non-local class (9.8), the function name is
11326 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011327 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011328 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11329 }
11330
John McCall337ec3d2010-10-12 23:13:28 +000011331 // - There's a non-dependent scope specifier, in which case we
11332 // compute it and do a previous lookup there for a function
11333 // or function template.
11334 } else if (!SS.getScopeRep()->isDependent()) {
11335 DC = computeDeclContext(SS);
11336 if (!DC) return 0;
11337
11338 if (RequireCompleteDeclContext(SS, DC)) return 0;
11339
11340 LookupQualifiedName(Previous, DC);
11341
11342 // Ignore things found implicitly in the wrong scope.
11343 // TODO: better diagnostics for this case. Suggesting the right
11344 // qualified scope would be nice...
11345 LookupResult::Filter F = Previous.makeFilter();
11346 while (F.hasNext()) {
11347 NamedDecl *D = F.next();
11348 if (!DC->InEnclosingNamespaceSetOf(
11349 D->getDeclContext()->getRedeclContext()))
11350 F.erase();
11351 }
11352 F.done();
11353
11354 if (Previous.empty()) {
11355 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011356 Diag(Loc, diag::err_qualified_friend_not_found)
11357 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011358 return 0;
11359 }
11360
11361 // C++ [class.friend]p1: A friend of a class is a function or
11362 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011363 if (DC->Equals(CurContext))
11364 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011365 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011366 diag::warn_cxx98_compat_friend_is_member :
11367 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011368
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011369 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011370 // C++ [class.friend]p6:
11371 // A function can be defined in a friend declaration of a class if and
11372 // only if the class is a non-local class (9.8), the function name is
11373 // unqualified, and the function has namespace scope.
11374 SemaDiagnosticBuilder DB
11375 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11376
11377 DB << SS.getScopeRep();
11378 if (DC->isFileContext())
11379 DB << FixItHint::CreateRemoval(SS.getRange());
11380 SS.clear();
11381 }
John McCall337ec3d2010-10-12 23:13:28 +000011382
11383 // - There's a scope specifier that does not match any template
11384 // parameter lists, in which case we use some arbitrary context,
11385 // create a method or method template, and wait for instantiation.
11386 // - There's a scope specifier that does match some template
11387 // parameter lists, which we don't handle right now.
11388 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011389 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011390 // C++ [class.friend]p6:
11391 // A function can be defined in a friend declaration of a class if and
11392 // only if the class is a non-local class (9.8), the function name is
11393 // unqualified, and the function has namespace scope.
11394 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11395 << SS.getScopeRep();
11396 }
11397
John McCall337ec3d2010-10-12 23:13:28 +000011398 DC = CurContext;
11399 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011400 }
Douglas Gregor883af832011-10-10 01:11:59 +000011401
John McCall29ae6e52010-10-13 05:45:15 +000011402 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011403 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011404 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11405 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11406 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011407 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011408 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11409 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011410 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011411 }
John McCall67d1a672009-08-06 02:15:43 +000011412 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011413
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011414 // FIXME: This is an egregious hack to cope with cases where the scope stack
11415 // does not contain the declaration context, i.e., in an out-of-line
11416 // definition of a class.
11417 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11418 if (!DCScope) {
11419 FakeDCScope.setEntity(DC);
11420 DCScope = &FakeDCScope;
11421 }
11422
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011423 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011424 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011425 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011426 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011427
Douglas Gregor182ddf02009-09-28 00:08:27 +000011428 assert(ND->getDeclContext() == DC);
11429 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011430
John McCallab88d972009-08-31 22:39:49 +000011431 // Add the function declaration to the appropriate lookup tables,
11432 // adjusting the redeclarations list as necessary. We don't
11433 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011434 //
John McCallab88d972009-08-31 22:39:49 +000011435 // Also update the scope-based lookup if the target context's
11436 // lookup context is in lexical scope.
11437 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011438 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011439 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011440 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011441 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011442 }
John McCall02cace72009-08-28 07:59:38 +000011443
11444 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011445 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011446 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011447 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011448 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011449
John McCall1f2e1a92012-08-10 03:15:35 +000011450 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011451 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011452 } else {
11453 if (DC->isRecord()) CheckFriendAccess(ND);
11454
John McCall6102ca12010-10-16 06:59:13 +000011455 FunctionDecl *FD;
11456 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11457 FD = FTD->getTemplatedDecl();
11458 else
11459 FD = cast<FunctionDecl>(ND);
11460
David Majnemerf6a144f2013-06-25 23:09:30 +000011461 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11462 // default argument expression, that declaration shall be a definition
11463 // and shall be the only declaration of the function or function
11464 // template in the translation unit.
11465 if (functionDeclHasDefaultArgument(FD)) {
11466 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11467 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11468 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11469 } else if (!D.isFunctionDefinition())
11470 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11471 }
11472
John McCall6102ca12010-10-16 06:59:13 +000011473 // Mark templated-scope function declarations as unsupported.
11474 if (FD->getNumTemplateParameterLists())
11475 FrD->setUnsupportedFriend(true);
11476 }
John McCall337ec3d2010-10-12 23:13:28 +000011477
John McCalld226f652010-08-21 09:40:31 +000011478 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011479}
11480
John McCalld226f652010-08-21 09:40:31 +000011481void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11482 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011483
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011484 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011485 if (!Fn) {
11486 Diag(DelLoc, diag::err_deleted_non_function);
11487 return;
11488 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011489
Douglas Gregoref96ee02012-01-14 16:38:05 +000011490 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011491 // Don't consider the implicit declaration we generate for explicit
11492 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011493 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11494 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011495 Diag(DelLoc, diag::err_deleted_decl_not_first);
11496 Diag(Prev->getLocation(), diag::note_previous_declaration);
11497 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011498 // If the declaration wasn't the first, we delete the function anyway for
11499 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011500 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011501 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011502
11503 if (Fn->isDeleted())
11504 return;
11505
11506 // See if we're deleting a function which is already known to override a
11507 // non-deleted virtual function.
11508 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11509 bool IssuedDiagnostic = false;
11510 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11511 E = MD->end_overridden_methods();
11512 I != E; ++I) {
11513 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11514 if (!IssuedDiagnostic) {
11515 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11516 IssuedDiagnostic = true;
11517 }
11518 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11519 }
11520 }
11521 }
11522
Sean Hunt10620eb2011-05-06 20:44:56 +000011523 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011524}
Sebastian Redl13e88542009-04-27 21:33:24 +000011525
Sean Hunte4246a62011-05-12 06:15:49 +000011526void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011527 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011528
11529 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011530 if (MD->getParent()->isDependentType()) {
11531 MD->setDefaulted();
11532 MD->setExplicitlyDefaulted();
11533 return;
11534 }
11535
Sean Hunte4246a62011-05-12 06:15:49 +000011536 CXXSpecialMember Member = getSpecialMember(MD);
11537 if (Member == CXXInvalid) {
11538 Diag(DefaultLoc, diag::err_default_special_members);
11539 return;
11540 }
11541
11542 MD->setDefaulted();
11543 MD->setExplicitlyDefaulted();
11544
Sean Huntcd10dec2011-05-23 23:14:04 +000011545 // If this definition appears within the record, do the checking when
11546 // the record is complete.
11547 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011548 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011549 // Find the uninstantiated declaration that actually had the '= default'
11550 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011551 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011552
Richard Smith12fef492013-03-27 00:22:47 +000011553 // If the method was defaulted on its first declaration, we will have
11554 // already performed the checking in CheckCompletedCXXClass. Such a
11555 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011556 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011557 return;
11558
Richard Smithb9d0b762012-07-27 04:22:15 +000011559 CheckExplicitlyDefaultedSpecialMember(MD);
11560
Richard Smith1d28caf2012-12-11 01:14:52 +000011561 // The exception specification is needed because we are defining the
11562 // function.
11563 ResolveExceptionSpec(DefaultLoc,
11564 MD->getType()->castAs<FunctionProtoType>());
11565
Sean Hunte4246a62011-05-12 06:15:49 +000011566 switch (Member) {
11567 case CXXDefaultConstructor: {
11568 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011569 if (!CD->isInvalidDecl())
11570 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11571 break;
11572 }
11573
11574 case CXXCopyConstructor: {
11575 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011576 if (!CD->isInvalidDecl())
11577 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011578 break;
11579 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011580
Sean Hunt2b188082011-05-14 05:23:28 +000011581 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011582 if (!MD->isInvalidDecl())
11583 DefineImplicitCopyAssignment(DefaultLoc, MD);
11584 break;
11585 }
11586
Sean Huntcb45a0f2011-05-12 22:46:25 +000011587 case CXXDestructor: {
11588 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011589 if (!DD->isInvalidDecl())
11590 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011591 break;
11592 }
11593
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011594 case CXXMoveConstructor: {
11595 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011596 if (!CD->isInvalidDecl())
11597 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011598 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011599 }
Sean Hunt82713172011-05-25 23:16:36 +000011600
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011601 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011602 if (!MD->isInvalidDecl())
11603 DefineImplicitMoveAssignment(DefaultLoc, MD);
11604 break;
11605 }
11606
11607 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011608 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011609 }
11610 } else {
11611 Diag(DefaultLoc, diag::err_default_special_members);
11612 }
11613}
11614
Sebastian Redl13e88542009-04-27 21:33:24 +000011615static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011616 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011617 Stmt *SubStmt = *CI;
11618 if (!SubStmt)
11619 continue;
11620 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011621 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011622 diag::err_return_in_constructor_handler);
11623 if (!isa<Expr>(SubStmt))
11624 SearchForReturnInStmt(Self, SubStmt);
11625 }
11626}
11627
11628void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11629 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11630 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11631 SearchForReturnInStmt(*this, Handler);
11632 }
11633}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011634
David Blaikie299adab2013-01-18 23:03:15 +000011635bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011636 const CXXMethodDecl *Old) {
11637 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11638 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11639
11640 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11641
11642 // If the calling conventions match, everything is fine
11643 if (NewCC == OldCC)
11644 return false;
11645
11646 // If either of the calling conventions are set to "default", we need to pick
11647 // something more sensible based on the target. This supports code where the
11648 // one method explicitly sets thiscall, and another has no explicit calling
11649 // convention.
11650 CallingConv Default =
11651 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11652 if (NewCC == CC_Default)
11653 NewCC = Default;
11654 if (OldCC == CC_Default)
11655 OldCC = Default;
11656
11657 // If the calling conventions still don't match, then report the error
11658 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011659 Diag(New->getLocation(),
11660 diag::err_conflicting_overriding_cc_attributes)
11661 << New->getDeclName() << New->getType() << Old->getType();
11662 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11663 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011664 }
11665
11666 return false;
11667}
11668
Mike Stump1eb44332009-09-09 15:08:12 +000011669bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011670 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011671 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11672 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011673
Chandler Carruth73857792010-02-15 11:53:20 +000011674 if (Context.hasSameType(NewTy, OldTy) ||
11675 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011676 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011677
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011678 // Check if the return types are covariant
11679 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011680
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011681 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011682 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11683 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011684 NewClassTy = NewPT->getPointeeType();
11685 OldClassTy = OldPT->getPointeeType();
11686 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011687 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11688 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11689 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11690 NewClassTy = NewRT->getPointeeType();
11691 OldClassTy = OldRT->getPointeeType();
11692 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011693 }
11694 }
Mike Stump1eb44332009-09-09 15:08:12 +000011695
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011696 // The return types aren't either both pointers or references to a class type.
11697 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011698 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011699 diag::err_different_return_type_for_overriding_virtual_function)
11700 << New->getDeclName() << NewTy << OldTy;
11701 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011702
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011703 return true;
11704 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011705
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011706 // C++ [class.virtual]p6:
11707 // If the return type of D::f differs from the return type of B::f, the
11708 // class type in the return type of D::f shall be complete at the point of
11709 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011710 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11711 if (!RT->isBeingDefined() &&
11712 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011713 diag::err_covariant_return_incomplete,
11714 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011715 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011716 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011717
Douglas Gregora4923eb2009-11-16 21:35:15 +000011718 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011719 // Check if the new class derives from the old class.
11720 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11721 Diag(New->getLocation(),
11722 diag::err_covariant_return_not_derived)
11723 << New->getDeclName() << NewTy << OldTy;
11724 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11725 return true;
11726 }
Mike Stump1eb44332009-09-09 15:08:12 +000011727
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011728 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011729 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011730 diag::err_covariant_return_inaccessible_base,
11731 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11732 // FIXME: Should this point to the return type?
11733 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011734 // FIXME: this note won't trigger for delayed access control
11735 // diagnostics, and it's impossible to get an undelayed error
11736 // here from access control during the original parse because
11737 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011738 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11739 return true;
11740 }
11741 }
Mike Stump1eb44332009-09-09 15:08:12 +000011742
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011743 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011744 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011745 Diag(New->getLocation(),
11746 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011747 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011748 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11749 return true;
11750 };
Mike Stump1eb44332009-09-09 15:08:12 +000011751
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011752
11753 // The new class type must have the same or less qualifiers as the old type.
11754 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11755 Diag(New->getLocation(),
11756 diag::err_covariant_return_type_class_type_more_qualified)
11757 << New->getDeclName() << NewTy << OldTy;
11758 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11759 return true;
11760 };
Mike Stump1eb44332009-09-09 15:08:12 +000011761
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011762 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011763}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011764
Douglas Gregor4ba31362009-12-01 17:24:26 +000011765/// \brief Mark the given method pure.
11766///
11767/// \param Method the method to be marked pure.
11768///
11769/// \param InitRange the source range that covers the "0" initializer.
11770bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011771 SourceLocation EndLoc = InitRange.getEnd();
11772 if (EndLoc.isValid())
11773 Method->setRangeEnd(EndLoc);
11774
Douglas Gregor4ba31362009-12-01 17:24:26 +000011775 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11776 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011777 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011778 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011779
11780 if (!Method->isInvalidDecl())
11781 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11782 << Method->getDeclName() << InitRange;
11783 return true;
11784}
11785
Douglas Gregor552e2992012-02-21 02:22:07 +000011786/// \brief Determine whether the given declaration is a static data member.
11787static bool isStaticDataMember(Decl *D) {
11788 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11789 if (!Var)
11790 return false;
11791
11792 return Var->isStaticDataMember();
11793}
John McCall731ad842009-12-19 09:28:58 +000011794/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11795/// an initializer for the out-of-line declaration 'Dcl'. The scope
11796/// is a fresh scope pushed for just this purpose.
11797///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011798/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11799/// static data member of class X, names should be looked up in the scope of
11800/// class X.
John McCalld226f652010-08-21 09:40:31 +000011801void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011802 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011803 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011804
John McCall731ad842009-12-19 09:28:58 +000011805 // We should only get called for declarations with scope specifiers, like:
11806 // int foo::bar;
11807 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011808 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011809
11810 // If we are parsing the initializer for a static data member, push a
11811 // new expression evaluation context that is associated with this static
11812 // data member.
11813 if (isStaticDataMember(D))
11814 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011815}
11816
11817/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011818/// initializer for the out-of-line declaration 'D'.
11819void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011820 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011821 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011822
Douglas Gregor552e2992012-02-21 02:22:07 +000011823 if (isStaticDataMember(D))
11824 PopExpressionEvaluationContext();
11825
John McCall731ad842009-12-19 09:28:58 +000011826 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011827 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011828}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011829
11830/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11831/// C++ if/switch/while/for statement.
11832/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011833DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011834 // C++ 6.4p2:
11835 // The declarator shall not specify a function or an array.
11836 // The type-specifier-seq shall not contain typedef and shall not declare a
11837 // new class or enumeration.
11838 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11839 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011840
11841 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011842 if (!Dcl)
11843 return true;
11844
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011845 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11846 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011847 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011848 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011849 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011850
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011851 return Dcl;
11852}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011853
Douglas Gregordfe65432011-07-28 19:11:31 +000011854void Sema::LoadExternalVTableUses() {
11855 if (!ExternalSource)
11856 return;
11857
11858 SmallVector<ExternalVTableUse, 4> VTables;
11859 ExternalSource->ReadUsedVTables(VTables);
11860 SmallVector<VTableUse, 4> NewUses;
11861 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11862 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11863 = VTablesUsed.find(VTables[I].Record);
11864 // Even if a definition wasn't required before, it may be required now.
11865 if (Pos != VTablesUsed.end()) {
11866 if (!Pos->second && VTables[I].DefinitionRequired)
11867 Pos->second = true;
11868 continue;
11869 }
11870
11871 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11872 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11873 }
11874
11875 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11876}
11877
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011878void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11879 bool DefinitionRequired) {
11880 // Ignore any vtable uses in unevaluated operands or for classes that do
11881 // not have a vtable.
11882 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011883 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011884 return;
11885
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011886 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011887 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011888 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11889 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11890 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11891 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011892 // If we already had an entry, check to see if we are promoting this vtable
11893 // to required a definition. If so, we need to reappend to the VTableUses
11894 // list, since we may have already processed the first entry.
11895 if (DefinitionRequired && !Pos.first->second) {
11896 Pos.first->second = true;
11897 } else {
11898 // Otherwise, we can early exit.
11899 return;
11900 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011901 }
11902
11903 // Local classes need to have their virtual members marked
11904 // immediately. For all other classes, we mark their virtual members
11905 // at the end of the translation unit.
11906 if (Class->isLocalClass())
11907 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011908 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011909 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011910}
11911
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011912bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011913 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011914 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011915 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011916
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011917 // Note: The VTableUses vector could grow as a result of marking
11918 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011919 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011920 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011921 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011922 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011923 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011924 if (!Class)
11925 continue;
11926
11927 SourceLocation Loc = VTableUses[I].second;
11928
Richard Smithb9d0b762012-07-27 04:22:15 +000011929 bool DefineVTable = true;
11930
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011931 // If this class has a key function, but that key function is
11932 // defined in another translation unit, we don't need to emit the
11933 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011934 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011935 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011936 switch (KeyFunction->getTemplateSpecializationKind()) {
11937 case TSK_Undeclared:
11938 case TSK_ExplicitSpecialization:
11939 case TSK_ExplicitInstantiationDeclaration:
11940 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011941 DefineVTable = false;
11942 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011943
11944 case TSK_ExplicitInstantiationDefinition:
11945 case TSK_ImplicitInstantiation:
11946 // We will be instantiating the key function.
11947 break;
11948 }
11949 } else if (!KeyFunction) {
11950 // If we have a class with no key function that is the subject
11951 // of an explicit instantiation declaration, suppress the
11952 // vtable; it will live with the explicit instantiation
11953 // definition.
11954 bool IsExplicitInstantiationDeclaration
11955 = Class->getTemplateSpecializationKind()
11956 == TSK_ExplicitInstantiationDeclaration;
11957 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11958 REnd = Class->redecls_end();
11959 R != REnd; ++R) {
11960 TemplateSpecializationKind TSK
11961 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11962 if (TSK == TSK_ExplicitInstantiationDeclaration)
11963 IsExplicitInstantiationDeclaration = true;
11964 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11965 IsExplicitInstantiationDeclaration = false;
11966 break;
11967 }
11968 }
11969
11970 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011971 DefineVTable = false;
11972 }
11973
11974 // The exception specifications for all virtual members may be needed even
11975 // if we are not providing an authoritative form of the vtable in this TU.
11976 // We may choose to emit it available_externally anyway.
11977 if (!DefineVTable) {
11978 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11979 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011980 }
11981
11982 // Mark all of the virtual members of this class as referenced, so
11983 // that we can build a vtable. Then, tell the AST consumer that a
11984 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011985 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011986 MarkVirtualMembersReferenced(Loc, Class);
11987 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11988 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11989
11990 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000011991 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011992 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011993 const FunctionDecl *KeyFunctionDef = 0;
11994 if (!KeyFunction ||
11995 (KeyFunction->hasBody(KeyFunctionDef) &&
11996 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011997 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11998 TSK_ExplicitInstantiationDefinition
11999 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12000 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012001 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012002 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012003 VTableUses.clear();
12004
Douglas Gregor78844032011-04-22 22:25:37 +000012005 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012006}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012007
Richard Smithb9d0b762012-07-27 04:22:15 +000012008void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12009 const CXXRecordDecl *RD) {
12010 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12011 E = RD->method_end(); I != E; ++I)
12012 if ((*I)->isVirtual() && !(*I)->isPure())
12013 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12014}
12015
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012016void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12017 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012018 // Mark all functions which will appear in RD's vtable as used.
12019 CXXFinalOverriderMap FinalOverriders;
12020 RD->getFinalOverriders(FinalOverriders);
12021 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12022 E = FinalOverriders.end();
12023 I != E; ++I) {
12024 for (OverridingMethods::const_iterator OI = I->second.begin(),
12025 OE = I->second.end();
12026 OI != OE; ++OI) {
12027 assert(OI->second.size() > 0 && "no final overrider");
12028 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012029
Richard Smithff817f72012-07-07 06:59:51 +000012030 // C++ [basic.def.odr]p2:
12031 // [...] A virtual member function is used if it is not pure. [...]
12032 if (!Overrider->isPure())
12033 MarkFunctionReferenced(Loc, Overrider);
12034 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012035 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012036
12037 // Only classes that have virtual bases need a VTT.
12038 if (RD->getNumVBases() == 0)
12039 return;
12040
12041 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12042 e = RD->bases_end(); i != e; ++i) {
12043 const CXXRecordDecl *Base =
12044 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012045 if (Base->getNumVBases() == 0)
12046 continue;
12047 MarkVirtualMembersReferenced(Loc, Base);
12048 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012049}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012050
12051/// SetIvarInitializers - This routine builds initialization ASTs for the
12052/// Objective-C implementation whose ivars need be initialized.
12053void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012054 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012055 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012056 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012057 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012058 CollectIvarsToConstructOrDestruct(OID, ivars);
12059 if (ivars.empty())
12060 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012061 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012062 for (unsigned i = 0; i < ivars.size(); i++) {
12063 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012064 if (Field->isInvalidDecl())
12065 continue;
12066
Sean Huntcbb67482011-01-08 20:30:50 +000012067 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012068 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12069 InitializationKind InitKind =
12070 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012071
12072 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12073 ExprResult MemberInit =
12074 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012075 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012076 // Note, MemberInit could actually come back empty if no initialization
12077 // is required (e.g., because it would call a trivial default constructor)
12078 if (!MemberInit.get() || MemberInit.isInvalid())
12079 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012080
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012081 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012082 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12083 SourceLocation(),
12084 MemberInit.takeAs<Expr>(),
12085 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012086 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012087
12088 // Be sure that the destructor is accessible and is marked as referenced.
12089 if (const RecordType *RecordTy
12090 = Context.getBaseElementType(Field->getType())
12091 ->getAs<RecordType>()) {
12092 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012093 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012094 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012095 CheckDestructorAccess(Field->getLocation(), Destructor,
12096 PDiag(diag::err_access_dtor_ivar)
12097 << Context.getBaseElementType(Field->getType()));
12098 }
12099 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012100 }
12101 ObjCImplementation->setIvarInitializers(Context,
12102 AllToInit.data(), AllToInit.size());
12103 }
12104}
Sean Huntfe57eef2011-05-04 05:57:24 +000012105
Sean Huntebcbe1d2011-05-04 23:29:54 +000012106static
12107void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12108 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12109 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12110 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12111 Sema &S) {
12112 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12113 CE = Current.end();
12114 if (Ctor->isInvalidDecl())
12115 return;
12116
Richard Smitha8eaf002012-08-23 06:16:52 +000012117 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12118
12119 // Target may not be determinable yet, for instance if this is a dependent
12120 // call in an uninstantiated template.
12121 if (Target) {
12122 const FunctionDecl *FNTarget = 0;
12123 (void)Target->hasBody(FNTarget);
12124 Target = const_cast<CXXConstructorDecl*>(
12125 cast_or_null<CXXConstructorDecl>(FNTarget));
12126 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012127
12128 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12129 // Avoid dereferencing a null pointer here.
12130 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12131
12132 if (!Current.insert(Canonical))
12133 return;
12134
12135 // We know that beyond here, we aren't chaining into a cycle.
12136 if (!Target || !Target->isDelegatingConstructor() ||
12137 Target->isInvalidDecl() || Valid.count(TCanonical)) {
12138 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12139 Valid.insert(*CI);
12140 Current.clear();
12141 // We've hit a cycle.
12142 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12143 Current.count(TCanonical)) {
12144 // If we haven't diagnosed this cycle yet, do so now.
12145 if (!Invalid.count(TCanonical)) {
12146 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012147 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012148 << Ctor;
12149
Richard Smitha8eaf002012-08-23 06:16:52 +000012150 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012151 if (TCanonical != Canonical)
12152 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12153
12154 CXXConstructorDecl *C = Target;
12155 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012156 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012157 (void)C->getTargetConstructor()->hasBody(FNTarget);
12158 assert(FNTarget && "Ctor cycle through bodiless function");
12159
Richard Smitha8eaf002012-08-23 06:16:52 +000012160 C = const_cast<CXXConstructorDecl*>(
12161 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012162 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12163 }
12164 }
12165
12166 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12167 Invalid.insert(*CI);
12168 Current.clear();
12169 } else {
12170 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12171 }
12172}
12173
12174
Sean Huntfe57eef2011-05-04 05:57:24 +000012175void Sema::CheckDelegatingCtorCycles() {
12176 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12177
Sean Huntebcbe1d2011-05-04 23:29:54 +000012178 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12179 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000012180
Douglas Gregor0129b562011-07-27 21:57:17 +000012181 for (DelegatingCtorDeclsType::iterator
12182 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012183 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012184 I != E; ++I)
12185 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012186
12187 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12188 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012189}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012190
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012191namespace {
12192 /// \brief AST visitor that finds references to the 'this' expression.
12193 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12194 Sema &S;
12195
12196 public:
12197 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12198
12199 bool VisitCXXThisExpr(CXXThisExpr *E) {
12200 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12201 << E->isImplicit();
12202 return false;
12203 }
12204 };
12205}
12206
12207bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12208 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12209 if (!TSInfo)
12210 return false;
12211
12212 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012213 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012214 if (!ProtoTL)
12215 return false;
12216
12217 // C++11 [expr.prim.general]p3:
12218 // [The expression this] shall not appear before the optional
12219 // cv-qualifier-seq and it shall not appear within the declaration of a
12220 // static member function (although its type and value category are defined
12221 // within a static member function as they are within a non-static member
12222 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012223 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012224 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012225 FindCXXThisExpr Finder(*this);
12226
12227 // If the return type came after the cv-qualifier-seq, check it now.
12228 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012229 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012230 return true;
12231
12232 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012233 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12234 return true;
12235
12236 return checkThisInStaticMemberFunctionAttributes(Method);
12237}
12238
12239bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12240 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12241 if (!TSInfo)
12242 return false;
12243
12244 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012245 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012246 if (!ProtoTL)
12247 return false;
12248
David Blaikie39e6ab42013-02-18 22:06:02 +000012249 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012250 FindCXXThisExpr Finder(*this);
12251
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012252 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012253 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012254 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012255 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012256 case EST_DynamicNone:
12257 case EST_MSAny:
12258 case EST_None:
12259 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012260
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012261 case EST_ComputedNoexcept:
12262 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12263 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012264
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012265 case EST_Dynamic:
12266 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012267 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012268 E != EEnd; ++E) {
12269 if (!Finder.TraverseType(*E))
12270 return true;
12271 }
12272 break;
12273 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012274
12275 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012276}
12277
12278bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12279 FindCXXThisExpr Finder(*this);
12280
12281 // Check attributes.
12282 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12283 A != AEnd; ++A) {
12284 // FIXME: This should be emitted by tblgen.
12285 Expr *Arg = 0;
12286 ArrayRef<Expr *> Args;
12287 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12288 Arg = G->getArg();
12289 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12290 Arg = G->getArg();
12291 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12292 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12293 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12294 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12295 else if (ExclusiveLockFunctionAttr *ELF
12296 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12297 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12298 else if (SharedLockFunctionAttr *SLF
12299 = dyn_cast<SharedLockFunctionAttr>(*A))
12300 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12301 else if (ExclusiveTrylockFunctionAttr *ETLF
12302 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12303 Arg = ETLF->getSuccessValue();
12304 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12305 } else if (SharedTrylockFunctionAttr *STLF
12306 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12307 Arg = STLF->getSuccessValue();
12308 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12309 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12310 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12311 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12312 Arg = LR->getArg();
12313 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12314 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12315 else if (ExclusiveLocksRequiredAttr *ELR
12316 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12317 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12318 else if (SharedLocksRequiredAttr *SLR
12319 = dyn_cast<SharedLocksRequiredAttr>(*A))
12320 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12321
12322 if (Arg && !Finder.TraverseStmt(Arg))
12323 return true;
12324
12325 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12326 if (!Finder.TraverseStmt(Args[I]))
12327 return true;
12328 }
12329 }
12330
12331 return false;
12332}
12333
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012334void
12335Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12336 ArrayRef<ParsedType> DynamicExceptions,
12337 ArrayRef<SourceRange> DynamicExceptionRanges,
12338 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012339 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012340 FunctionProtoType::ExtProtoInfo &EPI) {
12341 Exceptions.clear();
12342 EPI.ExceptionSpecType = EST;
12343 if (EST == EST_Dynamic) {
12344 Exceptions.reserve(DynamicExceptions.size());
12345 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12346 // FIXME: Preserve type source info.
12347 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12348
12349 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12350 collectUnexpandedParameterPacks(ET, Unexpanded);
12351 if (!Unexpanded.empty()) {
12352 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12353 UPPC_ExceptionType,
12354 Unexpanded);
12355 continue;
12356 }
12357
12358 // Check that the type is valid for an exception spec, and
12359 // drop it if not.
12360 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12361 Exceptions.push_back(ET);
12362 }
12363 EPI.NumExceptions = Exceptions.size();
12364 EPI.Exceptions = Exceptions.data();
12365 return;
12366 }
12367
12368 if (EST == EST_ComputedNoexcept) {
12369 // If an error occurred, there's no expression here.
12370 if (NoexceptExpr) {
12371 assert((NoexceptExpr->isTypeDependent() ||
12372 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12373 Context.BoolTy) &&
12374 "Parser should have made sure that the expression is boolean");
12375 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12376 EPI.ExceptionSpecType = EST_BasicNoexcept;
12377 return;
12378 }
12379
12380 if (!NoexceptExpr->isValueDependent())
12381 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012382 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012383 /*AllowFold*/ false).take();
12384 EPI.NoexceptExpr = NoexceptExpr;
12385 }
12386 return;
12387 }
12388}
12389
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012390/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12391Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12392 // Implicitly declared functions (e.g. copy constructors) are
12393 // __host__ __device__
12394 if (D->isImplicit())
12395 return CFT_HostDevice;
12396
12397 if (D->hasAttr<CUDAGlobalAttr>())
12398 return CFT_Global;
12399
12400 if (D->hasAttr<CUDADeviceAttr>()) {
12401 if (D->hasAttr<CUDAHostAttr>())
12402 return CFT_HostDevice;
12403 else
12404 return CFT_Device;
12405 }
12406
12407 return CFT_Host;
12408}
12409
12410bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12411 CUDAFunctionTarget CalleeTarget) {
12412 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12413 // Callable from the device only."
12414 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12415 return true;
12416
12417 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12418 // Callable from the host only."
12419 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12420 // Callable from the host only."
12421 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12422 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12423 return true;
12424
12425 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12426 return true;
12427
12428 return false;
12429}
John McCall76da55d2013-04-16 07:28:30 +000012430
12431/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12432///
12433MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12434 SourceLocation DeclStart,
12435 Declarator &D, Expr *BitWidth,
12436 InClassInitStyle InitStyle,
12437 AccessSpecifier AS,
12438 AttributeList *MSPropertyAttr) {
12439 IdentifierInfo *II = D.getIdentifier();
12440 if (!II) {
12441 Diag(DeclStart, diag::err_anonymous_property);
12442 return NULL;
12443 }
12444 SourceLocation Loc = D.getIdentifierLoc();
12445
12446 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12447 QualType T = TInfo->getType();
12448 if (getLangOpts().CPlusPlus) {
12449 CheckExtraCXXDefaultArguments(D);
12450
12451 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12452 UPPC_DataMemberType)) {
12453 D.setInvalidType();
12454 T = Context.IntTy;
12455 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12456 }
12457 }
12458
12459 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12460
12461 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12462 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12463 diag::err_invalid_thread)
12464 << DeclSpec::getSpecifierName(TSCS);
12465
12466 // Check to see if this name was declared as a member previously
12467 NamedDecl *PrevDecl = 0;
12468 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12469 LookupName(Previous, S);
12470 switch (Previous.getResultKind()) {
12471 case LookupResult::Found:
12472 case LookupResult::FoundUnresolvedValue:
12473 PrevDecl = Previous.getAsSingle<NamedDecl>();
12474 break;
12475
12476 case LookupResult::FoundOverloaded:
12477 PrevDecl = Previous.getRepresentativeDecl();
12478 break;
12479
12480 case LookupResult::NotFound:
12481 case LookupResult::NotFoundInCurrentInstantiation:
12482 case LookupResult::Ambiguous:
12483 break;
12484 }
12485
12486 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12487 // Maybe we will complain about the shadowed template parameter.
12488 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12489 // Just pretend that we didn't see the previous declaration.
12490 PrevDecl = 0;
12491 }
12492
12493 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12494 PrevDecl = 0;
12495
12496 SourceLocation TSSL = D.getLocStart();
12497 MSPropertyDecl *NewPD;
12498 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12499 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12500 II, T, TInfo, TSSL,
12501 Data.GetterId, Data.SetterId);
12502 ProcessDeclAttributes(TUScope, NewPD, D);
12503 NewPD->setAccess(AS);
12504
12505 if (NewPD->isInvalidDecl())
12506 Record->setInvalidDecl();
12507
12508 if (D.getDeclSpec().isModulePrivateSpecified())
12509 NewPD->setModulePrivate();
12510
12511 if (NewPD->isInvalidDecl() && PrevDecl) {
12512 // Don't introduce NewFD into scope; there's already something
12513 // with the same name in the same scope.
12514 } else if (II) {
12515 PushOnScopeChains(NewPD, S);
12516 } else
12517 Record->addDecl(NewPD);
12518
12519 return NewPD;
12520}