blob: dc33f2faf657ef8c88f853b50fca00b8c3be16cd [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Richard Smith4ac537b2013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000040#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000041#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000042#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000043
44using namespace clang;
45
Chris Lattner8123a952008-04-10 02:22:51 +000046//===----------------------------------------------------------------------===//
47// CheckDefaultArgumentVisitor
48//===----------------------------------------------------------------------===//
49
Chris Lattner9e979552008-04-12 23:52:44 +000050namespace {
51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
52 /// the default argument of a parameter to determine whether it
53 /// contains any ill-formed subexpressions. For example, this will
54 /// diagnose the use of local variables or parameters within the
55 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000056 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000057 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000058 Expr *DefaultArg;
59 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000060
Chris Lattner9e979552008-04-12 23:52:44 +000061 public:
Mike Stump1eb44332009-09-09 15:08:12 +000062 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000063 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 bool VisitExpr(Expr *Node);
66 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000067 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000068 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000069 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000070 };
Chris Lattner8123a952008-04-10 02:22:51 +000071
Chris Lattner9e979552008-04-12 23:52:44 +000072 /// VisitExpr - Visit all of the children of this expression.
73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
74 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000075 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000076 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000077 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000078 }
79
Chris Lattner9e979552008-04-12 23:52:44 +000080 /// VisitDeclRefExpr - Visit a reference to a declaration, to
81 /// determine whether this declaration can be used in the default
82 /// argument expression.
83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000084 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000085 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
86 // C++ [dcl.fct.default]p9
87 // Default arguments are evaluated each time the function is
88 // called. The order of evaluation of function arguments is
89 // unspecified. Consequently, parameters of a function shall not
90 // be used in default argument expressions, even if they are not
91 // evaluated. Parameters of a function declared before a default
92 // argument expression are in scope and can hide namespace and
93 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000094 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000097 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000098 // C++ [dcl.fct.default]p7
99 // Local variables shall not be used in default argument
100 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000101 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000102 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000104 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000105 }
Chris Lattner8123a952008-04-10 02:22:51 +0000106
Douglas Gregor3996f232008-11-04 13:41:56 +0000107 return false;
108 }
Chris Lattner9e979552008-04-12 23:52:44 +0000109
Douglas Gregor796da182008-11-04 14:32:21 +0000110 /// VisitCXXThisExpr - Visit a C++ "this" expression.
111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
112 // C++ [dcl.fct.default]p8:
113 // The keyword this shall not be used in a default argument of a
114 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000115 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000116 diag::err_param_default_argument_references_this)
117 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000118 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000119
John McCall045d2522013-04-09 01:56:28 +0000120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
121 bool Invalid = false;
122 for (PseudoObjectExpr::semantics_iterator
123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
124 Expr *E = *i;
125
126 // Look through bindings.
127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
128 E = OVE->getSourceExpr();
129 assert(E && "pseudo-object binding without source expression?");
130 }
131
132 Invalid |= Visit(E);
133 }
134 return Invalid;
135 }
136
Douglas Gregorf0459f82012-02-10 23:30:22 +0000137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
138 // C++11 [expr.lambda.prim]p13:
139 // A lambda-expression appearing in a default argument shall not
140 // implicitly or explicitly capture any entity.
141 if (Lambda->capture_begin() == Lambda->capture_end())
142 return false;
143
144 return S->Diag(Lambda->getLocStart(),
145 diag::err_lambda_capture_default_arg);
146 }
Chris Lattner8123a952008-04-10 02:22:51 +0000147}
148
Richard Smith0b0ca472013-04-10 06:11:48 +0000149void
150Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000152 // If we have an MSAny spec already, don't bother.
153 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000154 return;
155
156 const FunctionProtoType *Proto
157 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159 if (!Proto)
160 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000161
162 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
163
164 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000165 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000166 ClearExceptions();
167 ComputedEST = EST;
168 return;
169 }
170
Richard Smith7a614d82011-06-11 17:19:42 +0000171 // FIXME: If the call to this decl is using any of its default arguments, we
172 // need to search them for potentially-throwing calls.
173
Sean Hunt001cad92011-05-10 00:49:42 +0000174 // If this function has a basic noexcept, it doesn't affect the outcome.
175 if (EST == EST_BasicNoexcept)
176 return;
177
178 // If we have a throw-all spec at this point, ignore the function.
179 if (ComputedEST == EST_None)
180 return;
181
182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
184 if (EST == EST_DynamicNone) {
185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
188 }
189
190 // Check out noexcept specs.
191 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000192 FunctionProtoType::NoexceptResult NR =
193 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000194 assert(NR != FunctionProtoType::NR_NoNoexcept &&
195 "Must have noexcept result for EST_ComputedNoexcept.");
196 assert(NR != FunctionProtoType::NR_Dependent &&
197 "Should not generate implicit declarations for dependent cases, "
198 "and don't know how to handle them anyway.");
199
200 // noexcept(false) -> no spec on the new function
201 if (NR == FunctionProtoType::NR_Throw) {
202 ClearExceptions();
203 ComputedEST = EST_None;
204 }
205 // noexcept(true) won't change anything either.
206 return;
207 }
208
209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
214 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
215 EEnd = Proto->exception_end();
216 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000217 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000218 Exceptions.push_back(*E);
219}
220
Richard Smith7a614d82011-06-11 17:19:42 +0000221void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000222 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000223 return;
224
225 // FIXME:
226 //
227 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000228 // [An] implicit exception-specification specifies the type-id T if and
229 // only if T is allowed by the exception-specification of a function directly
230 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000231 // function it directly invokes allows all exceptions, and f shall allow no
232 // exceptions if every function it directly invokes allows no exceptions.
233 //
234 // Note in particular that if an implicit exception-specification is generated
235 // for a function containing a throw-expression, that specification can still
236 // be noexcept(true).
237 //
238 // Note also that 'directly invoked' is not defined in the standard, and there
239 // is no indication that we should only consider potentially-evaluated calls.
240 //
241 // Ultimately we should implement the intent of the standard: the exception
242 // specification should be the set of exceptions which can be thrown by the
243 // implicit definition. For now, we assume that any non-nothrow expression can
244 // throw any exception.
245
Richard Smithe6975e92012-04-17 00:58:00 +0000246 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000247 ComputedEST = EST_None;
248}
249
Anders Carlssoned961f92009-08-25 02:29:20 +0000250bool
John McCall9ae2f072010-08-23 23:25:46 +0000251Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000252 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000253 if (RequireCompleteType(Param->getLocation(), Param->getType(),
254 diag::err_typecheck_decl_incomplete_type)) {
255 Param->setInvalidDecl();
256 return true;
257 }
258
Anders Carlssoned961f92009-08-25 02:29:20 +0000259 // C++ [dcl.fct.default]p5
260 // A default argument expression is implicitly converted (clause
261 // 4) to the parameter type. The default argument expression has
262 // the same semantic constraints as the initializer expression in
263 // a declaration of a variable of the parameter type, using the
264 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000265 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
266 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000267 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
268 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000269 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000270 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000271 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000272 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000273 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000274
Richard Smith6c3af3d2013-01-17 01:17:56 +0000275 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000276 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Anders Carlssoned961f92009-08-25 02:29:20 +0000278 // Okay: add the default argument to the parameter
279 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000281 // We have already instantiated this parameter; provide each of the
282 // instantiations with the uninstantiated default argument.
283 UnparsedDefaultArgInstantiationsMap::iterator InstPos
284 = UnparsedDefaultArgInstantiations.find(Param);
285 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
286 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
287 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
288
289 // We're done tracking this parameter's instantiations.
290 UnparsedDefaultArgInstantiations.erase(InstPos);
291 }
292
Anders Carlsson9351c172009-08-25 03:18:48 +0000293 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000294}
295
Chris Lattner8123a952008-04-10 02:22:51 +0000296/// ActOnParamDefaultArgument - Check whether the default argument
297/// provided for a function parameter is well-formed. If so, attach it
298/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000299void
John McCalld226f652010-08-21 09:40:31 +0000300Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000301 Expr *DefaultArg) {
302 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000303 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000304
John McCalld226f652010-08-21 09:40:31 +0000305 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000306 UnparsedDefaultArgLocs.erase(Param);
307
Chris Lattner3d1cee32008-04-08 05:04:30 +0000308 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000309 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000310 Diag(EqualLoc, diag::err_param_default_argument)
311 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000312 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000313 return;
314 }
315
Douglas Gregor6f526752010-12-16 08:48:57 +0000316 // Check for unexpanded parameter packs.
317 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
318 Param->setInvalidDecl();
319 return;
320 }
321
Anders Carlsson66e30672009-08-25 01:02:06 +0000322 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000323 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
324 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000325 Param->setInvalidDecl();
326 return;
327 }
Mike Stump1eb44332009-09-09 15:08:12 +0000328
John McCall9ae2f072010-08-23 23:25:46 +0000329 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000330}
331
Douglas Gregor61366e92008-12-24 00:01:03 +0000332/// ActOnParamUnparsedDefaultArgument - We've seen a default
333/// argument for a function parameter, but we can't parse it yet
334/// because we're inside a class definition. Note that this default
335/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000336void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000337 SourceLocation EqualLoc,
338 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000339 if (!param)
340 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000341
John McCalld226f652010-08-21 09:40:31 +0000342 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000343 if (Param)
344 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Anders Carlsson5e300d12009-06-12 16:51:40 +0000346 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000347}
348
Douglas Gregor72b505b2008-12-16 21:30:33 +0000349/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
350/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000351void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000352 if (!param)
353 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000354
John McCalld226f652010-08-21 09:40:31 +0000355 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Anders Carlsson5e300d12009-06-12 16:51:40 +0000357 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Anders Carlsson5e300d12009-06-12 16:51:40 +0000359 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000360}
361
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000362/// CheckExtraCXXDefaultArguments - Check for any extra default
363/// arguments in the declarator, which is not a function declaration
364/// or definition and therefore is not permitted to have default
365/// arguments. This routine should be invoked for every declarator
366/// that is not a function declaration or definition.
367void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
368 // C++ [dcl.fct.default]p3
369 // A default argument expression shall be specified only in the
370 // parameter-declaration-clause of a function declaration or in a
371 // template-parameter (14.1). It shall not be specified for a
372 // parameter pack. If it is specified in a
373 // parameter-declaration-clause, it shall not occur within a
374 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000375 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000377 DeclaratorChunk &chunk = D.getTypeObject(i);
378 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000379 if (MightBeFunction) {
380 // This is a function declaration. It can have default arguments, but
381 // keep looking in case its return type is a function type with default
382 // arguments.
383 MightBeFunction = false;
384 continue;
385 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000386 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
387 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000388 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000389 if (Param->hasUnparsedDefaultArg()) {
390 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000392 << SourceRange((*Toks)[1].getLocation(),
393 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000394 delete Toks;
395 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000396 } else if (Param->getDefaultArg()) {
397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
398 << Param->getDefaultArg()->getSourceRange();
399 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000400 }
401 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000402 } else if (chunk.Kind != DeclaratorChunk::Paren) {
403 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000404 }
405 }
406}
407
David Majnemerf6a144f2013-06-25 23:09:30 +0000408static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
409 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
410 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
411 if (!PVD->hasDefaultArg())
412 return false;
413 if (!PVD->hasInheritedDefaultArg())
414 return true;
415 }
416 return false;
417}
418
Craig Topper1a6eac82012-09-21 04:33:26 +0000419/// MergeCXXFunctionDecl - Merge two declarations of the same C++
420/// function, once we already know that they have the same
421/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
422/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000423bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
424 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000425 bool Invalid = false;
426
Chris Lattner3d1cee32008-04-08 05:04:30 +0000427 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000428 // For non-template functions, default arguments can be added in
429 // later declarations of a function in the same
430 // scope. Declarations in different scopes have completely
431 // distinct sets of default arguments. That is, declarations in
432 // inner scopes do not acquire default arguments from
433 // declarations in outer scopes, and vice versa. In a given
434 // function declaration, all parameters subsequent to a
435 // parameter with a default argument shall have default
436 // arguments supplied in this or previous declarations. A
437 // default argument shall not be redefined by a later
438 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000439 //
440 // C++ [dcl.fct.default]p6:
441 // Except for member functions of class templates, the default arguments
442 // in a member function definition that appears outside of the class
443 // definition are added to the set of default arguments provided by the
444 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000445 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
446 ParmVarDecl *OldParam = Old->getParamDecl(p);
447 ParmVarDecl *NewParam = New->getParamDecl(p);
448
James Molloy9cda03f2012-03-13 08:55:35 +0000449 bool OldParamHasDfl = OldParam->hasDefaultArg();
450 bool NewParamHasDfl = NewParam->hasDefaultArg();
451
452 NamedDecl *ND = Old;
453 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
454 // Ignore default parameters of old decl if they are not in
455 // the same scope.
456 OldParamHasDfl = false;
457
458 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000459
Francois Pichet8d051e02011-04-10 03:03:52 +0000460 unsigned DiagDefaultParamID =
461 diag::err_param_default_argument_redefinition;
462
463 // MSVC accepts that default parameters be redefined for member functions
464 // of template class. The new default parameter's value is ignored.
465 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000466 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000467 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
468 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // Merge the old default argument into the new parameter.
470 NewParam->setHasInheritedDefaultArg();
471 if (OldParam->hasUninstantiatedDefaultArg())
472 NewParam->setUninstantiatedDefaultArg(
473 OldParam->getUninstantiatedDefaultArg());
474 else
475 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000476 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Invalid = false;
478 }
479 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000480
Francois Pichet8cf90492011-04-10 04:58:30 +0000481 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
482 // hint here. Alternatively, we could walk the type-source information
483 // for NewParam to find the last source location in the type... but it
484 // isn't worth the effort right now. This is the kind of test case that
485 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000486 // int f(int);
487 // void g(int (*fp)(int) = f);
488 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000489 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000490 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000491
492 // Look for the function declaration where the default argument was
493 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000494 for (FunctionDecl *Older = Old->getPreviousDecl();
495 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000496 if (!Older->getParamDecl(p)->hasDefaultArg())
497 break;
498
499 OldParam = Older->getParamDecl(p);
500 }
501
502 Diag(OldParam->getLocation(), diag::note_previous_definition)
503 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000504 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000505 // Merge the old default argument into the new parameter.
506 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000507 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000508 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000509 if (OldParam->hasUninstantiatedDefaultArg())
510 NewParam->setUninstantiatedDefaultArg(
511 OldParam->getUninstantiatedDefaultArg());
512 else
John McCall3d6c1782010-05-04 01:53:42 +0000513 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000514 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000515 if (New->getDescribedFunctionTemplate()) {
516 // Paragraph 4, quoted above, only applies to non-template functions.
517 Diag(NewParam->getLocation(),
518 diag::err_param_default_argument_template_redecl)
519 << NewParam->getDefaultArgRange();
520 Diag(Old->getLocation(), diag::note_template_prev_declaration)
521 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000522 } else if (New->getTemplateSpecializationKind()
523 != TSK_ImplicitInstantiation &&
524 New->getTemplateSpecializationKind() != TSK_Undeclared) {
525 // C++ [temp.expr.spec]p21:
526 // Default function arguments shall not be specified in a declaration
527 // or a definition for one of the following explicit specializations:
528 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000529 // - the explicit specialization of a member function template;
530 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000531 // template where the class template specialization to which the
532 // member function specialization belongs is implicitly
533 // instantiated.
534 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
535 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
536 << New->getDeclName()
537 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000538 } else if (New->getDeclContext()->isDependentContext()) {
539 // C++ [dcl.fct.default]p6 (DR217):
540 // Default arguments for a member function of a class template shall
541 // be specified on the initial declaration of the member function
542 // within the class template.
543 //
544 // Reading the tea leaves a bit in DR217 and its reference to DR205
545 // leads me to the conclusion that one cannot add default function
546 // arguments for an out-of-line definition of a member function of a
547 // dependent type.
548 int WhichKind = 2;
549 if (CXXRecordDecl *Record
550 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
551 if (Record->getDescribedClassTemplate())
552 WhichKind = 0;
553 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
554 WhichKind = 1;
555 else
556 WhichKind = 2;
557 }
558
559 Diag(NewParam->getLocation(),
560 diag::err_param_default_argument_member_template_redecl)
561 << WhichKind
562 << NewParam->getDefaultArgRange();
563 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000564 }
565 }
566
Richard Smithb8abff62012-11-28 03:45:24 +0000567 // DR1344: If a default argument is added outside a class definition and that
568 // default argument makes the function a special member function, the program
569 // is ill-formed. This can only happen for constructors.
570 if (isa<CXXConstructorDecl>(New) &&
571 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
572 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
573 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
574 if (NewSM != OldSM) {
575 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
576 assert(NewParam->hasDefaultArg());
577 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
578 << NewParam->getDefaultArgRange() << NewSM;
579 Diag(Old->getLocation(), diag::note_previous_declaration);
580 }
581 }
582
Richard Smithff234882012-02-20 23:28:05 +0000583 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000584 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000585 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000586 if (New->isConstexpr() != Old->isConstexpr()) {
587 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
588 << New << New->isConstexpr();
589 Diag(Old->getLocation(), diag::note_previous_declaration);
590 Invalid = true;
591 }
592
David Majnemerf6a144f2013-06-25 23:09:30 +0000593 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000594 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000595 // the only declaration of the function or function template in the
596 // translation unit.
597 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
598 functionDeclHasDefaultArgument(Old)) {
599 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
600 Diag(Old->getLocation(), diag::note_previous_declaration);
601 Invalid = true;
602 }
603
Douglas Gregore13ad832010-02-12 07:32:17 +0000604 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000605 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000606
Douglas Gregorcda9c672009-02-16 17:45:42 +0000607 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000608}
609
Sebastian Redl60618fa2011-03-12 11:50:43 +0000610/// \brief Merge the exception specifications of two variable declarations.
611///
612/// This is called when there's a redeclaration of a VarDecl. The function
613/// checks if the redeclaration might have an exception specification and
614/// validates compatibility and merges the specs if necessary.
615void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
616 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000617 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000618 return;
619
620 assert(Context.hasSameType(New->getType(), Old->getType()) &&
621 "Should only be called if types are otherwise the same.");
622
623 QualType NewType = New->getType();
624 QualType OldType = Old->getType();
625
626 // We're only interested in pointers and references to functions, as well
627 // as pointers to member functions.
628 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
629 NewType = R->getPointeeType();
630 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
631 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
632 NewType = P->getPointeeType();
633 OldType = OldType->getAs<PointerType>()->getPointeeType();
634 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
635 NewType = M->getPointeeType();
636 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
637 }
638
639 if (!NewType->isFunctionProtoType())
640 return;
641
642 // There's lots of special cases for functions. For function pointers, system
643 // libraries are hopefully not as broken so that we don't need these
644 // workarounds.
645 if (CheckEquivalentExceptionSpec(
646 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
647 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
648 New->setInvalidDecl();
649 }
650}
651
Chris Lattner3d1cee32008-04-08 05:04:30 +0000652/// CheckCXXDefaultArguments - Verify that the default arguments for a
653/// function declaration are well-formed according to C++
654/// [dcl.fct.default].
655void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
656 unsigned NumParams = FD->getNumParams();
657 unsigned p;
658
659 // Find first parameter with a default argument
660 for (p = 0; p < NumParams; ++p) {
661 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000662 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 break;
664 }
665
666 // C++ [dcl.fct.default]p4:
667 // In a given function declaration, all parameters
668 // subsequent to a parameter with a default argument shall
669 // have default arguments supplied in this or previous
670 // declarations. A default argument shall not be redefined
671 // by a later declaration (not even to the same value).
672 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000673 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000674 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000675 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000676 if (Param->isInvalidDecl())
677 /* We already complained about this parameter. */;
678 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000679 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000680 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000681 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000682 else
Mike Stump1eb44332009-09-09 15:08:12 +0000683 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000684 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattner3d1cee32008-04-08 05:04:30 +0000686 LastMissingDefaultArg = p;
687 }
688 }
689
690 if (LastMissingDefaultArg > 0) {
691 // Some default arguments were missing. Clear out all of the
692 // default arguments up to (and including) the last missing
693 // default argument, so that we leave the function parameters
694 // in a semantically valid state.
695 for (p = 0; p <= LastMissingDefaultArg; ++p) {
696 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000697 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000698 Param->setDefaultArg(0);
699 }
700 }
701 }
702}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000703
Richard Smith9f569cc2011-10-01 02:31:28 +0000704// CheckConstexprParameterTypes - Check whether a function's parameter types
705// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000706// diagnostic and return false.
707static bool CheckConstexprParameterTypes(Sema &SemaRef,
708 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000709 unsigned ArgIndex = 0;
710 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
711 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
712 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
713 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
714 SourceLocation ParamLoc = PD->getLocation();
715 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000716 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000717 diag::err_constexpr_non_literal_param,
718 ArgIndex+1, PD->getSourceRange(),
719 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000720 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000721 }
Joao Matos17d35c32012-08-31 22:18:20 +0000722 return true;
723}
724
725/// \brief Get diagnostic %select index for tag kind for
726/// record diagnostic message.
727/// WARNING: Indexes apply to particular diagnostics only!
728///
729/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000730static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000731 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000732 case TTK_Struct: return 0;
733 case TTK_Interface: return 1;
734 case TTK_Class: return 2;
735 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000736 }
Joao Matos17d35c32012-08-31 22:18:20 +0000737}
738
739// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
740// the requirements of a constexpr function definition or a constexpr
741// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000742// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000743//
Richard Smith86c3ae42012-02-13 03:54:03 +0000744// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
745bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000746 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
747 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000748 // C++11 [dcl.constexpr]p4:
749 // The definition of a constexpr constructor shall satisfy the following
750 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000751 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000752 const CXXRecordDecl *RD = MD->getParent();
753 if (RD->getNumVBases()) {
754 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
755 << isa<CXXConstructorDecl>(NewFD)
756 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
757 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
758 E = RD->vbases_end(); I != E; ++I)
759 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000760 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000761 return false;
762 }
Richard Smith35340502012-01-13 04:54:00 +0000763 }
764
765 if (!isa<CXXConstructorDecl>(NewFD)) {
766 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 // The definition of a constexpr function shall satisfy the following
768 // constraints:
769 // - it shall not be virtual;
770 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
771 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000772 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000773
Richard Smith86c3ae42012-02-13 03:54:03 +0000774 // If it's not obvious why this function is virtual, find an overridden
775 // function which uses the 'virtual' keyword.
776 const CXXMethodDecl *WrittenVirtual = Method;
777 while (!WrittenVirtual->isVirtualAsWritten())
778 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
779 if (WrittenVirtual != Method)
780 Diag(WrittenVirtual->getLocation(),
781 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000782 return false;
783 }
784
785 // - its return type shall be a literal type;
786 QualType RT = NewFD->getResultType();
787 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000788 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000789 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000790 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000791 }
792
Richard Smith35340502012-01-13 04:54:00 +0000793 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000794 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000795 return false;
796
Richard Smith9f569cc2011-10-01 02:31:28 +0000797 return true;
798}
799
800/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000801/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000802///
Richard Smitha10b9782013-04-22 15:31:51 +0000803/// \return true if the body is OK (maybe only as an extension), false if we
804/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000805static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000806 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
807 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000808 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
809 // contain only
810 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
811 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
812 switch ((*DclIt)->getKind()) {
813 case Decl::StaticAssert:
814 case Decl::Using:
815 case Decl::UsingShadow:
816 case Decl::UsingDirective:
817 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000818 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000819 // - static_assert-declarations
820 // - using-declarations,
821 // - using-directives,
822 continue;
823
824 case Decl::Typedef:
825 case Decl::TypeAlias: {
826 // - typedef declarations and alias-declarations that do not define
827 // classes or enumerations,
828 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
829 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
830 // Don't allow variably-modified types in constexpr functions.
831 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
832 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
833 << TL.getSourceRange() << TL.getType()
834 << isa<CXXConstructorDecl>(Dcl);
835 return false;
836 }
837 continue;
838 }
839
840 case Decl::Enum:
841 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000842 // C++1y allows types to be defined, not just declared.
843 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
844 SemaRef.Diag(DS->getLocStart(),
845 SemaRef.getLangOpts().CPlusPlus1y
846 ? diag::warn_cxx11_compat_constexpr_type_definition
847 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000848 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000849 continue;
850
Richard Smitha10b9782013-04-22 15:31:51 +0000851 case Decl::EnumConstant:
852 case Decl::IndirectField:
853 case Decl::ParmVar:
854 // These can only appear with other declarations which are banned in
855 // C++11 and permitted in C++1y, so ignore them.
856 continue;
857
858 case Decl::Var: {
859 // C++1y [dcl.constexpr]p3 allows anything except:
860 // a definition of a variable of non-literal type or of static or
861 // thread storage duration or for which no initialization is performed.
862 VarDecl *VD = cast<VarDecl>(*DclIt);
863 if (VD->isThisDeclarationADefinition()) {
864 if (VD->isStaticLocal()) {
865 SemaRef.Diag(VD->getLocation(),
866 diag::err_constexpr_local_var_static)
867 << isa<CXXConstructorDecl>(Dcl)
868 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
869 return false;
870 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000871 if (!VD->getType()->isDependentType() &&
872 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000873 VD->getLocation(), VD->getType(),
874 diag::err_constexpr_local_var_non_literal_type,
875 isa<CXXConstructorDecl>(Dcl)))
876 return false;
877 if (!VD->hasInit()) {
878 SemaRef.Diag(VD->getLocation(),
879 diag::err_constexpr_local_var_no_init)
880 << isa<CXXConstructorDecl>(Dcl);
881 return false;
882 }
883 }
884 SemaRef.Diag(VD->getLocation(),
885 SemaRef.getLangOpts().CPlusPlus1y
886 ? diag::warn_cxx11_compat_constexpr_local_var
887 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000888 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000889 continue;
890 }
891
892 case Decl::NamespaceAlias:
893 case Decl::Function:
894 // These are disallowed in C++11 and permitted in C++1y. Allow them
895 // everywhere as an extension.
896 if (!Cxx1yLoc.isValid())
897 Cxx1yLoc = DS->getLocStart();
898 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000899
900 default:
901 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
902 << isa<CXXConstructorDecl>(Dcl);
903 return false;
904 }
905 }
906
907 return true;
908}
909
910/// Check that the given field is initialized within a constexpr constructor.
911///
912/// \param Dcl The constexpr constructor being checked.
913/// \param Field The field being checked. This may be a member of an anonymous
914/// struct or union nested within the class being checked.
915/// \param Inits All declarations, including anonymous struct/union members and
916/// indirect members, for which any initialization was provided.
917/// \param Diagnosed Set to true if an error is produced.
918static void CheckConstexprCtorInitializer(Sema &SemaRef,
919 const FunctionDecl *Dcl,
920 FieldDecl *Field,
921 llvm::SmallSet<Decl*, 16> &Inits,
922 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000923 if (Field->isInvalidDecl())
924 return;
925
Douglas Gregord61db332011-10-10 17:22:13 +0000926 if (Field->isUnnamedBitfield())
927 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000928
929 if (Field->isAnonymousStructOrUnion() &&
930 Field->getType()->getAsCXXRecordDecl()->isEmpty())
931 return;
932
Richard Smith9f569cc2011-10-01 02:31:28 +0000933 if (!Inits.count(Field)) {
934 if (!Diagnosed) {
935 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
936 Diagnosed = true;
937 }
938 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
939 } else if (Field->isAnonymousStructOrUnion()) {
940 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
941 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
942 I != E; ++I)
943 // If an anonymous union contains an anonymous struct of which any member
944 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000945 if (!RD->isUnion() || Inits.count(*I))
946 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000947 }
948}
949
Richard Smitha10b9782013-04-22 15:31:51 +0000950/// Check the provided statement is allowed in a constexpr function
951/// definition.
952static bool
953CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000954 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000955 SourceLocation &Cxx1yLoc) {
956 // - its function-body shall be [...] a compound-statement that contains only
957 switch (S->getStmtClass()) {
958 case Stmt::NullStmtClass:
959 // - null statements,
960 return true;
961
962 case Stmt::DeclStmtClass:
963 // - static_assert-declarations
964 // - using-declarations,
965 // - using-directives,
966 // - typedef declarations and alias-declarations that do not define
967 // classes or enumerations,
968 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
969 return false;
970 return true;
971
972 case Stmt::ReturnStmtClass:
973 // - and exactly one return statement;
974 if (isa<CXXConstructorDecl>(Dcl)) {
975 // C++1y allows return statements in constexpr constructors.
976 if (!Cxx1yLoc.isValid())
977 Cxx1yLoc = S->getLocStart();
978 return true;
979 }
980
981 ReturnStmts.push_back(S->getLocStart());
982 return true;
983
984 case Stmt::CompoundStmtClass: {
985 // C++1y allows compound-statements.
986 if (!Cxx1yLoc.isValid())
987 Cxx1yLoc = S->getLocStart();
988
989 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
990 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
991 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
992 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
993 Cxx1yLoc))
994 return false;
995 }
996 return true;
997 }
998
999 case Stmt::AttributedStmtClass:
1000 if (!Cxx1yLoc.isValid())
1001 Cxx1yLoc = S->getLocStart();
1002 return true;
1003
1004 case Stmt::IfStmtClass: {
1005 // C++1y allows if-statements.
1006 if (!Cxx1yLoc.isValid())
1007 Cxx1yLoc = S->getLocStart();
1008
1009 IfStmt *If = cast<IfStmt>(S);
1010 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1011 Cxx1yLoc))
1012 return false;
1013 if (If->getElse() &&
1014 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1015 Cxx1yLoc))
1016 return false;
1017 return true;
1018 }
1019
1020 case Stmt::WhileStmtClass:
1021 case Stmt::DoStmtClass:
1022 case Stmt::ForStmtClass:
1023 case Stmt::CXXForRangeStmtClass:
1024 case Stmt::ContinueStmtClass:
1025 // C++1y allows all of these. We don't allow them as extensions in C++11,
1026 // because they don't make sense without variable mutation.
1027 if (!SemaRef.getLangOpts().CPlusPlus1y)
1028 break;
1029 if (!Cxx1yLoc.isValid())
1030 Cxx1yLoc = S->getLocStart();
1031 for (Stmt::child_range Children = S->children(); Children; ++Children)
1032 if (*Children &&
1033 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1034 Cxx1yLoc))
1035 return false;
1036 return true;
1037
1038 case Stmt::SwitchStmtClass:
1039 case Stmt::CaseStmtClass:
1040 case Stmt::DefaultStmtClass:
1041 case Stmt::BreakStmtClass:
1042 // C++1y allows switch-statements, and since they don't need variable
1043 // mutation, we can reasonably allow them in C++11 as an extension.
1044 if (!Cxx1yLoc.isValid())
1045 Cxx1yLoc = S->getLocStart();
1046 for (Stmt::child_range Children = S->children(); Children; ++Children)
1047 if (*Children &&
1048 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1049 Cxx1yLoc))
1050 return false;
1051 return true;
1052
1053 default:
1054 if (!isa<Expr>(S))
1055 break;
1056
1057 // C++1y allows expression-statements.
1058 if (!Cxx1yLoc.isValid())
1059 Cxx1yLoc = S->getLocStart();
1060 return true;
1061 }
1062
1063 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1064 << isa<CXXConstructorDecl>(Dcl);
1065 return false;
1066}
1067
Richard Smith9f569cc2011-10-01 02:31:28 +00001068/// Check the body for the given constexpr function declaration only contains
1069/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1070///
1071/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001072bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001073 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001074 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001075 // The definition of a constexpr function shall satisfy the following
1076 // constraints: [...]
1077 // - its function-body shall be = delete, = default, or a
1078 // compound-statement
1079 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001080 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 // In the definition of a constexpr constructor, [...]
1082 // - its function-body shall not be a function-try-block;
1083 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1084 << isa<CXXConstructorDecl>(Dcl);
1085 return false;
1086 }
1087
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001088 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001089
1090 // - its function-body shall be [...] a compound-statement that contains only
1091 // [... list of cases ...]
1092 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1093 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001094 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1095 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001096 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1097 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001098 }
1099
Richard Smitha10b9782013-04-22 15:31:51 +00001100 if (Cxx1yLoc.isValid())
1101 Diag(Cxx1yLoc,
1102 getLangOpts().CPlusPlus1y
1103 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1104 : diag::ext_constexpr_body_invalid_stmt)
1105 << isa<CXXConstructorDecl>(Dcl);
1106
Richard Smith9f569cc2011-10-01 02:31:28 +00001107 if (const CXXConstructorDecl *Constructor
1108 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1109 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001110 // DR1359:
1111 // - every non-variant non-static data member and base class sub-object
1112 // shall be initialized;
1113 // - if the class is a non-empty union, or for each non-empty anonymous
1114 // union member of a non-union class, exactly one non-static data member
1115 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001116 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001117 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001118 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1119 return false;
1120 }
Richard Smith6e433752011-10-10 16:38:04 +00001121 } else if (!Constructor->isDependentContext() &&
1122 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001123 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1124
1125 // Skip detailed checking if we have enough initializers, and we would
1126 // allow at most one initializer per member.
1127 bool AnyAnonStructUnionMembers = false;
1128 unsigned Fields = 0;
1129 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1130 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001131 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001132 AnyAnonStructUnionMembers = true;
1133 break;
1134 }
1135 }
1136 if (AnyAnonStructUnionMembers ||
1137 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1138 // Check initialization of non-static data members. Base classes are
1139 // always initialized so do not need to be checked. Dependent bases
1140 // might not have initializers in the member initializer list.
1141 llvm::SmallSet<Decl*, 16> Inits;
1142 for (CXXConstructorDecl::init_const_iterator
1143 I = Constructor->init_begin(), E = Constructor->init_end();
1144 I != E; ++I) {
1145 if (FieldDecl *FD = (*I)->getMember())
1146 Inits.insert(FD);
1147 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1148 Inits.insert(ID->chain_begin(), ID->chain_end());
1149 }
1150
1151 bool Diagnosed = false;
1152 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1153 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001154 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001155 if (Diagnosed)
1156 return false;
1157 }
1158 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001159 } else {
1160 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001161 // C++1y doesn't require constexpr functions to contain a 'return'
1162 // statement. We still do, unless the return type is void, because
1163 // otherwise if there's no return statement, the function cannot
1164 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001165 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001166 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001167 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1168 : diag::err_constexpr_body_no_return);
1169 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001170 }
1171 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001172 Diag(ReturnStmts.back(),
1173 getLangOpts().CPlusPlus1y
1174 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1175 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001176 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1177 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001178 }
1179 }
1180
Richard Smith5ba73e12012-02-04 00:33:54 +00001181 // C++11 [dcl.constexpr]p5:
1182 // if no function argument values exist such that the function invocation
1183 // substitution would produce a constant expression, the program is
1184 // ill-formed; no diagnostic required.
1185 // C++11 [dcl.constexpr]p3:
1186 // - every constructor call and implicit conversion used in initializing the
1187 // return value shall be one of those allowed in a constant expression.
1188 // C++11 [dcl.constexpr]p4:
1189 // - every constructor involved in initializing non-static data members and
1190 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001191 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001192 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001193 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001194 << isa<CXXConstructorDecl>(Dcl);
1195 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1196 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001197 // Don't return false here: we allow this for compatibility in
1198 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001199 }
1200
Richard Smith9f569cc2011-10-01 02:31:28 +00001201 return true;
1202}
1203
Douglas Gregorb48fe382008-10-31 09:07:45 +00001204/// isCurrentClassName - Determine whether the identifier II is the
1205/// name of the class type currently being defined. In the case of
1206/// nested classes, this will only return true if II is the name of
1207/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001208bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1209 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001210 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001211
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001212 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001213 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001214 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001215 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1216 } else
1217 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1218
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001219 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001220 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001221 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001222}
1223
Douglas Gregor229d47a2012-11-10 07:24:09 +00001224/// \brief Determine whether the given class is a base class of the given
1225/// class, including looking at dependent bases.
1226static bool findCircularInheritance(const CXXRecordDecl *Class,
1227 const CXXRecordDecl *Current) {
1228 SmallVector<const CXXRecordDecl*, 8> Queue;
1229
1230 Class = Class->getCanonicalDecl();
1231 while (true) {
1232 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1233 E = Current->bases_end();
1234 I != E; ++I) {
1235 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1236 if (!Base)
1237 continue;
1238
1239 Base = Base->getDefinition();
1240 if (!Base)
1241 continue;
1242
1243 if (Base->getCanonicalDecl() == Class)
1244 return true;
1245
1246 Queue.push_back(Base);
1247 }
1248
1249 if (Queue.empty())
1250 return false;
1251
Robert Wilhelm344472e2013-08-23 16:11:15 +00001252 Current = Queue.pop_back_val();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001253 }
1254
1255 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001256}
1257
Mike Stump1eb44332009-09-09 15:08:12 +00001258/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001259///
1260/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1261/// and returns NULL otherwise.
1262CXXBaseSpecifier *
1263Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1264 SourceRange SpecifierRange,
1265 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001266 TypeSourceInfo *TInfo,
1267 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001268 QualType BaseType = TInfo->getType();
1269
Douglas Gregor2943aed2009-03-03 04:44:36 +00001270 // C++ [class.union]p1:
1271 // A union shall not have base classes.
1272 if (Class->isUnion()) {
1273 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1274 << SpecifierRange;
1275 return 0;
1276 }
1277
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001278 if (EllipsisLoc.isValid() &&
1279 !TInfo->getType()->containsUnexpandedParameterPack()) {
1280 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1281 << TInfo->getTypeLoc().getSourceRange();
1282 EllipsisLoc = SourceLocation();
1283 }
Douglas Gregord777e282012-11-10 01:18:17 +00001284
1285 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1286
1287 if (BaseType->isDependentType()) {
1288 // Make sure that we don't have circular inheritance among our dependent
1289 // bases. For non-dependent bases, the check for completeness below handles
1290 // this.
1291 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1292 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1293 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001294 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001295 Diag(BaseLoc, diag::err_circular_inheritance)
1296 << BaseType << Context.getTypeDeclType(Class);
1297
1298 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1299 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1300 << BaseType;
1301
1302 return 0;
1303 }
1304 }
1305
Mike Stump1eb44332009-09-09 15:08:12 +00001306 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001307 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001308 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001309 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001310
1311 // Base specifiers must be record types.
1312 if (!BaseType->isRecordType()) {
1313 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1314 return 0;
1315 }
1316
1317 // C++ [class.union]p1:
1318 // A union shall not be used as a base class.
1319 if (BaseType->isUnionType()) {
1320 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1321 return 0;
1322 }
1323
1324 // C++ [class.derived]p2:
1325 // The class-name in a base-specifier shall not be an incompletely
1326 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001327 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001328 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001329 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001330 return 0;
John McCall572fc622010-08-17 07:23:57 +00001331 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001332
Eli Friedman1d954f62009-08-15 21:55:26 +00001333 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001334 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001335 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001336 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001337 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001338 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001339 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001340
Anders Carlsson1d209272011-03-25 14:55:14 +00001341 // C++ [class]p3:
1342 // If a class is marked final and it appears as a base-type-specifier in
1343 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001344 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001345 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1346 << CXXBaseDecl->getDeclName();
1347 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1348 << CXXBaseDecl->getDeclName();
1349 return 0;
1350 }
1351
John McCall572fc622010-08-17 07:23:57 +00001352 if (BaseDecl->isInvalidDecl())
1353 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001354
1355 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001356 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001357 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001358 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001359}
1360
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001361/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1362/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001363/// example:
1364/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001365/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001366BaseResult
John McCalld226f652010-08-21 09:40:31 +00001367Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001368 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001369 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001370 ParsedType basetype, SourceLocation BaseLoc,
1371 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001372 if (!classdecl)
1373 return true;
1374
Douglas Gregor40808ce2009-03-09 23:48:35 +00001375 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001376 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001377 if (!Class)
1378 return true;
1379
Richard Smith05321402013-02-19 23:47:15 +00001380 // We do not support any C++11 attributes on base-specifiers yet.
1381 // Diagnose any attributes we see.
1382 if (!Attributes.empty()) {
1383 for (AttributeList *Attr = Attributes.getList(); Attr;
1384 Attr = Attr->getNext()) {
1385 if (Attr->isInvalid() ||
1386 Attr->getKind() == AttributeList::IgnoredAttribute)
1387 continue;
1388 Diag(Attr->getLoc(),
1389 Attr->getKind() == AttributeList::UnknownAttribute
1390 ? diag::warn_unknown_attribute_ignored
1391 : diag::err_base_specifier_attribute)
1392 << Attr->getName();
1393 }
1394 }
1395
Nick Lewycky56062202010-07-26 16:56:01 +00001396 TypeSourceInfo *TInfo = 0;
1397 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001398
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001399 if (EllipsisLoc.isInvalid() &&
1400 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001401 UPPC_BaseType))
1402 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001403
Douglas Gregor2943aed2009-03-03 04:44:36 +00001404 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001405 Virtual, Access, TInfo,
1406 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001407 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001408 else
1409 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Douglas Gregor2943aed2009-03-03 04:44:36 +00001411 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001412}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001413
Douglas Gregor2943aed2009-03-03 04:44:36 +00001414/// \brief Performs the actual work of attaching the given base class
1415/// specifiers to a C++ class.
1416bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1417 unsigned NumBases) {
1418 if (NumBases == 0)
1419 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001420
1421 // Used to keep track of which base types we have already seen, so
1422 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001423 // that the key is always the unqualified canonical type of the base
1424 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001425 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1426
1427 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001428 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001429 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001430 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001431 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001432 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001433 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001434
1435 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1436 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001437 // C++ [class.mi]p3:
1438 // A class shall not be specified as a direct base class of a
1439 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001440 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001441 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001442 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001443 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001444
1445 // Delete the duplicate base class specifier; we're going to
1446 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001447 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001448
1449 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001450 } else {
1451 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001452 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001453 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001454 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1455 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1456 if (Class->isInterface() &&
1457 (!RD->isInterface() ||
1458 KnownBase->getAccessSpecifier() != AS_public)) {
1459 // The Microsoft extension __interface does not permit bases that
1460 // are not themselves public interfaces.
1461 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1462 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1463 << RD->getSourceRange();
1464 Invalid = true;
1465 }
1466 if (RD->hasAttr<WeakAttr>())
1467 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1468 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001469 }
1470 }
1471
1472 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001473 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001474
1475 // Delete the remaining (good) base class specifiers, since their
1476 // data has been copied into the CXXRecordDecl.
1477 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001478 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001479
1480 return Invalid;
1481}
1482
1483/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1484/// class, after checking whether there are any duplicate base
1485/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001486void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001487 unsigned NumBases) {
1488 if (!ClassDecl || !Bases || !NumBases)
1489 return;
1490
1491 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001492 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001493}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001494
Douglas Gregora8f32e02009-10-06 17:59:45 +00001495/// \brief Determine whether the type \p Derived is a C++ class that is
1496/// derived from the type \p Base.
1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001498 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001499 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001500
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001502 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001503 return false;
1504
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001506 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001507 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001508
1509 // If either the base or the derived type is invalid, don't try to
1510 // check whether one is derived from the other.
1511 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1512 return false;
1513
John McCall86ff3082010-02-04 22:26:26 +00001514 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1515 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001516}
1517
1518/// \brief Determine whether the type \p Derived is a C++ class that is
1519/// derived from the type \p Base.
1520bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001521 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001522 return false;
1523
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001524 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001525 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001526 return false;
1527
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001528 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001529 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001530 return false;
1531
Douglas Gregora8f32e02009-10-06 17:59:45 +00001532 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1533}
1534
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001535void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001536 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001537 assert(BasePathArray.empty() && "Base path array must be empty!");
1538 assert(Paths.isRecordingPaths() && "Must record paths!");
1539
1540 const CXXBasePath &Path = Paths.front();
1541
1542 // We first go backward and check if we have a virtual base.
1543 // FIXME: It would be better if CXXBasePath had the base specifier for
1544 // the nearest virtual base.
1545 unsigned Start = 0;
1546 for (unsigned I = Path.size(); I != 0; --I) {
1547 if (Path[I - 1].Base->isVirtual()) {
1548 Start = I - 1;
1549 break;
1550 }
1551 }
1552
1553 // Now add all bases.
1554 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001555 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001556}
1557
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001558/// \brief Determine whether the given base path includes a virtual
1559/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001560bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1561 for (CXXCastPath::const_iterator B = BasePath.begin(),
1562 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001563 B != BEnd; ++B)
1564 if ((*B)->isVirtual())
1565 return true;
1566
1567 return false;
1568}
1569
Douglas Gregora8f32e02009-10-06 17:59:45 +00001570/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1571/// conversion (where Derived and Base are class types) is
1572/// well-formed, meaning that the conversion is unambiguous (and
1573/// that all of the base classes are accessible). Returns true
1574/// and emits a diagnostic if the code is ill-formed, returns false
1575/// otherwise. Loc is the location where this routine should point to
1576/// if there is an error, and Range is the source range to highlight
1577/// if there is an error.
1578bool
1579Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001580 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001581 unsigned AmbigiousBaseConvID,
1582 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001583 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001584 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001585 // First, determine whether the path from Derived to Base is
1586 // ambiguous. This is slightly more expensive than checking whether
1587 // the Derived to Base conversion exists, because here we need to
1588 // explore multiple paths to determine if there is an ambiguity.
1589 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1590 /*DetectVirtual=*/false);
1591 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1592 assert(DerivationOkay &&
1593 "Can only be used with a derived-to-base conversion");
1594 (void)DerivationOkay;
1595
1596 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001597 if (InaccessibleBaseID) {
1598 // Check that the base class can be accessed.
1599 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1600 InaccessibleBaseID)) {
1601 case AR_inaccessible:
1602 return true;
1603 case AR_accessible:
1604 case AR_dependent:
1605 case AR_delayed:
1606 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001607 }
John McCall6b2accb2010-02-10 09:31:12 +00001608 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001609
1610 // Build a base path if necessary.
1611 if (BasePath)
1612 BuildBasePathArray(Paths, *BasePath);
1613 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001614 }
1615
David Majnemer2f686692013-06-22 06:43:58 +00001616 if (AmbigiousBaseConvID) {
1617 // We know that the derived-to-base conversion is ambiguous, and
1618 // we're going to produce a diagnostic. Perform the derived-to-base
1619 // search just one more time to compute all of the possible paths so
1620 // that we can print them out. This is more expensive than any of
1621 // the previous derived-to-base checks we've done, but at this point
1622 // performance isn't as much of an issue.
1623 Paths.clear();
1624 Paths.setRecordingPaths(true);
1625 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1626 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1627 (void)StillOkay;
1628
1629 // Build up a textual representation of the ambiguous paths, e.g.,
1630 // D -> B -> A, that will be used to illustrate the ambiguous
1631 // conversions in the diagnostic. We only print one of the paths
1632 // to each base class subobject.
1633 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1634
1635 Diag(Loc, AmbigiousBaseConvID)
1636 << Derived << Base << PathDisplayStr << Range << Name;
1637 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001638 return true;
1639}
1640
1641bool
1642Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001643 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001644 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001645 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001646 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001647 IgnoreAccess ? 0
1648 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001649 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001650 Loc, Range, DeclarationName(),
1651 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001652}
1653
1654
1655/// @brief Builds a string representing ambiguous paths from a
1656/// specific derived class to different subobjects of the same base
1657/// class.
1658///
1659/// This function builds a string that can be used in error messages
1660/// to show the different paths that one can take through the
1661/// inheritance hierarchy to go from the derived class to different
1662/// subobjects of a base class. The result looks something like this:
1663/// @code
1664/// struct D -> struct B -> struct A
1665/// struct D -> struct C -> struct A
1666/// @endcode
1667std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1668 std::string PathDisplayStr;
1669 std::set<unsigned> DisplayedPaths;
1670 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1671 Path != Paths.end(); ++Path) {
1672 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1673 // We haven't displayed a path to this particular base
1674 // class subobject yet.
1675 PathDisplayStr += "\n ";
1676 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1677 for (CXXBasePath::const_iterator Element = Path->begin();
1678 Element != Path->end(); ++Element)
1679 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1680 }
1681 }
1682
1683 return PathDisplayStr;
1684}
1685
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001686//===----------------------------------------------------------------------===//
1687// C++ class member Handling
1688//===----------------------------------------------------------------------===//
1689
Abramo Bagnara6206d532010-06-05 05:09:32 +00001690/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001691bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1692 SourceLocation ASLoc,
1693 SourceLocation ColonLoc,
1694 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001695 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001696 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001697 ASLoc, ColonLoc);
1698 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001699 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001700}
1701
Richard Smitha4b39652012-08-06 03:25:17 +00001702/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmandae92712013-09-05 23:51:03 +00001703void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001704 if (D->isInvalidDecl())
1705 return;
1706
Eli Friedmandae92712013-09-05 23:51:03 +00001707 // We only care about "override" and "final" declarations.
1708 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1709 return;
Anders Carlsson9e682d92011-01-20 05:57:14 +00001710
Eli Friedmandae92712013-09-05 23:51:03 +00001711 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001712
Eli Friedmandae92712013-09-05 23:51:03 +00001713 // We can't check dependent instance methods.
1714 if (MD && MD->isInstance() &&
1715 (MD->getParent()->hasAnyDependentBases() ||
1716 MD->getType()->isDependentType()))
1717 return;
1718
1719 if (MD && !MD->isVirtual()) {
1720 // If we have a non-virtual method, check if if hides a virtual method.
1721 // (In that case, it's most likely the method has the wrong type.)
1722 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1723 FindHiddenVirtualMethods(MD, OverloadedMethods);
1724
1725 if (!OverloadedMethods.empty()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001726 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1727 Diag(OA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001728 diag::override_keyword_hides_virtual_member_function)
1729 << "override" << (OverloadedMethods.size() > 1);
1730 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001731 Diag(FA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001732 diag::override_keyword_hides_virtual_member_function)
1733 << "final" << (OverloadedMethods.size() > 1);
Richard Smitha4b39652012-08-06 03:25:17 +00001734 }
Eli Friedmandae92712013-09-05 23:51:03 +00001735 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1736 MD->setInvalidDecl();
1737 return;
1738 }
1739 // Fall through into the general case diagnostic.
1740 // FIXME: We might want to attempt typo correction here.
1741 }
1742
1743 if (!MD || !MD->isVirtual()) {
1744 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1745 Diag(OA->getLocation(),
1746 diag::override_keyword_only_allowed_on_virtual_member_functions)
1747 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1748 D->dropAttr<OverrideAttr>();
1749 }
1750 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1751 Diag(FA->getLocation(),
1752 diag::override_keyword_only_allowed_on_virtual_member_functions)
1753 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1754 D->dropAttr<FinalAttr>();
Richard Smitha4b39652012-08-06 03:25:17 +00001755 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001756 return;
1757 }
Richard Smitha4b39652012-08-06 03:25:17 +00001758
Richard Smitha4b39652012-08-06 03:25:17 +00001759 // C++11 [class.virtual]p5:
1760 // If a virtual function is marked with the virt-specifier override and
1761 // does not override a member function of a base class, the program is
1762 // ill-formed.
1763 bool HasOverriddenMethods =
1764 MD->begin_overridden_methods() != MD->end_overridden_methods();
1765 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1766 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1767 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001768}
1769
Richard Smitha4b39652012-08-06 03:25:17 +00001770/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001771/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001772/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001773bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1774 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001775 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001776 return false;
1777
1778 Diag(New->getLocation(), diag::err_final_function_overridden)
1779 << New->getDeclName();
1780 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1781 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001782}
1783
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001784static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001785 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1786 // FIXME: Destruction of ObjC lifetime types has side-effects.
1787 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1788 return !RD->isCompleteDefinition() ||
1789 !RD->hasTrivialDefaultConstructor() ||
1790 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001791 return false;
1792}
1793
John McCall76da55d2013-04-16 07:28:30 +00001794static AttributeList *getMSPropertyAttr(AttributeList *list) {
1795 for (AttributeList* it = list; it != 0; it = it->getNext())
1796 if (it->isDeclspecPropertyAttribute())
1797 return it;
1798 return 0;
1799}
1800
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001801/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1802/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001803/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001804/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1805/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001806NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001807Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001808 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001809 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001810 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001811 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001812 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1813 DeclarationName Name = NameInfo.getName();
1814 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001815
1816 // For anonymous bitfields, the location should point to the type.
1817 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001818 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001819
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001820 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001821
John McCall4bde1e12010-06-04 08:34:12 +00001822 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001823 assert(!DS.isFriendSpecified());
1824
Richard Smith1ab0d902011-06-25 02:28:38 +00001825 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001826
John McCalle402e722012-09-25 07:32:39 +00001827 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1828 // The Microsoft extension __interface only permits public member functions
1829 // and prohibits constructors, destructors, operators, non-public member
1830 // functions, static methods and data members.
1831 unsigned InvalidDecl;
1832 bool ShowDeclName = true;
1833 if (!isFunc)
1834 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1835 else if (AS != AS_public)
1836 InvalidDecl = 2;
1837 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1838 InvalidDecl = 3;
1839 else switch (Name.getNameKind()) {
1840 case DeclarationName::CXXConstructorName:
1841 InvalidDecl = 4;
1842 ShowDeclName = false;
1843 break;
1844
1845 case DeclarationName::CXXDestructorName:
1846 InvalidDecl = 5;
1847 ShowDeclName = false;
1848 break;
1849
1850 case DeclarationName::CXXOperatorName:
1851 case DeclarationName::CXXConversionFunctionName:
1852 InvalidDecl = 6;
1853 break;
1854
1855 default:
1856 InvalidDecl = 0;
1857 break;
1858 }
1859
1860 if (InvalidDecl) {
1861 if (ShowDeclName)
1862 Diag(Loc, diag::err_invalid_member_in_interface)
1863 << (InvalidDecl-1) << Name;
1864 else
1865 Diag(Loc, diag::err_invalid_member_in_interface)
1866 << (InvalidDecl-1) << "";
1867 return 0;
1868 }
1869 }
1870
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001871 // C++ 9.2p6: A member shall not be declared to have automatic storage
1872 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001873 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1874 // data members and cannot be applied to names declared const or static,
1875 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001876 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001877 case DeclSpec::SCS_unspecified:
1878 case DeclSpec::SCS_typedef:
1879 case DeclSpec::SCS_static:
1880 break;
1881 case DeclSpec::SCS_mutable:
1882 if (isFunc) {
1883 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Richard Smithec642442013-04-12 22:46:28 +00001885 // FIXME: It would be nicer if the keyword was ignored only for this
1886 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001887 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001888 }
1889 break;
1890 default:
1891 Diag(DS.getStorageClassSpecLoc(),
1892 diag::err_storageclass_invalid_for_member);
1893 D.getMutableDeclSpec().ClearStorageClassSpecs();
1894 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001895 }
1896
Sebastian Redl669d5d72008-11-14 23:42:31 +00001897 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1898 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001899 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001900
David Blaikie1d87fba2013-01-30 01:22:18 +00001901 if (DS.isConstexprSpecified() && isInstField) {
1902 SemaDiagnosticBuilder B =
1903 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1904 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1905 if (InitStyle == ICIS_NoInit) {
1906 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1907 D.getMutableDeclSpec().ClearConstexprSpec();
1908 const char *PrevSpec;
1909 unsigned DiagID;
1910 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1911 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001912 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001913 assert(!Failed && "Making a constexpr member const shouldn't fail");
1914 } else {
1915 B << 1;
1916 const char *PrevSpec;
1917 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001918 if (D.getMutableDeclSpec().SetStorageClassSpec(
1919 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001920 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001921 "This is the only DeclSpec that should fail to be applied");
1922 B << 1;
1923 } else {
1924 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1925 isInstField = false;
1926 }
1927 }
1928 }
1929
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001930 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001931 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001932 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001933
1934 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001935 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001936 Diag(Loc, diag::err_bad_variable_name)
1937 << Name;
1938 return 0;
1939 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001940
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001941 IdentifierInfo *II = Name.getAsIdentifierInfo();
1942
Douglas Gregorf2503652011-09-21 14:40:46 +00001943 // Member field could not be with "template" keyword.
1944 // So TemplateParameterLists should be empty in this case.
1945 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001946 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001947 if (TemplateParams->size()) {
1948 // There is no such thing as a member field template.
1949 Diag(D.getIdentifierLoc(), diag::err_template_member)
1950 << II
1951 << SourceRange(TemplateParams->getTemplateLoc(),
1952 TemplateParams->getRAngleLoc());
1953 } else {
1954 // There is an extraneous 'template<>' for this member.
1955 Diag(TemplateParams->getTemplateLoc(),
1956 diag::err_template_member_noparams)
1957 << II
1958 << SourceRange(TemplateParams->getTemplateLoc(),
1959 TemplateParams->getRAngleLoc());
1960 }
1961 return 0;
1962 }
1963
Douglas Gregor922fff22010-10-13 22:19:53 +00001964 if (SS.isSet() && !SS.isInvalid()) {
1965 // The user provided a superfluous scope specifier inside a class
1966 // definition:
1967 //
1968 // class X {
1969 // int X::member;
1970 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001971 if (DeclContext *DC = computeDeclContext(SS, false))
1972 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001973 else
1974 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1975 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001976
Douglas Gregor922fff22010-10-13 22:19:53 +00001977 SS.clear();
1978 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001979
John McCall76da55d2013-04-16 07:28:30 +00001980 AttributeList *MSPropertyAttr =
1981 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00001982 if (MSPropertyAttr) {
1983 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1984 BitWidth, InitStyle, AS, MSPropertyAttr);
1985 if (!Member)
1986 return 0;
1987 isInstField = false;
1988 } else {
1989 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1990 BitWidth, InitStyle, AS);
1991 assert(Member && "HandleField never returns null");
1992 }
1993 } else {
1994 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1995
1996 Member = HandleDeclarator(S, D, TemplateParameterLists);
1997 if (!Member)
1998 return 0;
1999
2000 // Non-instance-fields can't have a bitfield.
2001 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002002 if (Member->isInvalidDecl()) {
2003 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002004 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002005 // C++ 9.6p3: A bit-field shall not be a static member.
2006 // "static member 'A' cannot be a bit-field"
2007 Diag(Loc, diag::err_static_not_bitfield)
2008 << Name << BitWidth->getSourceRange();
2009 } else if (isa<TypedefDecl>(Member)) {
2010 // "typedef member 'x' cannot be a bit-field"
2011 Diag(Loc, diag::err_typedef_not_bitfield)
2012 << Name << BitWidth->getSourceRange();
2013 } else {
2014 // A function typedef ("typedef int f(); f a;").
2015 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2016 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00002017 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00002018 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00002019 }
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Chris Lattner8b963ef2009-03-05 23:01:03 +00002021 BitWidth = 0;
2022 Member->setInvalidDecl();
2023 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002024
2025 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Larisse Voufoef4579c2013-08-06 01:03:05 +00002027 // If we have declared a member function template or static data member
2028 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002029 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2030 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002031 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2032 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002033 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002034
Richard Smitha4b39652012-08-06 03:25:17 +00002035 if (VS.isOverrideSpecified())
2036 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2037 if (VS.isFinalSpecified())
2038 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002039
Douglas Gregorf5251602011-03-08 17:10:18 +00002040 if (VS.getLastLocation().isValid()) {
2041 // Update the end location of a method that has a virt-specifiers.
2042 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2043 MD->setRangeEnd(VS.getLastLocation());
2044 }
Richard Smitha4b39652012-08-06 03:25:17 +00002045
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002046 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002047
Douglas Gregor10bd3682008-11-17 22:58:34 +00002048 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002049
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002050 if (isInstField) {
2051 FieldDecl *FD = cast<FieldDecl>(Member);
2052 FieldCollector->Add(FD);
2053
2054 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2055 FD->getLocation())
2056 != DiagnosticsEngine::Ignored) {
2057 // Remember all explicit private FieldDecls that have a name, no side
2058 // effects and are not part of a dependent type declaration.
2059 if (!FD->isImplicit() && FD->getDeclName() &&
2060 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002061 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002062 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002063 !InitializationHasSideEffects(*FD))
2064 UnusedPrivateFields.insert(FD);
2065 }
2066 }
2067
John McCalld226f652010-08-21 09:40:31 +00002068 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002069}
2070
Hans Wennborg471f9852012-09-18 15:58:06 +00002071namespace {
2072 class UninitializedFieldVisitor
2073 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2074 Sema &S;
2075 ValueDecl *VD;
Richard Trieufbb08b52013-09-13 03:20:53 +00002076 bool isReferenceType;
Hans Wennborg471f9852012-09-18 15:58:06 +00002077 public:
2078 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2079 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002080 S(S) {
2081 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2082 this->VD = IFD->getAnonField();
2083 else
2084 this->VD = VD;
Richard Trieufbb08b52013-09-13 03:20:53 +00002085 isReferenceType = this->VD->getType()->isReferenceType();
Hans Wennborg471f9852012-09-18 15:58:06 +00002086 }
2087
Richard Trieu3ddec882013-09-16 20:46:50 +00002088 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
2089 if (CheckReferenceOnly && !isReferenceType)
2090 return;
2091
Richard Trieufbb08b52013-09-13 03:20:53 +00002092 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2093 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002094
Richard Trieufbb08b52013-09-13 03:20:53 +00002095 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2096 // or union.
2097 MemberExpr *FieldME = ME;
2098
2099 Expr *Base = ME;
2100 while (isa<MemberExpr>(Base)) {
2101 ME = cast<MemberExpr>(Base);
2102
2103 if (isa<VarDecl>(ME->getMemberDecl()))
2104 return;
2105
2106 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2107 if (!FD->isAnonymousStructOrUnion())
2108 FieldME = ME;
2109
2110 Base = ME->getBase();
2111 }
2112
Richard Trieu3ddec882013-09-16 20:46:50 +00002113 if (!isa<CXXThisExpr>(Base))
2114 return;
2115
2116 if (VD == FieldME->getMemberDecl()) {
2117 unsigned diag = isReferenceType
Richard Trieufbb08b52013-09-13 03:20:53 +00002118 ? diag::warn_reference_field_is_uninit
2119 : diag::warn_field_is_uninit;
2120 S.Diag(FieldME->getExprLoc(), diag) << VD;
2121 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002122 }
2123
2124 void HandleValue(Expr *E) {
2125 E = E->IgnoreParens();
2126
2127 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002128 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002129 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002130 }
2131
2132 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2133 HandleValue(CO->getTrueExpr());
2134 HandleValue(CO->getFalseExpr());
2135 return;
2136 }
2137
2138 if (BinaryConditionalOperator *BCO =
2139 dyn_cast<BinaryConditionalOperator>(E)) {
2140 HandleValue(BCO->getCommon());
2141 HandleValue(BCO->getFalseExpr());
2142 return;
2143 }
2144
2145 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2146 switch (BO->getOpcode()) {
2147 default:
2148 return;
2149 case(BO_PtrMemD):
2150 case(BO_PtrMemI):
2151 HandleValue(BO->getLHS());
2152 return;
2153 case(BO_Comma):
2154 HandleValue(BO->getRHS());
2155 return;
2156 }
2157 }
2158 }
2159
Richard Trieufbb08b52013-09-13 03:20:53 +00002160 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002161 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002162
2163 Inherited::VisitMemberExpr(ME);
2164 }
2165
Hans Wennborg471f9852012-09-18 15:58:06 +00002166 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2167 if (E->getCastKind() == CK_LValueToRValue)
2168 HandleValue(E->getSubExpr());
2169
2170 Inherited::VisitImplicitCastExpr(E);
2171 }
2172
Richard Trieufbb08b52013-09-13 03:20:53 +00002173 void VisitCXXConstructExpr(CXXConstructExpr *E) {
2174 if (E->getNumArgs() == 1)
2175 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2176 if (ICE->getCastKind() == CK_NoOp)
2177 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieu3ddec882013-09-16 20:46:50 +00002178 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002179
2180 Inherited::VisitCXXConstructExpr(E);
2181 }
2182
Hans Wennborg471f9852012-09-18 15:58:06 +00002183 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2184 Expr *Callee = E->getCallee();
2185 if (isa<MemberExpr>(Callee))
2186 HandleValue(Callee);
2187
2188 Inherited::VisitCXXMemberCallExpr(E);
2189 }
2190 };
2191 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2192 ValueDecl *VD) {
Richard Trieufbb08b52013-09-13 03:20:53 +00002193 if (E)
2194 UninitializedFieldVisitor(S, VD).Visit(E);
Hans Wennborg471f9852012-09-18 15:58:06 +00002195 }
2196} // namespace
2197
Richard Smith7a614d82011-06-11 17:19:42 +00002198/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002199/// in-class initializer for a non-static C++ class member, and after
2200/// instantiating an in-class initializer in a class template. Such actions
2201/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002202void
Richard Smithca523302012-06-10 03:12:00 +00002203Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002204 Expr *InitExpr) {
2205 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002206 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2207 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002208
2209 if (!InitExpr) {
2210 FD->setInvalidDecl();
2211 FD->removeInClassInitializer();
2212 return;
2213 }
2214
Peter Collingbournefef21892011-10-23 18:59:44 +00002215 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2216 FD->setInvalidDecl();
2217 FD->removeInClassInitializer();
2218 return;
2219 }
2220
Richard Smith7a614d82011-06-11 17:19:42 +00002221 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002222 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002223 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002224 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002225 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002226 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002227 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2228 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002229 if (Init.isInvalid()) {
2230 FD->setInvalidDecl();
2231 return;
2232 }
Richard Smith7a614d82011-06-11 17:19:42 +00002233 }
2234
Richard Smith41956372013-01-14 22:39:08 +00002235 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002236 // The initialization of each base and member constitutes a
2237 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002238 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002239 if (Init.isInvalid()) {
2240 FD->setInvalidDecl();
2241 return;
2242 }
2243
2244 InitExpr = Init.release();
2245
Richard Trieufbb08b52013-09-13 03:20:53 +00002246 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2247 != DiagnosticsEngine::Ignored) {
2248 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2249 }
2250
Richard Smith7a614d82011-06-11 17:19:42 +00002251 FD->setInClassInitializer(InitExpr);
2252}
2253
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002254/// \brief Find the direct and/or virtual base specifiers that
2255/// correspond to the given base type, for use in base initialization
2256/// within a constructor.
2257static bool FindBaseInitializer(Sema &SemaRef,
2258 CXXRecordDecl *ClassDecl,
2259 QualType BaseType,
2260 const CXXBaseSpecifier *&DirectBaseSpec,
2261 const CXXBaseSpecifier *&VirtualBaseSpec) {
2262 // First, check for a direct base class.
2263 DirectBaseSpec = 0;
2264 for (CXXRecordDecl::base_class_const_iterator Base
2265 = ClassDecl->bases_begin();
2266 Base != ClassDecl->bases_end(); ++Base) {
2267 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2268 // We found a direct base of this type. That's what we're
2269 // initializing.
2270 DirectBaseSpec = &*Base;
2271 break;
2272 }
2273 }
2274
2275 // Check for a virtual base class.
2276 // FIXME: We might be able to short-circuit this if we know in advance that
2277 // there are no virtual bases.
2278 VirtualBaseSpec = 0;
2279 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2280 // We haven't found a base yet; search the class hierarchy for a
2281 // virtual base class.
2282 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2283 /*DetectVirtual=*/false);
2284 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2285 BaseType, Paths)) {
2286 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2287 Path != Paths.end(); ++Path) {
2288 if (Path->back().Base->isVirtual()) {
2289 VirtualBaseSpec = Path->back().Base;
2290 break;
2291 }
2292 }
2293 }
2294 }
2295
2296 return DirectBaseSpec || VirtualBaseSpec;
2297}
2298
Sebastian Redl6df65482011-09-24 17:48:25 +00002299/// \brief Handle a C++ member initializer using braced-init-list syntax.
2300MemInitResult
2301Sema::ActOnMemInitializer(Decl *ConstructorD,
2302 Scope *S,
2303 CXXScopeSpec &SS,
2304 IdentifierInfo *MemberOrBase,
2305 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002306 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002307 SourceLocation IdLoc,
2308 Expr *InitList,
2309 SourceLocation EllipsisLoc) {
2310 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002311 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002312 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002313}
2314
2315/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002316MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002317Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002318 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002319 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002320 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002321 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002322 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002323 SourceLocation IdLoc,
2324 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002325 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002326 SourceLocation RParenLoc,
2327 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002328 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002329 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002330 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002331 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002332}
2333
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002334namespace {
2335
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002336// Callback to only accept typo corrections that can be a valid C++ member
2337// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002338class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002339public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002340 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2341 : ClassDecl(ClassDecl) {}
2342
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002343 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002344 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2345 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2346 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002347 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002348 }
2349 return false;
2350 }
2351
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002352private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002353 CXXRecordDecl *ClassDecl;
2354};
2355
2356}
2357
Sebastian Redl6df65482011-09-24 17:48:25 +00002358/// \brief Handle a C++ member initializer.
2359MemInitResult
2360Sema::BuildMemInitializer(Decl *ConstructorD,
2361 Scope *S,
2362 CXXScopeSpec &SS,
2363 IdentifierInfo *MemberOrBase,
2364 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002365 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002366 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002367 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002368 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002369 if (!ConstructorD)
2370 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002371
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002372 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002373
2374 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002375 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002376 if (!Constructor) {
2377 // The user wrote a constructor initializer on a function that is
2378 // not a C++ constructor. Ignore the error for now, because we may
2379 // have more member initializers coming; we'll diagnose it just
2380 // once in ActOnMemInitializers.
2381 return true;
2382 }
2383
2384 CXXRecordDecl *ClassDecl = Constructor->getParent();
2385
2386 // C++ [class.base.init]p2:
2387 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002388 // constructor's class and, if not found in that scope, are looked
2389 // up in the scope containing the constructor's definition.
2390 // [Note: if the constructor's class contains a member with the
2391 // same name as a direct or virtual base class of the class, a
2392 // mem-initializer-id naming the member or base class and composed
2393 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002394 // mem-initializer-id for the hidden base class may be specified
2395 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002396 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002397 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002398 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002399 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002400 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002401 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002402 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2403 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002404 if (EllipsisLoc.isValid())
2405 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002406 << MemberOrBase
2407 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002408
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002409 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002410 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002411 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002412 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002413 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002414 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002415 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002416
2417 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002418 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002419 } else if (DS.getTypeSpecType() == TST_decltype) {
2420 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002421 } else {
2422 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2423 LookupParsedName(R, S, &SS);
2424
2425 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2426 if (!TyD) {
2427 if (R.isAmbiguous()) return true;
2428
John McCallfd225442010-04-09 19:01:14 +00002429 // We don't want access-control diagnostics here.
2430 R.suppressDiagnostics();
2431
Douglas Gregor7a886e12010-01-19 06:46:48 +00002432 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2433 bool NotUnknownSpecialization = false;
2434 DeclContext *DC = computeDeclContext(SS, false);
2435 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2436 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2437
2438 if (!NotUnknownSpecialization) {
2439 // When the scope specifier can refer to a member of an unknown
2440 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002441 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2442 SS.getWithLocInContext(Context),
2443 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002444 if (BaseType.isNull())
2445 return true;
2446
Douglas Gregor7a886e12010-01-19 06:46:48 +00002447 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002448 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002449 }
2450 }
2451
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002452 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002453 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002454 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002455 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002456 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002457 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002458 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002459 // We have found a non-static data member with a similar
2460 // name to what was typed; complain and initialize that
2461 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002462 diagnoseTypo(Corr,
2463 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2464 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002465 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002466 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002467 const CXXBaseSpecifier *DirectBaseSpec;
2468 const CXXBaseSpecifier *VirtualBaseSpec;
2469 if (FindBaseInitializer(*this, ClassDecl,
2470 Context.getTypeDeclType(Type),
2471 DirectBaseSpec, VirtualBaseSpec)) {
2472 // We have found a direct or virtual base class with a
2473 // similar name to what was typed; complain and initialize
2474 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002475 diagnoseTypo(Corr,
2476 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2477 << MemberOrBase << false,
2478 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002479
Richard Smith2d670972013-08-17 00:46:16 +00002480 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2481 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002482 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002483 diag::note_base_class_specified_here)
2484 << BaseSpec->getType()
2485 << BaseSpec->getSourceRange();
2486
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002487 TyD = Type;
2488 }
2489 }
2490 }
2491
Douglas Gregor7a886e12010-01-19 06:46:48 +00002492 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002493 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002494 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002495 return true;
2496 }
John McCall2b194412009-12-21 10:41:20 +00002497 }
2498
Douglas Gregor7a886e12010-01-19 06:46:48 +00002499 if (BaseType.isNull()) {
2500 BaseType = Context.getTypeDeclType(TyD);
2501 if (SS.isSet()) {
2502 NestedNameSpecifier *Qualifier =
2503 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002504
Douglas Gregor7a886e12010-01-19 06:46:48 +00002505 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002506 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002507 }
John McCall2b194412009-12-21 10:41:20 +00002508 }
2509 }
Mike Stump1eb44332009-09-09 15:08:12 +00002510
John McCalla93c9342009-12-07 02:54:59 +00002511 if (!TInfo)
2512 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002513
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002514 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002515}
2516
Chandler Carruth81c64772011-09-03 01:14:15 +00002517/// Checks a member initializer expression for cases where reference (or
2518/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002519static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2520 Expr *Init,
2521 SourceLocation IdLoc) {
2522 QualType MemberTy = Member->getType();
2523
2524 // We only handle pointers and references currently.
2525 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2526 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2527 return;
2528
2529 const bool IsPointer = MemberTy->isPointerType();
2530 if (IsPointer) {
2531 if (const UnaryOperator *Op
2532 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2533 // The only case we're worried about with pointers requires taking the
2534 // address.
2535 if (Op->getOpcode() != UO_AddrOf)
2536 return;
2537
2538 Init = Op->getSubExpr();
2539 } else {
2540 // We only handle address-of expression initializers for pointers.
2541 return;
2542 }
2543 }
2544
Richard Smitha4bb99c2013-06-12 21:51:50 +00002545 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002546 // We only warn when referring to a non-reference parameter declaration.
2547 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2548 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002549 return;
2550
2551 S.Diag(Init->getExprLoc(),
2552 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2553 : diag::warn_bind_ref_member_to_parameter)
2554 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002555 } else {
2556 // Other initializers are fine.
2557 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002558 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002559
2560 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2561 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002562}
2563
John McCallf312b1e2010-08-26 23:41:50 +00002564MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002565Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002566 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002567 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2568 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2569 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002570 "Member must be a FieldDecl or IndirectFieldDecl");
2571
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002572 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002573 return true;
2574
Douglas Gregor464b2f02010-11-05 22:21:31 +00002575 if (Member->isInvalidDecl())
2576 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002577
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002578 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002579 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002580 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002581 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002582 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002583 } else {
2584 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002585 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002586 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002587
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002588 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002589
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002590 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002591 // Can't check initialization for a member of dependent type or when
2592 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002593 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002594 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002595 bool InitList = false;
2596 if (isa<InitListExpr>(Init)) {
2597 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002598 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002599 }
2600
Chandler Carruth894aed92010-12-06 09:23:57 +00002601 // Initialize the member.
2602 InitializedEntity MemberEntity =
2603 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2604 : InitializedEntity::InitializeMember(IndirectMember, 0);
2605 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002606 InitList ? InitializationKind::CreateDirectList(IdLoc)
2607 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2608 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002609
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002610 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2611 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002612 if (MemberInit.isInvalid())
2613 return true;
2614
Richard Smith8a07cd32013-06-12 20:42:33 +00002615 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2616
Richard Smith41956372013-01-14 22:39:08 +00002617 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002618 // The initialization of each base and member constitutes a
2619 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002620 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002621 if (MemberInit.isInvalid())
2622 return true;
2623
Richard Smithc83c2302012-12-19 01:39:02 +00002624 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002625 }
2626
Chandler Carruth894aed92010-12-06 09:23:57 +00002627 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002628 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2629 InitRange.getBegin(), Init,
2630 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002631 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002632 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2633 InitRange.getBegin(), Init,
2634 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002635 }
Eli Friedman59c04372009-07-29 19:44:27 +00002636}
2637
John McCallf312b1e2010-08-26 23:41:50 +00002638MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002639Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002640 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002641 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002642 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002643 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002644 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002645 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002646
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002647 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002648 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002649 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2650 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002651 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002652 }
2653
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002654 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002655 // Initialize the object.
2656 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2657 QualType(ClassDecl->getTypeForDecl(), 0));
2658 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002659 InitList ? InitializationKind::CreateDirectList(NameLoc)
2660 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2661 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002662 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002663 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002664 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002665 if (DelegationInit.isInvalid())
2666 return true;
2667
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002668 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2669 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002670
Richard Smith41956372013-01-14 22:39:08 +00002671 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002672 // The initialization of each base and member constitutes a
2673 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002674 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2675 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002676 if (DelegationInit.isInvalid())
2677 return true;
2678
Eli Friedmand21016f2012-05-19 23:35:23 +00002679 // If we are in a dependent context, template instantiation will
2680 // perform this type-checking again. Just save the arguments that we
2681 // received in a ParenListExpr.
2682 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2683 // of the information that we have about the base
2684 // initializer. However, deconstructing the ASTs is a dicey process,
2685 // and this approach is far more likely to get the corner cases right.
2686 if (CurContext->isDependentContext())
2687 DelegationInit = Owned(Init);
2688
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002689 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002690 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002691 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002692}
2693
2694MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002695Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002696 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002697 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002698 SourceLocation BaseLoc
2699 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002700
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002701 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2702 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2703 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2704
2705 // C++ [class.base.init]p2:
2706 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002707 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002708 // of that class, the mem-initializer is ill-formed. A
2709 // mem-initializer-list can initialize a base class using any
2710 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002711 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002712
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002713 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002714 if (EllipsisLoc.isValid()) {
2715 // This is a pack expansion.
2716 if (!BaseType->containsUnexpandedParameterPack()) {
2717 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002718 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002719
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002720 EllipsisLoc = SourceLocation();
2721 }
2722 } else {
2723 // Check for any unexpanded parameter packs.
2724 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2725 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002726
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002727 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002728 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002729 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002730
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002731 // Check for direct and virtual base classes.
2732 const CXXBaseSpecifier *DirectBaseSpec = 0;
2733 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2734 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002735 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2736 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002737 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002738
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002739 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2740 VirtualBaseSpec);
2741
2742 // C++ [base.class.init]p2:
2743 // Unless the mem-initializer-id names a nonstatic data member of the
2744 // constructor's class or a direct or virtual base of that class, the
2745 // mem-initializer is ill-formed.
2746 if (!DirectBaseSpec && !VirtualBaseSpec) {
2747 // If the class has any dependent bases, then it's possible that
2748 // one of those types will resolve to the same type as
2749 // BaseType. Therefore, just treat this as a dependent base
2750 // class initialization. FIXME: Should we try to check the
2751 // initialization anyway? It seems odd.
2752 if (ClassDecl->hasAnyDependentBases())
2753 Dependent = true;
2754 else
2755 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2756 << BaseType << Context.getTypeDeclType(ClassDecl)
2757 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2758 }
2759 }
2760
2761 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002762 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Sebastian Redl6df65482011-09-24 17:48:25 +00002764 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2765 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002766 InitRange.getBegin(), Init,
2767 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002768 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002769
2770 // C++ [base.class.init]p2:
2771 // If a mem-initializer-id is ambiguous because it designates both
2772 // a direct non-virtual base class and an inherited virtual base
2773 // class, the mem-initializer is ill-formed.
2774 if (DirectBaseSpec && VirtualBaseSpec)
2775 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002776 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002777
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002778 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002779 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002780 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002781
2782 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002783 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002784 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002785 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002786 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002787 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002788 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002789
2790 InitializedEntity BaseEntity =
2791 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2792 InitializationKind Kind =
2793 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2794 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2795 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002796 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2797 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002798 if (BaseInit.isInvalid())
2799 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002800
Richard Smith41956372013-01-14 22:39:08 +00002801 // C++11 [class.base.init]p7:
2802 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002803 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002804 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002805 if (BaseInit.isInvalid())
2806 return true;
2807
2808 // If we are in a dependent context, template instantiation will
2809 // perform this type-checking again. Just save the arguments that we
2810 // received in a ParenListExpr.
2811 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2812 // of the information that we have about the base
2813 // initializer. However, deconstructing the ASTs is a dicey process,
2814 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002815 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002816 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002817
Sean Huntcbb67482011-01-08 20:30:50 +00002818 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002819 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002820 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002821 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002822 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002823}
2824
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002825// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002826static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2827 if (T.isNull()) T = E->getType();
2828 QualType TargetType = SemaRef.BuildReferenceType(
2829 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002830 SourceLocation ExprLoc = E->getLocStart();
2831 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2832 TargetType, ExprLoc);
2833
2834 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2835 SourceRange(ExprLoc, ExprLoc),
2836 E->getSourceRange()).take();
2837}
2838
Anders Carlssone5ef7402010-04-23 03:10:23 +00002839/// ImplicitInitializerKind - How an implicit base or member initializer should
2840/// initialize its base or member.
2841enum ImplicitInitializerKind {
2842 IIK_Default,
2843 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002844 IIK_Move,
2845 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002846};
2847
Anders Carlssondefefd22010-04-23 02:00:02 +00002848static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002849BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002850 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002851 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002852 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002853 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002854 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002855 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2856 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002857
John McCall60d7b3a2010-08-24 06:29:42 +00002858 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002859
2860 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002861 case IIK_Inherit: {
2862 const CXXRecordDecl *Inherited =
2863 Constructor->getInheritedConstructor()->getParent();
2864 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2865 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2866 // C++11 [class.inhctor]p8:
2867 // Each expression in the expression-list is of the form
2868 // static_cast<T&&>(p), where p is the name of the corresponding
2869 // constructor parameter and T is the declared type of p.
2870 SmallVector<Expr*, 16> Args;
2871 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2872 ParmVarDecl *PD = Constructor->getParamDecl(I);
2873 ExprResult ArgExpr =
2874 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2875 VK_LValue, SourceLocation());
2876 if (ArgExpr.isInvalid())
2877 return true;
2878 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2879 }
2880
2881 InitializationKind InitKind = InitializationKind::CreateDirect(
2882 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002883 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002884 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2885 break;
2886 }
2887 }
2888 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002889 case IIK_Default: {
2890 InitializationKind InitKind
2891 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002892 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2893 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002894 break;
2895 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002896
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002897 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002898 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002899 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002900 ParmVarDecl *Param = Constructor->getParamDecl(0);
2901 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002902
Anders Carlssone5ef7402010-04-23 03:10:23 +00002903 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002904 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002905 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002906 Constructor->getLocation(), ParamType,
2907 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002908
Eli Friedman5f2987c2012-02-02 03:46:19 +00002909 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2910
Anders Carlssonc7957502010-04-24 22:02:54 +00002911 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002912 QualType ArgTy =
2913 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2914 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002915
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002916 if (Moving) {
2917 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2918 }
2919
John McCallf871d0c2010-08-07 06:22:56 +00002920 CXXCastPath BasePath;
2921 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002922 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2923 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002924 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002925 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002926
Anders Carlssone5ef7402010-04-23 03:10:23 +00002927 InitializationKind InitKind
2928 = InitializationKind::CreateDirect(Constructor->getLocation(),
2929 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002930 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2931 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002932 break;
2933 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002934 }
John McCall9ae2f072010-08-23 23:25:46 +00002935
Douglas Gregor53c374f2010-12-07 00:41:46 +00002936 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002937 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002938 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002939
Anders Carlssondefefd22010-04-23 02:00:02 +00002940 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002941 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002942 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2943 SourceLocation()),
2944 BaseSpec->isVirtual(),
2945 SourceLocation(),
2946 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002947 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002948 SourceLocation());
2949
Anders Carlssondefefd22010-04-23 02:00:02 +00002950 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002951}
2952
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002953static bool RefersToRValueRef(Expr *MemRef) {
2954 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2955 return Referenced->getType()->isRValueReferenceType();
2956}
2957
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002958static bool
2959BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002960 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002961 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002962 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002963 if (Field->isInvalidDecl())
2964 return true;
2965
Chandler Carruthf186b542010-06-29 23:50:44 +00002966 SourceLocation Loc = Constructor->getLocation();
2967
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002968 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2969 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002970 ParmVarDecl *Param = Constructor->getParamDecl(0);
2971 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002972
2973 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002974 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2975 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002976
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002977 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002978 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002979 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002980 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002981
Eli Friedman5f2987c2012-02-02 03:46:19 +00002982 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2983
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002984 if (Moving) {
2985 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2986 }
2987
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002988 // Build a reference to this field within the parameter.
2989 CXXScopeSpec SS;
2990 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2991 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002992 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2993 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002994 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002995 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002996 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002997 ParamType, Loc,
2998 /*IsArrow=*/false,
2999 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003000 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003001 /*FirstQualifierInScope=*/0,
3002 MemberLookup,
3003 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003004 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003005 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003006
3007 // C++11 [class.copy]p15:
3008 // - if a member m has rvalue reference type T&&, it is direct-initialized
3009 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003010 if (RefersToRValueRef(CtorArg.get())) {
3011 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003012 }
3013
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003014 // When the field we are copying is an array, create index variables for
3015 // each dimension of the array. We use these index variables to subscript
3016 // the source array, and other clients (e.g., CodeGen) will perform the
3017 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003018 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003019 QualType BaseType = Field->getType();
3020 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003021 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003022 while (const ConstantArrayType *Array
3023 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003024 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003025 // Create the iteration variable for this array index.
3026 IdentifierInfo *IterationVarName = 0;
3027 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003028 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003029 llvm::raw_svector_ostream OS(Str);
3030 OS << "__i" << IndexVariables.size();
3031 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3032 }
3033 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003034 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003035 IterationVarName, SizeType,
3036 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003037 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003038 IndexVariables.push_back(IterationVar);
3039
3040 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003041 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003042 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003043 assert(!IterationVarRef.isInvalid() &&
3044 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003045 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3046 assert(!IterationVarRef.isInvalid() &&
3047 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003048
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003049 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003050 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003051 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003052 Loc);
3053 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003054 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003055
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003056 BaseType = Array->getElementType();
3057 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003058
3059 // The array subscript expression is an lvalue, which is wrong for moving.
3060 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003061 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003062
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003063 // Construct the entity that we will be initializing. For an array, this
3064 // will be first element in the array, which may require several levels
3065 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003066 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003067 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003068 if (Indirect)
3069 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3070 else
3071 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003072 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3073 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3074 0,
3075 Entities.back()));
3076
3077 // Direct-initialize to use the copy constructor.
3078 InitializationKind InitKind =
3079 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3080
Sebastian Redl74e611a2011-09-04 18:14:28 +00003081 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003082 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003083
John McCall60d7b3a2010-08-24 06:29:42 +00003084 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003085 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003086 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003087 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003088 if (MemberInit.isInvalid())
3089 return true;
3090
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003091 if (Indirect) {
3092 assert(IndexVariables.size() == 0 &&
3093 "Indirect field improperly initialized");
3094 CXXMemberInit
3095 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3096 Loc, Loc,
3097 MemberInit.takeAs<Expr>(),
3098 Loc);
3099 } else
3100 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3101 Loc, MemberInit.takeAs<Expr>(),
3102 Loc,
3103 IndexVariables.data(),
3104 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003105 return false;
3106 }
3107
Richard Smith07b0fdc2013-03-18 21:12:30 +00003108 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3109 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003110
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003111 QualType FieldBaseElementType =
3112 SemaRef.Context.getBaseElementType(Field->getType());
3113
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003114 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003115 InitializedEntity InitEntity
3116 = Indirect? InitializedEntity::InitializeMember(Indirect)
3117 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003118 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003119 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003120
3121 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3122 ExprResult MemberInit =
3123 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003124
Douglas Gregor53c374f2010-12-07 00:41:46 +00003125 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003126 if (MemberInit.isInvalid())
3127 return true;
3128
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003129 if (Indirect)
3130 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3131 Indirect, Loc,
3132 Loc,
3133 MemberInit.get(),
3134 Loc);
3135 else
3136 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3137 Field, Loc, Loc,
3138 MemberInit.get(),
3139 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003140 return false;
3141 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003142
Sean Hunt1f2f3842011-05-17 00:19:05 +00003143 if (!Field->getParent()->isUnion()) {
3144 if (FieldBaseElementType->isReferenceType()) {
3145 SemaRef.Diag(Constructor->getLocation(),
3146 diag::err_uninitialized_member_in_ctor)
3147 << (int)Constructor->isImplicit()
3148 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3149 << 0 << Field->getDeclName();
3150 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3151 return true;
3152 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003153
Sean Hunt1f2f3842011-05-17 00:19:05 +00003154 if (FieldBaseElementType.isConstQualified()) {
3155 SemaRef.Diag(Constructor->getLocation(),
3156 diag::err_uninitialized_member_in_ctor)
3157 << (int)Constructor->isImplicit()
3158 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3159 << 1 << Field->getDeclName();
3160 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3161 return true;
3162 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003163 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003164
David Blaikie4e4d0842012-03-11 07:00:24 +00003165 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003166 FieldBaseElementType->isObjCRetainableType() &&
3167 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3168 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003169 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003170 // Default-initialize Objective-C pointers to NULL.
3171 CXXMemberInit
3172 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3173 Loc, Loc,
3174 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3175 Loc);
3176 return false;
3177 }
3178
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003179 // Nothing to initialize.
3180 CXXMemberInit = 0;
3181 return false;
3182}
John McCallf1860e52010-05-20 23:23:51 +00003183
3184namespace {
3185struct BaseAndFieldInfo {
3186 Sema &S;
3187 CXXConstructorDecl *Ctor;
3188 bool AnyErrorsInInits;
3189 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003190 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003191 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003192
3193 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3194 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003195 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3196 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003197 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003198 else if (Generated && Ctor->isMoveConstructor())
3199 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003200 else if (Ctor->getInheritedConstructor())
3201 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003202 else
3203 IIK = IIK_Default;
3204 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003205
3206 bool isImplicitCopyOrMove() const {
3207 switch (IIK) {
3208 case IIK_Copy:
3209 case IIK_Move:
3210 return true;
3211
3212 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003213 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003214 return false;
3215 }
David Blaikie30263482012-01-20 21:50:17 +00003216
3217 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003218 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003219
3220 bool addFieldInitializer(CXXCtorInitializer *Init) {
3221 AllToInit.push_back(Init);
3222
3223 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003224 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003225 S.UnusedPrivateFields.remove(Init->getAnyMember());
3226
3227 return false;
3228 }
John McCallf1860e52010-05-20 23:23:51 +00003229};
3230}
3231
Richard Smitha4950662011-09-19 13:34:43 +00003232/// \brief Determine whether the given indirect field declaration is somewhere
3233/// within an anonymous union.
3234static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3235 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3236 CEnd = F->chain_end();
3237 C != CEnd; ++C)
3238 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3239 if (Record->isUnion())
3240 return true;
3241
3242 return false;
3243}
3244
Douglas Gregorddb21472011-11-02 23:04:16 +00003245/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3246/// array type.
3247static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3248 if (T->isIncompleteArrayType())
3249 return true;
3250
3251 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3252 if (!ArrayT->getSize())
3253 return true;
3254
3255 T = ArrayT->getElementType();
3256 }
3257
3258 return false;
3259}
3260
Richard Smith7a614d82011-06-11 17:19:42 +00003261static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003262 FieldDecl *Field,
3263 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003264 if (Field->isInvalidDecl())
3265 return false;
John McCallf1860e52010-05-20 23:23:51 +00003266
Chandler Carruthe861c602010-06-30 02:59:29 +00003267 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003268 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3269 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003270
Richard Smith0b8220a2012-08-07 21:30:42 +00003271 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003272 // has a brace-or-equal-initializer, the entity is initialized as specified
3273 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003274 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003275 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3276 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003277 CXXCtorInitializer *Init;
3278 if (Indirect)
3279 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3280 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003281 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003282 SourceLocation());
3283 else
3284 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3285 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003286 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003287 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003288 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003289 }
3290
Richard Smithc115f632011-09-18 11:14:50 +00003291 // Don't build an implicit initializer for union members if none was
3292 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003293 if (Field->getParent()->isUnion() ||
3294 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003295 return false;
3296
Douglas Gregorddb21472011-11-02 23:04:16 +00003297 // Don't initialize incomplete or zero-length arrays.
3298 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3299 return false;
3300
John McCallf1860e52010-05-20 23:23:51 +00003301 // Don't try to build an implicit initializer if there were semantic
3302 // errors in any of the initializers (and therefore we might be
3303 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003304 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003305 return false;
3306
Sean Huntcbb67482011-01-08 20:30:50 +00003307 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003308 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3309 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003310 return true;
John McCallf1860e52010-05-20 23:23:51 +00003311
Richard Smith0b8220a2012-08-07 21:30:42 +00003312 if (!Init)
3313 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003314
Richard Smith0b8220a2012-08-07 21:30:42 +00003315 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003316}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003317
3318bool
3319Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3320 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003321 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003322 Constructor->setNumCtorInitializers(1);
3323 CXXCtorInitializer **initializer =
3324 new (Context) CXXCtorInitializer*[1];
3325 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3326 Constructor->setCtorInitializers(initializer);
3327
Sean Huntb76af9c2011-05-03 23:05:34 +00003328 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003329 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003330 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3331 }
3332
Sean Huntc1598702011-05-05 00:05:47 +00003333 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003334
Sean Hunt059ce0d2011-05-01 07:04:31 +00003335 return false;
3336}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003337
David Blaikie93c86172013-01-17 05:26:25 +00003338bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3339 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003340 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003341 // Just store the initializers as written, they will be checked during
3342 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003343 if (!Initializers.empty()) {
3344 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003345 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003346 new (Context) CXXCtorInitializer*[Initializers.size()];
3347 memcpy(baseOrMemberInitializers, Initializers.data(),
3348 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003349 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003350 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003351
3352 // Let template instantiation know whether we had errors.
3353 if (AnyErrors)
3354 Constructor->setInvalidDecl();
3355
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003356 return false;
3357 }
3358
John McCallf1860e52010-05-20 23:23:51 +00003359 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003360
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003361 // We need to build the initializer AST according to order of construction
3362 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003363 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003364 if (!ClassDecl)
3365 return true;
3366
Eli Friedman80c30da2009-11-09 19:20:36 +00003367 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003368
David Blaikie93c86172013-01-17 05:26:25 +00003369 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003370 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003371
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003372 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003373 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003374 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003375 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003376 }
3377
Anders Carlsson711f34a2010-04-21 19:52:01 +00003378 // Keep track of the direct virtual bases.
3379 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3380 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3381 E = ClassDecl->bases_end(); I != E; ++I) {
3382 if (I->isVirtual())
3383 DirectVBases.insert(I);
3384 }
3385
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003386 // Push virtual bases before others.
3387 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3388 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3389
Sean Huntcbb67482011-01-08 20:30:50 +00003390 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003391 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003392 // [class.base.init]p7, per DR257:
3393 // A mem-initializer where the mem-initializer-id names a virtual base
3394 // class is ignored during execution of a constructor of any class that
3395 // is not the most derived class.
3396 if (ClassDecl->isAbstract()) {
3397 // FIXME: Provide a fixit to remove the base specifier. This requires
3398 // tracking the location of the associated comma for a base specifier.
3399 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3400 << VBase->getType() << ClassDecl;
3401 DiagnoseAbstractType(ClassDecl);
3402 }
3403
John McCallf1860e52010-05-20 23:23:51 +00003404 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003405 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3406 // [class.base.init]p8, per DR257:
3407 // If a given [...] base class is not named by a mem-initializer-id
3408 // [...] and the entity is not a virtual base class of an abstract
3409 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003410 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003411 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003412 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003413 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003414 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003415 HadError = true;
3416 continue;
3417 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003418
John McCallf1860e52010-05-20 23:23:51 +00003419 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003420 }
3421 }
Mike Stump1eb44332009-09-09 15:08:12 +00003422
John McCallf1860e52010-05-20 23:23:51 +00003423 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003424 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3425 E = ClassDecl->bases_end(); Base != E; ++Base) {
3426 // Virtuals are in the virtual base list and already constructed.
3427 if (Base->isVirtual())
3428 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Sean Huntcbb67482011-01-08 20:30:50 +00003430 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003431 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3432 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003433 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003434 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003435 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003436 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003437 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003438 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003439 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003440 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003441
John McCallf1860e52010-05-20 23:23:51 +00003442 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003443 }
3444 }
Mike Stump1eb44332009-09-09 15:08:12 +00003445
John McCallf1860e52010-05-20 23:23:51 +00003446 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003447 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3448 MemEnd = ClassDecl->decls_end();
3449 Mem != MemEnd; ++Mem) {
3450 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003451 // C++ [class.bit]p2:
3452 // A declaration for a bit-field that omits the identifier declares an
3453 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3454 // initialized.
3455 if (F->isUnnamedBitfield())
3456 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003457
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003458 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003459 // handle anonymous struct/union fields based on their individual
3460 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003461 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003462 continue;
3463
3464 if (CollectFieldInitializer(*this, Info, F))
3465 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003466 continue;
3467 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003468
3469 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003470 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003471 continue;
3472
3473 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3474 if (F->getType()->isIncompleteArrayType()) {
3475 assert(ClassDecl->hasFlexibleArrayMember() &&
3476 "Incomplete array type is not valid");
3477 continue;
3478 }
3479
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003480 // Initialize each field of an anonymous struct individually.
3481 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3482 HadError = true;
3483
3484 continue;
3485 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003486 }
Mike Stump1eb44332009-09-09 15:08:12 +00003487
David Blaikie93c86172013-01-17 05:26:25 +00003488 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003489 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003490 Constructor->setNumCtorInitializers(NumInitializers);
3491 CXXCtorInitializer **baseOrMemberInitializers =
3492 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003493 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003494 NumInitializers * sizeof(CXXCtorInitializer*));
3495 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003496
John McCallef027fe2010-03-16 21:39:52 +00003497 // Constructors implicitly reference the base and member
3498 // destructors.
3499 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3500 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003501 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003502
3503 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003504}
3505
David Blaikieee000bb2013-01-17 08:49:22 +00003506static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003507 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003508 const RecordDecl *RD = RT->getDecl();
3509 if (RD->isAnonymousStructOrUnion()) {
3510 for (RecordDecl::field_iterator Field = RD->field_begin(),
3511 E = RD->field_end(); Field != E; ++Field)
3512 PopulateKeysForFields(*Field, IdealInits);
3513 return;
3514 }
Eli Friedman6347f422009-07-21 19:28:10 +00003515 }
David Blaikieee000bb2013-01-17 08:49:22 +00003516 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003517}
3518
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003519static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3520 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003521}
3522
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003523static const void *GetKeyForMember(ASTContext &Context,
3524 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003525 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003526 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003527
David Blaikieee000bb2013-01-17 08:49:22 +00003528 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003529}
3530
David Blaikie93c86172013-01-17 05:26:25 +00003531static void DiagnoseBaseOrMemInitializerOrder(
3532 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3533 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003534 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003535 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003537 // Don't check initializers order unless the warning is enabled at the
3538 // location of at least one initializer.
3539 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003540 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003541 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003542 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3543 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003544 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003545 ShouldCheckOrder = true;
3546 break;
3547 }
3548 }
3549 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003550 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003551
John McCalld6ca8da2010-04-10 07:37:23 +00003552 // Build the list of bases and members in the order that they'll
3553 // actually be initialized. The explicit initializers should be in
3554 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003555 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003556
Anders Carlsson071d6102010-04-02 03:38:04 +00003557 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3558
John McCalld6ca8da2010-04-10 07:37:23 +00003559 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003560 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003561 ClassDecl->vbases_begin(),
3562 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003563 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003564
John McCalld6ca8da2010-04-10 07:37:23 +00003565 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003566 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003567 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003568 if (Base->isVirtual())
3569 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003570 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003571 }
Mike Stump1eb44332009-09-09 15:08:12 +00003572
John McCalld6ca8da2010-04-10 07:37:23 +00003573 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003574 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003575 E = ClassDecl->field_end(); Field != E; ++Field) {
3576 if (Field->isUnnamedBitfield())
3577 continue;
3578
David Blaikieee000bb2013-01-17 08:49:22 +00003579 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003580 }
3581
John McCalld6ca8da2010-04-10 07:37:23 +00003582 unsigned NumIdealInits = IdealInitKeys.size();
3583 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003584
Sean Huntcbb67482011-01-08 20:30:50 +00003585 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003586 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003587 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003588 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003589
3590 // Scan forward to try to find this initializer in the idealized
3591 // initializers list.
3592 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3593 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003594 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003595
3596 // If we didn't find this initializer, it must be because we
3597 // scanned past it on a previous iteration. That can only
3598 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003599 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003600 Sema::SemaDiagnosticBuilder D =
3601 SemaRef.Diag(PrevInit->getSourceLocation(),
3602 diag::warn_initializer_out_of_order);
3603
Francois Pichet00eb3f92010-12-04 09:14:42 +00003604 if (PrevInit->isAnyMemberInitializer())
3605 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003606 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003607 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003608
Francois Pichet00eb3f92010-12-04 09:14:42 +00003609 if (Init->isAnyMemberInitializer())
3610 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003611 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003612 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003613
3614 // Move back to the initializer's location in the ideal list.
3615 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3616 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003617 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003618
3619 assert(IdealIndex != NumIdealInits &&
3620 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003621 }
John McCalld6ca8da2010-04-10 07:37:23 +00003622
3623 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003624 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003625}
3626
John McCall3c3ccdb2010-04-10 09:28:51 +00003627namespace {
3628bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003629 CXXCtorInitializer *Init,
3630 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003631 if (!PrevInit) {
3632 PrevInit = Init;
3633 return false;
3634 }
3635
Douglas Gregordc392c12013-03-25 23:28:23 +00003636 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003637 S.Diag(Init->getSourceLocation(),
3638 diag::err_multiple_mem_initialization)
3639 << Field->getDeclName()
3640 << Init->getSourceRange();
3641 else {
John McCallf4c73712011-01-19 06:33:43 +00003642 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003643 assert(BaseClass && "neither field nor base");
3644 S.Diag(Init->getSourceLocation(),
3645 diag::err_multiple_base_initialization)
3646 << QualType(BaseClass, 0)
3647 << Init->getSourceRange();
3648 }
3649 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3650 << 0 << PrevInit->getSourceRange();
3651
3652 return true;
3653}
3654
Sean Huntcbb67482011-01-08 20:30:50 +00003655typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003656typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3657
3658bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003659 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003660 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003661 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003662 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003663 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003664
3665 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003666 if (Parent->isUnion()) {
3667 UnionEntry &En = Unions[Parent];
3668 if (En.first && En.first != Child) {
3669 S.Diag(Init->getSourceLocation(),
3670 diag::err_multiple_mem_union_initialization)
3671 << Field->getDeclName()
3672 << Init->getSourceRange();
3673 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3674 << 0 << En.second->getSourceRange();
3675 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003676 }
3677 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003678 En.first = Child;
3679 En.second = Init;
3680 }
David Blaikie6fe29652011-11-17 06:01:57 +00003681 if (!Parent->isAnonymousStructOrUnion())
3682 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003683 }
3684
3685 Child = Parent;
3686 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003687 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003688
3689 return false;
3690}
3691}
3692
Richard Trieu225e9822013-09-16 21:54:53 +00003693// Diagnose value-uses of fields to initialize themselves, e.g.
3694// foo(foo)
3695// where foo is not also a parameter to the constructor.
3696// TODO: implement -Wuninitialized and fold this into that framework.
3697// FIXME: Warn about the case when other fields are used before being
3698// initialized. For example, let this field be the i'th field. When
3699// initializing the i'th field, throw a warning if any of the >= i'th
3700// fields are used, as they are not yet initialized.
3701// Right now we are only handling the case where the i'th field uses
3702// itself in its initializer.
3703// Also need to take into account that some fields may be initialized by
3704// in-class initializers, see C++11 [class.base.init]p9.
3705static void DiagnoseUnitializedFields(
3706 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3707
3708 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
3709 Constructor->getLocation())
3710 == DiagnosticsEngine::Ignored) {
3711 return;
3712 }
3713
3714 for (CXXConstructorDecl::init_const_iterator
3715 FieldInit = Constructor->init_begin(),
3716 FieldInitEnd = Constructor->init_end();
3717 FieldInit != FieldInitEnd; ++FieldInit) {
3718
3719 FieldDecl *FD = (*FieldInit)->getAnyMember();
3720 if (!FD)
3721 continue;
3722 Expr *InitExpr = (*FieldInit)->getInit();
3723
3724 if (!isa<CXXDefaultInitExpr>(InitExpr)) {
3725 CheckInitExprContainsUninitializedFields(SemaRef, InitExpr, FD);
3726 }
3727 }
3728}
3729
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003730/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003731void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003732 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003733 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003734 bool AnyErrors) {
3735 if (!ConstructorDecl)
3736 return;
3737
3738 AdjustDeclIfTemplate(ConstructorDecl);
3739
3740 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003741 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003742
3743 if (!Constructor) {
3744 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3745 return;
3746 }
3747
John McCall3c3ccdb2010-04-10 09:28:51 +00003748 // Mapping for the duplicate initializers check.
3749 // For member initializers, this is keyed with a FieldDecl*.
3750 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003751 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003752
3753 // Mapping for the inconsistent anonymous-union initializers check.
3754 RedundantUnionMap MemberUnions;
3755
Anders Carlssonea356fb2010-04-02 05:42:15 +00003756 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003757 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003758 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003759
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003760 // Set the source order index.
3761 Init->setSourceOrder(i);
3762
Francois Pichet00eb3f92010-12-04 09:14:42 +00003763 if (Init->isAnyMemberInitializer()) {
3764 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003765 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3766 CheckRedundantUnionInit(*this, Init, MemberUnions))
3767 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003768 } else if (Init->isBaseInitializer()) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003769 const void *Key =
3770 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall3c3ccdb2010-04-10 09:28:51 +00003771 if (CheckRedundantInit(*this, Init, Members[Key]))
3772 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003773 } else {
3774 assert(Init->isDelegatingInitializer());
3775 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003776 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003777 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003778 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003779 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003780 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003781 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003782 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003783 // Return immediately as the initializer is set.
3784 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003785 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003786 }
3787
Anders Carlssonea356fb2010-04-02 05:42:15 +00003788 if (HadError)
3789 return;
3790
David Blaikie93c86172013-01-17 05:26:25 +00003791 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003792
David Blaikie93c86172013-01-17 05:26:25 +00003793 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu225e9822013-09-16 21:54:53 +00003794
3795 DiagnoseUnitializedFields(*this, Constructor);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003796}
3797
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003798void
John McCallef027fe2010-03-16 21:39:52 +00003799Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3800 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003801 // Ignore dependent contexts. Also ignore unions, since their members never
3802 // have destructors implicitly called.
3803 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003804 return;
John McCall58e6f342010-03-16 05:22:47 +00003805
3806 // FIXME: all the access-control diagnostics are positioned on the
3807 // field/base declaration. That's probably good; that said, the
3808 // user might reasonably want to know why the destructor is being
3809 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003810
Anders Carlsson9f853df2009-11-17 04:44:12 +00003811 // Non-static data members.
3812 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3813 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003814 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003815 if (Field->isInvalidDecl())
3816 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003817
3818 // Don't destroy incomplete or zero-length arrays.
3819 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3820 continue;
3821
Anders Carlsson9f853df2009-11-17 04:44:12 +00003822 QualType FieldType = Context.getBaseElementType(Field->getType());
3823
3824 const RecordType* RT = FieldType->getAs<RecordType>();
3825 if (!RT)
3826 continue;
3827
3828 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003829 if (FieldClassDecl->isInvalidDecl())
3830 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003831 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003832 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003833 // The destructor for an implicit anonymous union member is never invoked.
3834 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3835 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003836
Douglas Gregordb89f282010-07-01 22:47:18 +00003837 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003838 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003839 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003840 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003841 << Field->getDeclName()
3842 << FieldType);
3843
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003844 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003845 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003846 }
3847
John McCall58e6f342010-03-16 05:22:47 +00003848 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3849
Anders Carlsson9f853df2009-11-17 04:44:12 +00003850 // Bases.
3851 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3852 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003853 // Bases are always records in a well-formed non-dependent class.
3854 const RecordType *RT = Base->getType()->getAs<RecordType>();
3855
3856 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003857 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003858 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003859
John McCall58e6f342010-03-16 05:22:47 +00003860 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003861 // If our base class is invalid, we probably can't get its dtor anyway.
3862 if (BaseClassDecl->isInvalidDecl())
3863 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003864 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003865 continue;
John McCall58e6f342010-03-16 05:22:47 +00003866
Douglas Gregordb89f282010-07-01 22:47:18 +00003867 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003868 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003869
3870 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003871 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003872 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003873 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003874 << Base->getSourceRange(),
3875 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003876
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003877 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003878 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003879 }
3880
3881 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003882 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3883 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003884
3885 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003886 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003887
3888 // Ignore direct virtual bases.
3889 if (DirectVirtualBases.count(RT))
3890 continue;
3891
John McCall58e6f342010-03-16 05:22:47 +00003892 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003893 // If our base class is invalid, we probably can't get its dtor anyway.
3894 if (BaseClassDecl->isInvalidDecl())
3895 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003896 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003897 continue;
John McCall58e6f342010-03-16 05:22:47 +00003898
Douglas Gregordb89f282010-07-01 22:47:18 +00003899 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003900 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00003901 if (CheckDestructorAccess(
3902 ClassDecl->getLocation(), Dtor,
3903 PDiag(diag::err_access_dtor_vbase)
3904 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3905 Context.getTypeDeclType(ClassDecl)) ==
3906 AR_accessible) {
3907 CheckDerivedToBaseConversion(
3908 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3909 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3910 SourceRange(), DeclarationName(), 0);
3911 }
John McCall58e6f342010-03-16 05:22:47 +00003912
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003913 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003914 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003915 }
3916}
3917
John McCalld226f652010-08-21 09:40:31 +00003918void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003919 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003920 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003921
Mike Stump1eb44332009-09-09 15:08:12 +00003922 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003923 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003924 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003925}
3926
Mike Stump1eb44332009-09-09 15:08:12 +00003927bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003928 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003929 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3930 unsigned DiagID;
3931 AbstractDiagSelID SelID;
3932
3933 public:
3934 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3935 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003936
3937 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman2217f852012-08-14 02:06:07 +00003938 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003939 if (SelID == -1)
3940 S.Diag(Loc, DiagID) << T;
3941 else
3942 S.Diag(Loc, DiagID) << SelID << T;
3943 }
3944 } Diagnoser(DiagID, SelID);
3945
3946 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003947}
3948
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003949bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003950 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003951 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003952 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003953
Anders Carlsson11f21a02009-03-23 19:10:31 +00003954 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003955 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003956
Ted Kremenek6217b802009-07-29 21:53:49 +00003957 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003958 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003959 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003960 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003961
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003962 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003963 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003964 }
Mike Stump1eb44332009-09-09 15:08:12 +00003965
Ted Kremenek6217b802009-07-29 21:53:49 +00003966 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003967 if (!RT)
3968 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003969
John McCall86ff3082010-02-04 22:26:26 +00003970 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003971
John McCall94c3b562010-08-18 09:41:07 +00003972 // We can't answer whether something is abstract until it has a
3973 // definition. If it's currently being defined, we'll walk back
3974 // over all the declarations when we have a full definition.
3975 const CXXRecordDecl *Def = RD->getDefinition();
3976 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003977 return false;
3978
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003979 if (!RD->isAbstract())
3980 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003981
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003982 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003983 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003984
John McCall94c3b562010-08-18 09:41:07 +00003985 return true;
3986}
3987
3988void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3989 // Check if we've already emitted the list of pure virtual functions
3990 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003991 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003992 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003993
Richard Smithcbc820a2013-07-22 02:56:56 +00003994 // If the diagnostic is suppressed, don't emit the notes. We're only
3995 // going to emit them once, so try to attach them to a diagnostic we're
3996 // actually going to show.
3997 if (Diags.isLastDiagnosticIgnored())
3998 return;
3999
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004000 CXXFinalOverriderMap FinalOverriders;
4001 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00004002
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004003 // Keep a set of seen pure methods so we won't diagnose the same method
4004 // more than once.
4005 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4006
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004007 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4008 MEnd = FinalOverriders.end();
4009 M != MEnd;
4010 ++M) {
4011 for (OverridingMethods::iterator SO = M->second.begin(),
4012 SOEnd = M->second.end();
4013 SO != SOEnd; ++SO) {
4014 // C++ [class.abstract]p4:
4015 // A class is abstract if it contains or inherits at least one
4016 // pure virtual function for which the final overrider is pure
4017 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00004018
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004019 //
4020 if (SO->second.size() != 1)
4021 continue;
4022
4023 if (!SO->second.front().Method->isPure())
4024 continue;
4025
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004026 if (!SeenPureMethods.insert(SO->second.front().Method))
4027 continue;
4028
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004029 Diag(SO->second.front().Method->getLocation(),
4030 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00004031 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004032 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004033 }
4034
4035 if (!PureVirtualClassDiagSet)
4036 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4037 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004038}
4039
Anders Carlsson8211eff2009-03-24 01:19:16 +00004040namespace {
John McCall94c3b562010-08-18 09:41:07 +00004041struct AbstractUsageInfo {
4042 Sema &S;
4043 CXXRecordDecl *Record;
4044 CanQualType AbstractType;
4045 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00004046
John McCall94c3b562010-08-18 09:41:07 +00004047 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4048 : S(S), Record(Record),
4049 AbstractType(S.Context.getCanonicalType(
4050 S.Context.getTypeDeclType(Record))),
4051 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00004052
John McCall94c3b562010-08-18 09:41:07 +00004053 void DiagnoseAbstractType() {
4054 if (Invalid) return;
4055 S.DiagnoseAbstractType(Record);
4056 Invalid = true;
4057 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00004058
John McCall94c3b562010-08-18 09:41:07 +00004059 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4060};
4061
4062struct CheckAbstractUsage {
4063 AbstractUsageInfo &Info;
4064 const NamedDecl *Ctx;
4065
4066 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4067 : Info(Info), Ctx(Ctx) {}
4068
4069 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4070 switch (TL.getTypeLocClass()) {
4071#define ABSTRACT_TYPELOC(CLASS, PARENT)
4072#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004073 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004074#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004075 }
John McCall94c3b562010-08-18 09:41:07 +00004076 }
Mike Stump1eb44332009-09-09 15:08:12 +00004077
John McCall94c3b562010-08-18 09:41:07 +00004078 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4079 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4080 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00004081 if (!TL.getArg(I))
4082 continue;
4083
John McCall94c3b562010-08-18 09:41:07 +00004084 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4085 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004086 }
John McCall94c3b562010-08-18 09:41:07 +00004087 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004088
John McCall94c3b562010-08-18 09:41:07 +00004089 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4090 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4091 }
Mike Stump1eb44332009-09-09 15:08:12 +00004092
John McCall94c3b562010-08-18 09:41:07 +00004093 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4094 // Visit the type parameters from a permissive context.
4095 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4096 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4097 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4098 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4099 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4100 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004101 }
John McCall94c3b562010-08-18 09:41:07 +00004102 }
Mike Stump1eb44332009-09-09 15:08:12 +00004103
John McCall94c3b562010-08-18 09:41:07 +00004104 // Visit pointee types from a permissive context.
4105#define CheckPolymorphic(Type) \
4106 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4107 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4108 }
4109 CheckPolymorphic(PointerTypeLoc)
4110 CheckPolymorphic(ReferenceTypeLoc)
4111 CheckPolymorphic(MemberPointerTypeLoc)
4112 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004113 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004114
John McCall94c3b562010-08-18 09:41:07 +00004115 /// Handle all the types we haven't given a more specific
4116 /// implementation for above.
4117 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4118 // Every other kind of type that we haven't called out already
4119 // that has an inner type is either (1) sugar or (2) contains that
4120 // inner type in some way as a subobject.
4121 if (TypeLoc Next = TL.getNextTypeLoc())
4122 return Visit(Next, Sel);
4123
4124 // If there's no inner type and we're in a permissive context,
4125 // don't diagnose.
4126 if (Sel == Sema::AbstractNone) return;
4127
4128 // Check whether the type matches the abstract type.
4129 QualType T = TL.getType();
4130 if (T->isArrayType()) {
4131 Sel = Sema::AbstractArrayType;
4132 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004133 }
John McCall94c3b562010-08-18 09:41:07 +00004134 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4135 if (CT != Info.AbstractType) return;
4136
4137 // It matched; do some magic.
4138 if (Sel == Sema::AbstractArrayType) {
4139 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4140 << T << TL.getSourceRange();
4141 } else {
4142 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4143 << Sel << T << TL.getSourceRange();
4144 }
4145 Info.DiagnoseAbstractType();
4146 }
4147};
4148
4149void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4150 Sema::AbstractDiagSelID Sel) {
4151 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4152}
4153
4154}
4155
4156/// Check for invalid uses of an abstract type in a method declaration.
4157static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4158 CXXMethodDecl *MD) {
4159 // No need to do the check on definitions, which require that
4160 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004161 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004162 return;
4163
4164 // For safety's sake, just ignore it if we don't have type source
4165 // information. This should never happen for non-implicit methods,
4166 // but...
4167 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4168 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4169}
4170
4171/// Check for invalid uses of an abstract type within a class definition.
4172static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4173 CXXRecordDecl *RD) {
4174 for (CXXRecordDecl::decl_iterator
4175 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4176 Decl *D = *I;
4177 if (D->isImplicit()) continue;
4178
4179 // Methods and method templates.
4180 if (isa<CXXMethodDecl>(D)) {
4181 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4182 } else if (isa<FunctionTemplateDecl>(D)) {
4183 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4184 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4185
4186 // Fields and static variables.
4187 } else if (isa<FieldDecl>(D)) {
4188 FieldDecl *FD = cast<FieldDecl>(D);
4189 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4190 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4191 } else if (isa<VarDecl>(D)) {
4192 VarDecl *VD = cast<VarDecl>(D);
4193 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4194 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4195
4196 // Nested classes and class templates.
4197 } else if (isa<CXXRecordDecl>(D)) {
4198 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4199 } else if (isa<ClassTemplateDecl>(D)) {
4200 CheckAbstractClassUsage(Info,
4201 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4202 }
4203 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004204}
4205
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004206/// \brief Perform semantic checks on a class definition that has been
4207/// completing, introducing implicitly-declared members, checking for
4208/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004209void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004210 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004211 return;
4212
John McCall94c3b562010-08-18 09:41:07 +00004213 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4214 AbstractUsageInfo Info(*this, Record);
4215 CheckAbstractClassUsage(Info, Record);
4216 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004217
4218 // If this is not an aggregate type and has no user-declared constructor,
4219 // complain about any non-static data members of reference or const scalar
4220 // type, since they will never get initializers.
4221 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004222 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4223 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004224 bool Complained = false;
4225 for (RecordDecl::field_iterator F = Record->field_begin(),
4226 FEnd = Record->field_end();
4227 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004228 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004229 continue;
4230
Douglas Gregor325e5932010-04-15 00:00:53 +00004231 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004232 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004233 if (!Complained) {
4234 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4235 << Record->getTagKind() << Record;
4236 Complained = true;
4237 }
4238
4239 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4240 << F->getType()->isReferenceType()
4241 << F->getDeclName();
4242 }
4243 }
4244 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004245
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004246 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004247 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004248
4249 if (Record->getIdentifier()) {
4250 // C++ [class.mem]p13:
4251 // If T is the name of a class, then each of the following shall have a
4252 // name different from T:
4253 // - every member of every anonymous union that is a member of class T.
4254 //
4255 // C++ [class.mem]p14:
4256 // In addition, if class T has a user-declared constructor (12.1), every
4257 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004258 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4259 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4260 ++I) {
4261 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004262 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4263 isa<IndirectFieldDecl>(D)) {
4264 Diag(D->getLocation(), diag::err_member_name_of_class)
4265 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004266 break;
4267 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004268 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004269 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004270
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004271 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004272 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004273 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004274 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004275 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4276 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4277 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004278
David Blaikieb6b5b972012-09-21 03:21:07 +00004279 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4280 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4281 DiagnoseAbstractType(Record);
4282 }
4283
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004284 if (!Record->isDependentType()) {
4285 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4286 MEnd = Record->method_end();
4287 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004288 // See if a method overloads virtual methods in a base
4289 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004290 if (!M->isStatic())
Eli Friedmandae92712013-09-05 23:51:03 +00004291 DiagnoseHiddenVirtualMethods(*M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004292
4293 // Check whether the explicitly-defaulted special members are valid.
4294 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4295 CheckExplicitlyDefaultedSpecialMember(*M);
4296
4297 // For an explicitly defaulted or deleted special member, we defer
4298 // determining triviality until the class is complete. That time is now!
4299 if (!M->isImplicit() && !M->isUserProvided()) {
4300 CXXSpecialMember CSM = getSpecialMember(*M);
4301 if (CSM != CXXInvalid) {
4302 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4303
4304 // Inform the class that we've finished declaring this member.
4305 Record->finishedDefaultedOrDeletedMember(*M);
4306 }
4307 }
4308 }
4309 }
4310
4311 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4312 // function that is not a constructor declares that member function to be
4313 // const. [...] The class of which that function is a member shall be
4314 // a literal type.
4315 //
4316 // If the class has virtual bases, any constexpr members will already have
4317 // been diagnosed by the checks performed on the member declaration, so
4318 // suppress this (less useful) diagnostic.
4319 //
4320 // We delay this until we know whether an explicitly-defaulted (or deleted)
4321 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004322 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004323 !Record->isLiteral() && !Record->getNumVBases()) {
4324 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4325 MEnd = Record->method_end();
4326 M != MEnd; ++M) {
4327 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4328 switch (Record->getTemplateSpecializationKind()) {
4329 case TSK_ImplicitInstantiation:
4330 case TSK_ExplicitInstantiationDeclaration:
4331 case TSK_ExplicitInstantiationDefinition:
4332 // If a template instantiates to a non-literal type, but its members
4333 // instantiate to constexpr functions, the template is technically
4334 // ill-formed, but we allow it for sanity.
4335 continue;
4336
4337 case TSK_Undeclared:
4338 case TSK_ExplicitSpecialization:
4339 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4340 diag::err_constexpr_method_non_literal);
4341 break;
4342 }
4343
4344 // Only produce one error per class.
4345 break;
4346 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004347 }
4348 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004349
Richard Smith07b0fdc2013-03-18 21:12:30 +00004350 // Declare inheriting constructors. We do this eagerly here because:
4351 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004352 // constructors from different classes.
4353 // - The lazy declaration of the other implicit constructors is so as to not
4354 // waste space and performance on classes that are not meant to be
4355 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004356 // have inheriting constructors.
4357 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004358}
4359
Richard Smith7756afa2012-06-10 05:43:50 +00004360/// Is the special member function which would be selected to perform the
4361/// specified operation on the specified class type a constexpr constructor?
4362static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4363 Sema::CXXSpecialMember CSM,
4364 bool ConstArg) {
4365 Sema::SpecialMemberOverloadResult *SMOR =
4366 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4367 false, false, false, false);
4368 if (!SMOR || !SMOR->getMethod())
4369 // A constructor we wouldn't select can't be "involved in initializing"
4370 // anything.
4371 return true;
4372 return SMOR->getMethod()->isConstexpr();
4373}
4374
4375/// Determine whether the specified special member function would be constexpr
4376/// if it were implicitly defined.
4377static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4378 Sema::CXXSpecialMember CSM,
4379 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004380 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004381 return false;
4382
4383 // C++11 [dcl.constexpr]p4:
4384 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004385 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004386 switch (CSM) {
4387 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004388 // Since default constructor lookup is essentially trivial (and cannot
4389 // involve, for instance, template instantiation), we compute whether a
4390 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4391 //
4392 // This is important for performance; we need to know whether the default
4393 // constructor is constexpr to determine whether the type is a literal type.
4394 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4395
Richard Smith7756afa2012-06-10 05:43:50 +00004396 case Sema::CXXCopyConstructor:
4397 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004398 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004399 break;
4400
4401 case Sema::CXXCopyAssignment:
4402 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004403 if (!S.getLangOpts().CPlusPlus1y)
4404 return false;
4405 // In C++1y, we need to perform overload resolution.
4406 Ctor = false;
4407 break;
4408
Richard Smith7756afa2012-06-10 05:43:50 +00004409 case Sema::CXXDestructor:
4410 case Sema::CXXInvalid:
4411 return false;
4412 }
4413
4414 // -- if the class is a non-empty union, or for each non-empty anonymous
4415 // union member of a non-union class, exactly one non-static data member
4416 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004417 //
4418 // If we squint, this is guaranteed, since exactly one non-static data member
4419 // will be initialized (if the constructor isn't deleted), we just don't know
4420 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004421 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004422 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004423
4424 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004425 if (Ctor && ClassDecl->getNumVBases())
4426 return false;
4427
4428 // C++1y [class.copy]p26:
4429 // -- [the class] is a literal type, and
4430 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004431 return false;
4432
4433 // -- every constructor involved in initializing [...] base class
4434 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004435 // -- the assignment operator selected to copy/move each direct base
4436 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004437 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4438 BEnd = ClassDecl->bases_end();
4439 B != BEnd; ++B) {
4440 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4441 if (!BaseType) continue;
4442
4443 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4444 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4445 return false;
4446 }
4447
4448 // -- every constructor involved in initializing non-static data members
4449 // [...] shall be a constexpr constructor;
4450 // -- every non-static data member and base class sub-object shall be
4451 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004452 // -- for each non-stastic data member of X that is of class type (or array
4453 // thereof), the assignment operator selected to copy/move that member is
4454 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004455 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4456 FEnd = ClassDecl->field_end();
4457 F != FEnd; ++F) {
4458 if (F->isInvalidDecl())
4459 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004460 if (const RecordType *RecordTy =
4461 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004462 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4463 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4464 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004465 }
4466 }
4467
4468 // All OK, it's constexpr!
4469 return true;
4470}
4471
Richard Smithb9d0b762012-07-27 04:22:15 +00004472static Sema::ImplicitExceptionSpecification
4473computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4474 switch (S.getSpecialMember(MD)) {
4475 case Sema::CXXDefaultConstructor:
4476 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4477 case Sema::CXXCopyConstructor:
4478 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4479 case Sema::CXXCopyAssignment:
4480 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4481 case Sema::CXXMoveConstructor:
4482 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4483 case Sema::CXXMoveAssignment:
4484 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4485 case Sema::CXXDestructor:
4486 return S.ComputeDefaultedDtorExceptionSpec(MD);
4487 case Sema::CXXInvalid:
4488 break;
4489 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004490 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4491 "only special members have implicit exception specs");
4492 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004493}
4494
Richard Smithdd25e802012-07-30 23:48:14 +00004495static void
4496updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4497 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4498 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4499 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004500 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4501 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004502}
4503
Reid Kleckneref072032013-08-27 23:08:25 +00004504static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4505 CXXMethodDecl *MD) {
4506 FunctionProtoType::ExtProtoInfo EPI;
4507
4508 // Build an exception specification pointing back at this member.
4509 EPI.ExceptionSpecType = EST_Unevaluated;
4510 EPI.ExceptionSpecDecl = MD;
4511
4512 // Set the calling convention to the default for C++ instance methods.
4513 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4514 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4515 /*IsCXXMethod=*/true));
4516 return EPI;
4517}
4518
Richard Smithb9d0b762012-07-27 04:22:15 +00004519void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4520 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4521 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4522 return;
4523
Richard Smithdd25e802012-07-30 23:48:14 +00004524 // Evaluate the exception specification.
4525 ImplicitExceptionSpecification ExceptSpec =
4526 computeImplicitExceptionSpec(*this, Loc, MD);
4527
4528 // Update the type of the special member to use it.
4529 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4530
4531 // A user-provided destructor can be defined outside the class. When that
4532 // happens, be sure to update the exception specification on both
4533 // declarations.
4534 const FunctionProtoType *CanonicalFPT =
4535 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4536 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4537 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4538 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004539}
4540
Richard Smith3003e1d2012-05-15 04:39:51 +00004541void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4542 CXXRecordDecl *RD = MD->getParent();
4543 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004544
Richard Smith3003e1d2012-05-15 04:39:51 +00004545 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4546 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004547
4548 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004549 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004550 bool First = MD == MD->getCanonicalDecl();
4551
4552 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004553
4554 // C++11 [dcl.fct.def.default]p1:
4555 // A function that is explicitly defaulted shall
4556 // -- be a special member function (checked elsewhere),
4557 // -- have the same type (except for ref-qualifiers, and except that a
4558 // copy operation can take a non-const reference) as an implicit
4559 // declaration, and
4560 // -- not have default arguments.
4561 unsigned ExpectedParams = 1;
4562 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4563 ExpectedParams = 0;
4564 if (MD->getNumParams() != ExpectedParams) {
4565 // This also checks for default arguments: a copy or move constructor with a
4566 // default argument is classified as a default constructor, and assignment
4567 // operations and destructors can't have default arguments.
4568 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4569 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004570 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004571 } else if (MD->isVariadic()) {
4572 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4573 << CSM << MD->getSourceRange();
4574 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004575 }
4576
Richard Smith3003e1d2012-05-15 04:39:51 +00004577 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004578
Richard Smith7756afa2012-06-10 05:43:50 +00004579 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004580 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004581 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004582 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004583 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004584
Richard Smith3003e1d2012-05-15 04:39:51 +00004585 QualType ReturnType = Context.VoidTy;
4586 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4587 // Check for return type matching.
4588 ReturnType = Type->getResultType();
4589 QualType ExpectedReturnType =
4590 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4591 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4592 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4593 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4594 HadError = true;
4595 }
4596
4597 // A defaulted special member cannot have cv-qualifiers.
4598 if (Type->getTypeQuals()) {
4599 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004600 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004601 HadError = true;
4602 }
4603 }
4604
4605 // Check for parameter type matching.
4606 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004607 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004608 if (ExpectedParams && ArgType->isReferenceType()) {
4609 // Argument must be reference to possibly-const T.
4610 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004611 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004612
4613 if (ReferentType.isVolatileQualified()) {
4614 Diag(MD->getLocation(),
4615 diag::err_defaulted_special_member_volatile_param) << CSM;
4616 HadError = true;
4617 }
4618
Richard Smith7756afa2012-06-10 05:43:50 +00004619 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004620 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4621 Diag(MD->getLocation(),
4622 diag::err_defaulted_special_member_copy_const_param)
4623 << (CSM == CXXCopyAssignment);
4624 // FIXME: Explain why this special member can't be const.
4625 } else {
4626 Diag(MD->getLocation(),
4627 diag::err_defaulted_special_member_move_const_param)
4628 << (CSM == CXXMoveAssignment);
4629 }
4630 HadError = true;
4631 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004632 } else if (ExpectedParams) {
4633 // A copy assignment operator can take its argument by value, but a
4634 // defaulted one cannot.
4635 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004636 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004637 HadError = true;
4638 }
Sean Huntbe631222011-05-17 20:44:43 +00004639
Richard Smith61802452011-12-22 02:22:31 +00004640 // C++11 [dcl.fct.def.default]p2:
4641 // An explicitly-defaulted function may be declared constexpr only if it
4642 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004643 // Do not apply this rule to members of class templates, since core issue 1358
4644 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004645 // functions which cannot be constexpr (for non-constructors in C++11 and for
4646 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004647 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4648 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004649 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4650 : isa<CXXConstructorDecl>(MD)) &&
4651 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004652 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4653 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004654 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004655 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004656 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004657
Richard Smith61802452011-12-22 02:22:31 +00004658 // and may have an explicit exception-specification only if it is compatible
4659 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004660 if (Type->hasExceptionSpec()) {
4661 // Delay the check if this is the first declaration of the special member,
4662 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004663 if (First) {
4664 // If the exception specification needs to be instantiated, do so now,
4665 // before we clobber it with an EST_Unevaluated specification below.
4666 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4667 InstantiateExceptionSpec(MD->getLocStart(), MD);
4668 Type = MD->getType()->getAs<FunctionProtoType>();
4669 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004670 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004671 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004672 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4673 }
Richard Smith61802452011-12-22 02:22:31 +00004674
4675 // If a function is explicitly defaulted on its first declaration,
4676 if (First) {
4677 // -- it is implicitly considered to be constexpr if the implicit
4678 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004679 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004680
Richard Smith3003e1d2012-05-15 04:39:51 +00004681 // -- it is implicitly considered to have the same exception-specification
4682 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004683 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4684 EPI.ExceptionSpecType = EST_Unevaluated;
4685 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004686 MD->setType(Context.getFunctionType(ReturnType,
4687 ArrayRef<QualType>(&ArgType,
4688 ExpectedParams),
4689 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004690 }
4691
Richard Smith3003e1d2012-05-15 04:39:51 +00004692 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004693 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004694 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004695 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004696 // C++11 [dcl.fct.def.default]p4:
4697 // [For a] user-provided explicitly-defaulted function [...] if such a
4698 // function is implicitly defined as deleted, the program is ill-formed.
4699 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4700 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004701 }
4702 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004703
Richard Smith3003e1d2012-05-15 04:39:51 +00004704 if (HadError)
4705 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004706}
4707
Richard Smith1d28caf2012-12-11 01:14:52 +00004708/// Check whether the exception specification provided for an
4709/// explicitly-defaulted special member matches the exception specification
4710/// that would have been generated for an implicit special member, per
4711/// C++11 [dcl.fct.def.default]p2.
4712void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4713 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4714 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00004715 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4716 /*IsCXXMethod=*/true);
4717 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith1d28caf2012-12-11 01:14:52 +00004718 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4719 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004720 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004721
4722 // Ensure that it matches.
4723 CheckEquivalentExceptionSpec(
4724 PDiag(diag::err_incorrect_defaulted_exception_spec)
4725 << getSpecialMember(MD), PDiag(),
4726 ImplicitType, SourceLocation(),
4727 SpecifiedType, MD->getLocation());
4728}
4729
4730void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4731 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4732 I != N; ++I)
4733 CheckExplicitlyDefaultedMemberExceptionSpec(
4734 DelayedDefaultedMemberExceptionSpecs[I].first,
4735 DelayedDefaultedMemberExceptionSpecs[I].second);
4736
4737 DelayedDefaultedMemberExceptionSpecs.clear();
4738}
4739
Richard Smith7d5088a2012-02-18 02:02:13 +00004740namespace {
4741struct SpecialMemberDeletionInfo {
4742 Sema &S;
4743 CXXMethodDecl *MD;
4744 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004745 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004746
4747 // Properties of the special member, computed for convenience.
4748 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4749 SourceLocation Loc;
4750
4751 bool AllFieldsAreConst;
4752
4753 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004754 Sema::CXXSpecialMember CSM, bool Diagnose)
4755 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004756 IsConstructor(false), IsAssignment(false), IsMove(false),
4757 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4758 AllFieldsAreConst(true) {
4759 switch (CSM) {
4760 case Sema::CXXDefaultConstructor:
4761 case Sema::CXXCopyConstructor:
4762 IsConstructor = true;
4763 break;
4764 case Sema::CXXMoveConstructor:
4765 IsConstructor = true;
4766 IsMove = true;
4767 break;
4768 case Sema::CXXCopyAssignment:
4769 IsAssignment = true;
4770 break;
4771 case Sema::CXXMoveAssignment:
4772 IsAssignment = true;
4773 IsMove = true;
4774 break;
4775 case Sema::CXXDestructor:
4776 break;
4777 case Sema::CXXInvalid:
4778 llvm_unreachable("invalid special member kind");
4779 }
4780
4781 if (MD->getNumParams()) {
4782 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4783 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4784 }
4785 }
4786
4787 bool inUnion() const { return MD->getParent()->isUnion(); }
4788
4789 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004790 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4791 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004792 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004793 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4794 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4795 Quals = 0;
4796 return S.LookupSpecialMember(Class, CSM,
4797 ConstArg || (Quals & Qualifiers::Const),
4798 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004799 MD->getRefQualifier() == RQ_RValue,
4800 TQ & Qualifiers::Const,
4801 TQ & Qualifiers::Volatile);
4802 }
4803
Richard Smith6c4c36c2012-03-30 20:53:28 +00004804 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004805
Richard Smith6c4c36c2012-03-30 20:53:28 +00004806 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004807 bool shouldDeleteForField(FieldDecl *FD);
4808 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004809
Richard Smith517bb842012-07-18 03:51:16 +00004810 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4811 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004812 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4813 Sema::SpecialMemberOverloadResult *SMOR,
4814 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004815
4816 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004817};
4818}
4819
John McCall12d8d802012-04-09 20:53:23 +00004820/// Is the given special member inaccessible when used on the given
4821/// sub-object.
4822bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4823 CXXMethodDecl *target) {
4824 /// If we're operating on a base class, the object type is the
4825 /// type of this special member.
4826 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004827 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004828 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4829 objectTy = S.Context.getTypeDeclType(MD->getParent());
4830 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4831
4832 // If we're operating on a field, the object type is the type of the field.
4833 } else {
4834 objectTy = S.Context.getTypeDeclType(target->getParent());
4835 }
4836
4837 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4838}
4839
Richard Smith6c4c36c2012-03-30 20:53:28 +00004840/// Check whether we should delete a special member due to the implicit
4841/// definition containing a call to a special member of a subobject.
4842bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4843 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4844 bool IsDtorCallInCtor) {
4845 CXXMethodDecl *Decl = SMOR->getMethod();
4846 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4847
4848 int DiagKind = -1;
4849
4850 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4851 DiagKind = !Decl ? 0 : 1;
4852 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4853 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004854 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004855 DiagKind = 3;
4856 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4857 !Decl->isTrivial()) {
4858 // A member of a union must have a trivial corresponding special member.
4859 // As a weird special case, a destructor call from a union's constructor
4860 // must be accessible and non-deleted, but need not be trivial. Such a
4861 // destructor is never actually called, but is semantically checked as
4862 // if it were.
4863 DiagKind = 4;
4864 }
4865
4866 if (DiagKind == -1)
4867 return false;
4868
4869 if (Diagnose) {
4870 if (Field) {
4871 S.Diag(Field->getLocation(),
4872 diag::note_deleted_special_member_class_subobject)
4873 << CSM << MD->getParent() << /*IsField*/true
4874 << Field << DiagKind << IsDtorCallInCtor;
4875 } else {
4876 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4877 S.Diag(Base->getLocStart(),
4878 diag::note_deleted_special_member_class_subobject)
4879 << CSM << MD->getParent() << /*IsField*/false
4880 << Base->getType() << DiagKind << IsDtorCallInCtor;
4881 }
4882
4883 if (DiagKind == 1)
4884 S.NoteDeletedFunction(Decl);
4885 // FIXME: Explain inaccessibility if DiagKind == 3.
4886 }
4887
4888 return true;
4889}
4890
Richard Smith9a561d52012-02-26 09:11:52 +00004891/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004892/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004893bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004894 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004895 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004896
4897 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004898 // -- any direct or virtual base class, or non-static data member with no
4899 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004900 // either M has no default constructor or overload resolution as applied
4901 // to M's default constructor results in an ambiguity or in a function
4902 // that is deleted or inaccessible
4903 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4904 // -- a direct or virtual base class B that cannot be copied/moved because
4905 // overload resolution, as applied to B's corresponding special member,
4906 // results in an ambiguity or a function that is deleted or inaccessible
4907 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004908 // C++11 [class.dtor]p5:
4909 // -- any direct or virtual base class [...] has a type with a destructor
4910 // that is deleted or inaccessible
4911 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004912 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004913 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004914 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004915
Richard Smith6c4c36c2012-03-30 20:53:28 +00004916 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4917 // -- any direct or virtual base class or non-static data member has a
4918 // type with a destructor that is deleted or inaccessible
4919 if (IsConstructor) {
4920 Sema::SpecialMemberOverloadResult *SMOR =
4921 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4922 false, false, false, false, false);
4923 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4924 return true;
4925 }
4926
Richard Smith9a561d52012-02-26 09:11:52 +00004927 return false;
4928}
4929
4930/// Check whether we should delete a special member function due to the class
4931/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004932bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004933 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004934 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004935}
4936
4937/// Check whether we should delete a special member function due to the class
4938/// having a particular non-static data member.
4939bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4940 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4941 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4942
4943 if (CSM == Sema::CXXDefaultConstructor) {
4944 // For a default constructor, all references must be initialized in-class
4945 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004946 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4947 if (Diagnose)
4948 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4949 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004950 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004951 }
Richard Smith79363f52012-02-27 06:07:25 +00004952 // C++11 [class.ctor]p5: any non-variant non-static data member of
4953 // const-qualified type (or array thereof) with no
4954 // brace-or-equal-initializer does not have a user-provided default
4955 // constructor.
4956 if (!inUnion() && FieldType.isConstQualified() &&
4957 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004958 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4959 if (Diagnose)
4960 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004961 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004962 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004963 }
4964
4965 if (inUnion() && !FieldType.isConstQualified())
4966 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004967 } else if (CSM == Sema::CXXCopyConstructor) {
4968 // For a copy constructor, data members must not be of rvalue reference
4969 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004970 if (FieldType->isRValueReferenceType()) {
4971 if (Diagnose)
4972 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4973 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004974 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004975 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004976 } else if (IsAssignment) {
4977 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004978 if (FieldType->isReferenceType()) {
4979 if (Diagnose)
4980 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4981 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004982 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004983 }
4984 if (!FieldRecord && FieldType.isConstQualified()) {
4985 // C++11 [class.copy]p23:
4986 // -- a non-static data member of const non-class type (or array thereof)
4987 if (Diagnose)
4988 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004989 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004990 return true;
4991 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004992 }
4993
4994 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004995 // Some additional restrictions exist on the variant members.
4996 if (!inUnion() && FieldRecord->isUnion() &&
4997 FieldRecord->isAnonymousStructOrUnion()) {
4998 bool AllVariantFieldsAreConst = true;
4999
Richard Smithdf8dc862012-03-29 19:00:10 +00005000 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00005001 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5002 UE = FieldRecord->field_end();
5003 UI != UE; ++UI) {
5004 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00005005
5006 if (!UnionFieldType.isConstQualified())
5007 AllVariantFieldsAreConst = false;
5008
Richard Smith9a561d52012-02-26 09:11:52 +00005009 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5010 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00005011 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5012 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00005013 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005014 }
5015
5016 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00005017 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005018 FieldRecord->field_begin() != FieldRecord->field_end()) {
5019 if (Diagnose)
5020 S.Diag(FieldRecord->getLocation(),
5021 diag::note_deleted_default_ctor_all_const)
5022 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00005023 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005024 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005025
Richard Smithdf8dc862012-03-29 19:00:10 +00005026 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00005027 // This is technically non-conformant, but sanity demands it.
5028 return false;
5029 }
5030
Richard Smith517bb842012-07-18 03:51:16 +00005031 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5032 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00005033 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005034 }
5035
5036 return false;
5037}
5038
5039/// C++11 [class.ctor] p5:
5040/// A defaulted default constructor for a class X is defined as deleted if
5041/// X is a union and all of its variant members are of const-qualified type.
5042bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00005043 // This is a silly definition, because it gives an empty union a deleted
5044 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005045 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5046 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5047 if (Diagnose)
5048 S.Diag(MD->getParent()->getLocation(),
5049 diag::note_deleted_default_ctor_all_const)
5050 << MD->getParent() << /*not anonymous union*/0;
5051 return true;
5052 }
5053 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005054}
5055
5056/// Determine whether a defaulted special member function should be defined as
5057/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5058/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005059bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5060 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00005061 if (MD->isInvalidDecl())
5062 return false;
Sean Hunte16da072011-10-10 06:18:57 +00005063 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00005064 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00005065 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005066 return false;
5067
Richard Smith7d5088a2012-02-18 02:02:13 +00005068 // C++11 [expr.lambda.prim]p19:
5069 // The closure type associated with a lambda-expression has a
5070 // deleted (8.4.3) default constructor and a deleted copy
5071 // assignment operator.
5072 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005073 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5074 if (Diagnose)
5075 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005076 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005077 }
5078
Richard Smith5bdaac52012-04-02 20:59:25 +00005079 // For an anonymous struct or union, the copy and assignment special members
5080 // will never be used, so skip the check. For an anonymous union declared at
5081 // namespace scope, the constructor and destructor are used.
5082 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5083 RD->isAnonymousStructOrUnion())
5084 return false;
5085
Richard Smith6c4c36c2012-03-30 20:53:28 +00005086 // C++11 [class.copy]p7, p18:
5087 // If the class definition declares a move constructor or move assignment
5088 // operator, an implicitly declared copy constructor or copy assignment
5089 // operator is defined as deleted.
5090 if (MD->isImplicit() &&
5091 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5092 CXXMethodDecl *UserDeclaredMove = 0;
5093
5094 // In Microsoft mode, a user-declared move only causes the deletion of the
5095 // corresponding copy operation, not both copy operations.
5096 if (RD->hasUserDeclaredMoveConstructor() &&
5097 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5098 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005099
5100 // Find any user-declared move constructor.
5101 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5102 E = RD->ctor_end(); I != E; ++I) {
5103 if (I->isMoveConstructor()) {
5104 UserDeclaredMove = *I;
5105 break;
5106 }
5107 }
Richard Smith1c931be2012-04-02 18:40:40 +00005108 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005109 } else if (RD->hasUserDeclaredMoveAssignment() &&
5110 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5111 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005112
5113 // Find any user-declared move assignment operator.
5114 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5115 E = RD->method_end(); I != E; ++I) {
5116 if (I->isMoveAssignmentOperator()) {
5117 UserDeclaredMove = *I;
5118 break;
5119 }
5120 }
Richard Smith1c931be2012-04-02 18:40:40 +00005121 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005122 }
5123
5124 if (UserDeclaredMove) {
5125 Diag(UserDeclaredMove->getLocation(),
5126 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005127 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005128 << UserDeclaredMove->isMoveAssignmentOperator();
5129 return true;
5130 }
5131 }
Sean Hunte16da072011-10-10 06:18:57 +00005132
Richard Smith5bdaac52012-04-02 20:59:25 +00005133 // Do access control from the special member function
5134 ContextRAII MethodContext(*this, MD);
5135
Richard Smith9a561d52012-02-26 09:11:52 +00005136 // C++11 [class.dtor]p5:
5137 // -- for a virtual destructor, lookup of the non-array deallocation function
5138 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005139 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005140 FunctionDecl *OperatorDelete = 0;
5141 DeclarationName Name =
5142 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5143 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005144 OperatorDelete, false)) {
5145 if (Diagnose)
5146 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005147 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005148 }
Richard Smith9a561d52012-02-26 09:11:52 +00005149 }
5150
Richard Smith6c4c36c2012-03-30 20:53:28 +00005151 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005152
Sean Huntcdee3fe2011-05-11 22:34:38 +00005153 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005154 BE = RD->bases_end(); BI != BE; ++BI)
5155 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005156 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005157 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005158
Richard Smithe0883602013-07-22 18:06:23 +00005159 // Per DR1611, do not consider virtual bases of constructors of abstract
5160 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005161 if (!RD->isAbstract() || !SMI.IsConstructor) {
5162 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5163 BE = RD->vbases_end();
5164 BI != BE; ++BI)
5165 if (SMI.shouldDeleteForBase(BI))
5166 return true;
5167 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005168
5169 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005170 FE = RD->field_end(); FI != FE; ++FI)
5171 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005172 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005173 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005174
Richard Smith7d5088a2012-02-18 02:02:13 +00005175 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005176 return true;
5177
5178 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005179}
5180
Richard Smithac713512012-12-08 02:53:02 +00005181/// Perform lookup for a special member of the specified kind, and determine
5182/// whether it is trivial. If the triviality can be determined without the
5183/// lookup, skip it. This is intended for use when determining whether a
5184/// special member of a containing object is trivial, and thus does not ever
5185/// perform overload resolution for default constructors.
5186///
5187/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5188/// member that was most likely to be intended to be trivial, if any.
5189static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5190 Sema::CXXSpecialMember CSM, unsigned Quals,
5191 CXXMethodDecl **Selected) {
5192 if (Selected)
5193 *Selected = 0;
5194
5195 switch (CSM) {
5196 case Sema::CXXInvalid:
5197 llvm_unreachable("not a special member");
5198
5199 case Sema::CXXDefaultConstructor:
5200 // C++11 [class.ctor]p5:
5201 // A default constructor is trivial if:
5202 // - all the [direct subobjects] have trivial default constructors
5203 //
5204 // Note, no overload resolution is performed in this case.
5205 if (RD->hasTrivialDefaultConstructor())
5206 return true;
5207
5208 if (Selected) {
5209 // If there's a default constructor which could have been trivial, dig it
5210 // out. Otherwise, if there's any user-provided default constructor, point
5211 // to that as an example of why there's not a trivial one.
5212 CXXConstructorDecl *DefCtor = 0;
5213 if (RD->needsImplicitDefaultConstructor())
5214 S.DeclareImplicitDefaultConstructor(RD);
5215 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5216 CE = RD->ctor_end(); CI != CE; ++CI) {
5217 if (!CI->isDefaultConstructor())
5218 continue;
5219 DefCtor = *CI;
5220 if (!DefCtor->isUserProvided())
5221 break;
5222 }
5223
5224 *Selected = DefCtor;
5225 }
5226
5227 return false;
5228
5229 case Sema::CXXDestructor:
5230 // C++11 [class.dtor]p5:
5231 // A destructor is trivial if:
5232 // - all the direct [subobjects] have trivial destructors
5233 if (RD->hasTrivialDestructor())
5234 return true;
5235
5236 if (Selected) {
5237 if (RD->needsImplicitDestructor())
5238 S.DeclareImplicitDestructor(RD);
5239 *Selected = RD->getDestructor();
5240 }
5241
5242 return false;
5243
5244 case Sema::CXXCopyConstructor:
5245 // C++11 [class.copy]p12:
5246 // A copy constructor is trivial if:
5247 // - the constructor selected to copy each direct [subobject] is trivial
5248 if (RD->hasTrivialCopyConstructor()) {
5249 if (Quals == Qualifiers::Const)
5250 // We must either select the trivial copy constructor or reach an
5251 // ambiguity; no need to actually perform overload resolution.
5252 return true;
5253 } else if (!Selected) {
5254 return false;
5255 }
5256 // In C++98, we are not supposed to perform overload resolution here, but we
5257 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5258 // cases like B as having a non-trivial copy constructor:
5259 // struct A { template<typename T> A(T&); };
5260 // struct B { mutable A a; };
5261 goto NeedOverloadResolution;
5262
5263 case Sema::CXXCopyAssignment:
5264 // C++11 [class.copy]p25:
5265 // A copy assignment operator is trivial if:
5266 // - the assignment operator selected to copy each direct [subobject] is
5267 // trivial
5268 if (RD->hasTrivialCopyAssignment()) {
5269 if (Quals == Qualifiers::Const)
5270 return true;
5271 } else if (!Selected) {
5272 return false;
5273 }
5274 // In C++98, we are not supposed to perform overload resolution here, but we
5275 // treat that as a language defect.
5276 goto NeedOverloadResolution;
5277
5278 case Sema::CXXMoveConstructor:
5279 case Sema::CXXMoveAssignment:
5280 NeedOverloadResolution:
5281 Sema::SpecialMemberOverloadResult *SMOR =
5282 S.LookupSpecialMember(RD, CSM,
5283 Quals & Qualifiers::Const,
5284 Quals & Qualifiers::Volatile,
5285 /*RValueThis*/false, /*ConstThis*/false,
5286 /*VolatileThis*/false);
5287
5288 // The standard doesn't describe how to behave if the lookup is ambiguous.
5289 // We treat it as not making the member non-trivial, just like the standard
5290 // mandates for the default constructor. This should rarely matter, because
5291 // the member will also be deleted.
5292 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5293 return true;
5294
5295 if (!SMOR->getMethod()) {
5296 assert(SMOR->getKind() ==
5297 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5298 return false;
5299 }
5300
5301 // We deliberately don't check if we found a deleted special member. We're
5302 // not supposed to!
5303 if (Selected)
5304 *Selected = SMOR->getMethod();
5305 return SMOR->getMethod()->isTrivial();
5306 }
5307
5308 llvm_unreachable("unknown special method kind");
5309}
5310
Benjamin Kramera574c892013-02-15 12:30:38 +00005311static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005312 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5313 CI != CE; ++CI)
5314 if (!CI->isImplicit())
5315 return *CI;
5316
5317 // Look for constructor templates.
5318 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5319 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5320 if (CXXConstructorDecl *CD =
5321 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5322 return CD;
5323 }
5324
5325 return 0;
5326}
5327
5328/// The kind of subobject we are checking for triviality. The values of this
5329/// enumeration are used in diagnostics.
5330enum TrivialSubobjectKind {
5331 /// The subobject is a base class.
5332 TSK_BaseClass,
5333 /// The subobject is a non-static data member.
5334 TSK_Field,
5335 /// The object is actually the complete object.
5336 TSK_CompleteObject
5337};
5338
5339/// Check whether the special member selected for a given type would be trivial.
5340static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5341 QualType SubType,
5342 Sema::CXXSpecialMember CSM,
5343 TrivialSubobjectKind Kind,
5344 bool Diagnose) {
5345 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5346 if (!SubRD)
5347 return true;
5348
5349 CXXMethodDecl *Selected;
5350 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5351 Diagnose ? &Selected : 0))
5352 return true;
5353
5354 if (Diagnose) {
5355 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5356 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5357 << Kind << SubType.getUnqualifiedType();
5358 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5359 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5360 } else if (!Selected)
5361 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5362 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5363 else if (Selected->isUserProvided()) {
5364 if (Kind == TSK_CompleteObject)
5365 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5366 << Kind << SubType.getUnqualifiedType() << CSM;
5367 else {
5368 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5369 << Kind << SubType.getUnqualifiedType() << CSM;
5370 S.Diag(Selected->getLocation(), diag::note_declared_at);
5371 }
5372 } else {
5373 if (Kind != TSK_CompleteObject)
5374 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5375 << Kind << SubType.getUnqualifiedType() << CSM;
5376
5377 // Explain why the defaulted or deleted special member isn't trivial.
5378 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5379 }
5380 }
5381
5382 return false;
5383}
5384
5385/// Check whether the members of a class type allow a special member to be
5386/// trivial.
5387static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5388 Sema::CXXSpecialMember CSM,
5389 bool ConstArg, bool Diagnose) {
5390 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5391 FE = RD->field_end(); FI != FE; ++FI) {
5392 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5393 continue;
5394
5395 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5396
5397 // Pretend anonymous struct or union members are members of this class.
5398 if (FI->isAnonymousStructOrUnion()) {
5399 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5400 CSM, ConstArg, Diagnose))
5401 return false;
5402 continue;
5403 }
5404
5405 // C++11 [class.ctor]p5:
5406 // A default constructor is trivial if [...]
5407 // -- no non-static data member of its class has a
5408 // brace-or-equal-initializer
5409 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5410 if (Diagnose)
5411 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5412 return false;
5413 }
5414
5415 // Objective C ARC 4.3.5:
5416 // [...] nontrivally ownership-qualified types are [...] not trivially
5417 // default constructible, copy constructible, move constructible, copy
5418 // assignable, move assignable, or destructible [...]
5419 if (S.getLangOpts().ObjCAutoRefCount &&
5420 FieldType.hasNonTrivialObjCLifetime()) {
5421 if (Diagnose)
5422 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5423 << RD << FieldType.getObjCLifetime();
5424 return false;
5425 }
5426
5427 if (ConstArg && !FI->isMutable())
5428 FieldType.addConst();
5429 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5430 TSK_Field, Diagnose))
5431 return false;
5432 }
5433
5434 return true;
5435}
5436
5437/// Diagnose why the specified class does not have a trivial special member of
5438/// the given kind.
5439void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5440 QualType Ty = Context.getRecordType(RD);
5441 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5442 Ty.addConst();
5443
5444 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5445 TSK_CompleteObject, /*Diagnose*/true);
5446}
5447
5448/// Determine whether a defaulted or deleted special member function is trivial,
5449/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5450/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5451bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5452 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005453 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5454
5455 CXXRecordDecl *RD = MD->getParent();
5456
5457 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005458
5459 // C++11 [class.copy]p12, p25:
5460 // A [special member] is trivial if its declared parameter type is the same
5461 // as if it had been implicitly declared [...]
5462 switch (CSM) {
5463 case CXXDefaultConstructor:
5464 case CXXDestructor:
5465 // Trivial default constructors and destructors cannot have parameters.
5466 break;
5467
5468 case CXXCopyConstructor:
5469 case CXXCopyAssignment: {
5470 // Trivial copy operations always have const, non-volatile parameter types.
5471 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005472 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005473 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5474 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5475 if (Diagnose)
5476 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5477 << Param0->getSourceRange() << Param0->getType()
5478 << Context.getLValueReferenceType(
5479 Context.getRecordType(RD).withConst());
5480 return false;
5481 }
5482 break;
5483 }
5484
5485 case CXXMoveConstructor:
5486 case CXXMoveAssignment: {
5487 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005488 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005489 const RValueReferenceType *RT =
5490 Param0->getType()->getAs<RValueReferenceType>();
5491 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5492 if (Diagnose)
5493 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5494 << Param0->getSourceRange() << Param0->getType()
5495 << Context.getRValueReferenceType(Context.getRecordType(RD));
5496 return false;
5497 }
5498 break;
5499 }
5500
5501 case CXXInvalid:
5502 llvm_unreachable("not a special member");
5503 }
5504
5505 // FIXME: We require that the parameter-declaration-clause is equivalent to
5506 // that of an implicit declaration, not just that the declared parameter type
5507 // matches, in order to prevent absuridities like a function simultaneously
5508 // being a trivial copy constructor and a non-trivial default constructor.
5509 // This issue has not yet been assigned a core issue number.
5510 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5511 if (Diagnose)
5512 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5513 diag::note_nontrivial_default_arg)
5514 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5515 return false;
5516 }
5517 if (MD->isVariadic()) {
5518 if (Diagnose)
5519 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5520 return false;
5521 }
5522
5523 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5524 // A copy/move [constructor or assignment operator] is trivial if
5525 // -- the [member] selected to copy/move each direct base class subobject
5526 // is trivial
5527 //
5528 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5529 // A [default constructor or destructor] is trivial if
5530 // -- all the direct base classes have trivial [default constructors or
5531 // destructors]
5532 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5533 BE = RD->bases_end(); BI != BE; ++BI)
5534 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5535 ConstArg ? BI->getType().withConst()
5536 : BI->getType(),
5537 CSM, TSK_BaseClass, Diagnose))
5538 return false;
5539
5540 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5541 // A copy/move [constructor or assignment operator] for a class X is
5542 // trivial if
5543 // -- for each non-static data member of X that is of class type (or array
5544 // thereof), the constructor selected to copy/move that member is
5545 // trivial
5546 //
5547 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5548 // A [default constructor or destructor] is trivial if
5549 // -- for all of the non-static data members of its class that are of class
5550 // type (or array thereof), each such class has a trivial [default
5551 // constructor or destructor]
5552 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5553 return false;
5554
5555 // C++11 [class.dtor]p5:
5556 // A destructor is trivial if [...]
5557 // -- the destructor is not virtual
5558 if (CSM == CXXDestructor && MD->isVirtual()) {
5559 if (Diagnose)
5560 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5561 return false;
5562 }
5563
5564 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5565 // A [special member] for class X is trivial if [...]
5566 // -- class X has no virtual functions and no virtual base classes
5567 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5568 if (!Diagnose)
5569 return false;
5570
5571 if (RD->getNumVBases()) {
5572 // Check for virtual bases. We already know that the corresponding
5573 // member in all bases is trivial, so vbases must all be direct.
5574 CXXBaseSpecifier &BS = *RD->vbases_begin();
5575 assert(BS.isVirtual());
5576 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5577 return false;
5578 }
5579
5580 // Must have a virtual method.
5581 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5582 ME = RD->method_end(); MI != ME; ++MI) {
5583 if (MI->isVirtual()) {
5584 SourceLocation MLoc = MI->getLocStart();
5585 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5586 return false;
5587 }
5588 }
5589
5590 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5591 }
5592
5593 // Looks like it's trivial!
5594 return true;
5595}
5596
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005597/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005598namespace {
5599 struct FindHiddenVirtualMethodData {
5600 Sema *S;
5601 CXXMethodDecl *Method;
5602 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005603 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005604 };
5605}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005606
David Blaikie5f750682012-10-19 00:53:08 +00005607/// \brief Check whether any most overriden method from MD in Methods
5608static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5609 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5610 if (MD->size_overridden_methods() == 0)
5611 return Methods.count(MD->getCanonicalDecl());
5612 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5613 E = MD->end_overridden_methods();
5614 I != E; ++I)
5615 if (CheckMostOverridenMethods(*I, Methods))
5616 return true;
5617 return false;
5618}
5619
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005620/// \brief Member lookup function that determines whether a given C++
5621/// method overloads virtual methods in a base class without overriding any,
5622/// to be used with CXXRecordDecl::lookupInBases().
5623static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5624 CXXBasePath &Path,
5625 void *UserData) {
5626 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5627
5628 FindHiddenVirtualMethodData &Data
5629 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5630
5631 DeclarationName Name = Data.Method->getDeclName();
5632 assert(Name.getNameKind() == DeclarationName::Identifier);
5633
5634 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005635 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005636 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005637 !Path.Decls.empty();
5638 Path.Decls = Path.Decls.slice(1)) {
5639 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005640 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005641 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005642 foundSameNameMethod = true;
5643 // Interested only in hidden virtual methods.
5644 if (!MD->isVirtual())
5645 continue;
5646 // If the method we are checking overrides a method from its base
5647 // don't warn about the other overloaded methods.
5648 if (!Data.S->IsOverload(Data.Method, MD, false))
5649 return true;
5650 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005651 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005652 overloadedMethods.push_back(MD);
5653 }
5654 }
5655
5656 if (foundSameNameMethod)
5657 Data.OverloadedMethods.append(overloadedMethods.begin(),
5658 overloadedMethods.end());
5659 return foundSameNameMethod;
5660}
5661
David Blaikie5f750682012-10-19 00:53:08 +00005662/// \brief Add the most overriden methods from MD to Methods
5663static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5664 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5665 if (MD->size_overridden_methods() == 0)
5666 Methods.insert(MD->getCanonicalDecl());
5667 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5668 E = MD->end_overridden_methods();
5669 I != E; ++I)
5670 AddMostOverridenMethods(*I, Methods);
5671}
5672
Eli Friedmandae92712013-09-05 23:51:03 +00005673/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005674/// overriding any.
Eli Friedmandae92712013-09-05 23:51:03 +00005675void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5676 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramerc4704422012-05-19 16:03:58 +00005677 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005678 return;
5679
5680 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5681 /*bool RecordPaths=*/false,
5682 /*bool DetectVirtual=*/false);
5683 FindHiddenVirtualMethodData Data;
5684 Data.Method = MD;
5685 Data.S = this;
5686
5687 // Keep the base methods that were overriden or introduced in the subclass
5688 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmandae92712013-09-05 23:51:03 +00005689 CXXRecordDecl *DC = MD->getParent();
David Blaikie3bc93e32012-12-19 00:45:41 +00005690 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5691 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5692 NamedDecl *ND = *I;
5693 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005694 ND = shad->getTargetDecl();
5695 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5696 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005697 }
5698
Eli Friedmandae92712013-09-05 23:51:03 +00005699 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5700 OverloadedMethods = Data.OverloadedMethods;
5701}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005702
Eli Friedmandae92712013-09-05 23:51:03 +00005703void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5704 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5705 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5706 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5707 PartialDiagnostic PD = PDiag(
5708 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5709 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5710 Diag(overloadedMD->getLocation(), PD);
5711 }
5712}
5713
5714/// \brief Diagnose methods which overload virtual methods in a base class
5715/// without overriding any.
5716void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5717 if (MD->isInvalidDecl())
5718 return;
5719
5720 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5721 MD->getLocation()) == DiagnosticsEngine::Ignored)
5722 return;
5723
5724 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5725 FindHiddenVirtualMethods(MD, OverloadedMethods);
5726 if (!OverloadedMethods.empty()) {
5727 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5728 << MD << (OverloadedMethods.size() > 1);
5729
5730 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005731 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005732}
5733
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005734void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005735 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005736 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005737 SourceLocation RBrac,
5738 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005739 if (!TagDecl)
5740 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005741
Douglas Gregor42af25f2009-05-11 19:58:34 +00005742 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005743
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005744 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5745 if (l->getKind() != AttributeList::AT_Visibility)
5746 continue;
5747 l->setInvalid();
5748 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5749 l->getName();
5750 }
5751
David Blaikie77b6de02011-09-22 02:58:26 +00005752 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005753 // strict aliasing violation!
5754 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005755 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005756
Douglas Gregor23c94db2010-07-02 17:43:08 +00005757 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005758 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005759}
5760
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005761/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5762/// special functions, such as the default constructor, copy
5763/// constructor, or destructor, to the given C++ class (C++
5764/// [special]p1). This routine can only be executed just before the
5765/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005766void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005767 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005768 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005769
Richard Smithbc2a35d2012-12-08 08:32:28 +00005770 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005771 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005772
Richard Smithbc2a35d2012-12-08 08:32:28 +00005773 // If the properties or semantics of the copy constructor couldn't be
5774 // determined while the class was being declared, force a declaration
5775 // of it now.
5776 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5777 DeclareImplicitCopyConstructor(ClassDecl);
5778 }
5779
Richard Smith80ad52f2013-01-02 11:42:31 +00005780 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005781 ++ASTContext::NumImplicitMoveConstructors;
5782
Richard Smithbc2a35d2012-12-08 08:32:28 +00005783 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5784 DeclareImplicitMoveConstructor(ClassDecl);
5785 }
5786
Douglas Gregora376d102010-07-02 21:50:04 +00005787 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5788 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005789
5790 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005791 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005792 // it shows up in the right place in the vtable and that we diagnose
5793 // problems with the implicit exception specification.
5794 if (ClassDecl->isDynamicClass() ||
5795 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005796 DeclareImplicitCopyAssignment(ClassDecl);
5797 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005798
Richard Smith80ad52f2013-01-02 11:42:31 +00005799 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005800 ++ASTContext::NumImplicitMoveAssignmentOperators;
5801
5802 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005803 if (ClassDecl->isDynamicClass() ||
5804 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005805 DeclareImplicitMoveAssignment(ClassDecl);
5806 }
5807
Douglas Gregor4923aa22010-07-02 20:37:36 +00005808 if (!ClassDecl->hasUserDeclaredDestructor()) {
5809 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005810
5811 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005812 // have to declare the destructor immediately. This ensures that, e.g., it
5813 // shows up in the right place in the vtable and that we diagnose problems
5814 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005815 if (ClassDecl->isDynamicClass() ||
5816 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005817 DeclareImplicitDestructor(ClassDecl);
5818 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005819}
5820
Francois Pichet8387e2a2011-04-22 22:18:13 +00005821void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5822 if (!D)
5823 return;
5824
5825 int NumParamList = D->getNumTemplateParameterLists();
5826 for (int i = 0; i < NumParamList; i++) {
5827 TemplateParameterList* Params = D->getTemplateParameterList(i);
5828 for (TemplateParameterList::iterator Param = Params->begin(),
5829 ParamEnd = Params->end();
5830 Param != ParamEnd; ++Param) {
5831 NamedDecl *Named = cast<NamedDecl>(*Param);
5832 if (Named->getDeclName()) {
5833 S->AddDecl(Named);
5834 IdResolver.AddDecl(Named);
5835 }
5836 }
5837 }
5838}
5839
John McCalld226f652010-08-21 09:40:31 +00005840void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005841 if (!D)
5842 return;
5843
5844 TemplateParameterList *Params = 0;
5845 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5846 Params = Template->getTemplateParameters();
5847 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5848 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5849 Params = PartialSpec->getTemplateParameters();
5850 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005851 return;
5852
Douglas Gregor6569d682009-05-27 23:11:45 +00005853 for (TemplateParameterList::iterator Param = Params->begin(),
5854 ParamEnd = Params->end();
5855 Param != ParamEnd; ++Param) {
5856 NamedDecl *Named = cast<NamedDecl>(*Param);
5857 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005858 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005859 IdResolver.AddDecl(Named);
5860 }
5861 }
5862}
5863
John McCalld226f652010-08-21 09:40:31 +00005864void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005865 if (!RecordD) return;
5866 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005867 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005868 PushDeclContext(S, Record);
5869}
5870
John McCalld226f652010-08-21 09:40:31 +00005871void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005872 if (!RecordD) return;
5873 PopDeclContext();
5874}
5875
Douglas Gregor72b505b2008-12-16 21:30:33 +00005876/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5877/// parsing a top-level (non-nested) C++ class, and we are now
5878/// parsing those parts of the given Method declaration that could
5879/// not be parsed earlier (C++ [class.mem]p2), such as default
5880/// arguments. This action should enter the scope of the given
5881/// Method declaration as if we had just parsed the qualified method
5882/// name. However, it should not bring the parameters into scope;
5883/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005884void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005885}
5886
5887/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5888/// C++ method declaration. We're (re-)introducing the given
5889/// function parameter into scope for use in parsing later parts of
5890/// the method declaration. For example, we could see an
5891/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005892void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005893 if (!ParamD)
5894 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005895
John McCalld226f652010-08-21 09:40:31 +00005896 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005897
5898 // If this parameter has an unparsed default argument, clear it out
5899 // to make way for the parsed default argument.
5900 if (Param->hasUnparsedDefaultArg())
5901 Param->setDefaultArg(0);
5902
John McCalld226f652010-08-21 09:40:31 +00005903 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005904 if (Param->getDeclName())
5905 IdResolver.AddDecl(Param);
5906}
5907
5908/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5909/// processing the delayed method declaration for Method. The method
5910/// declaration is now considered finished. There may be a separate
5911/// ActOnStartOfFunctionDef action later (not necessarily
5912/// immediately!) for this method, if it was also defined inside the
5913/// class body.
John McCalld226f652010-08-21 09:40:31 +00005914void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005915 if (!MethodD)
5916 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005917
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005918 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005919
John McCalld226f652010-08-21 09:40:31 +00005920 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005921
5922 // Now that we have our default arguments, check the constructor
5923 // again. It could produce additional diagnostics or affect whether
5924 // the class has implicitly-declared destructors, among other
5925 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005926 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5927 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005928
5929 // Check the default arguments, which we may have added.
5930 if (!Method->isInvalidDecl())
5931 CheckCXXDefaultArguments(Method);
5932}
5933
Douglas Gregor42a552f2008-11-05 20:51:48 +00005934/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005935/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005936/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005937/// emit diagnostics and set the invalid bit to true. In any case, the type
5938/// will be updated to reflect a well-formed type for the constructor and
5939/// returned.
5940QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005941 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005942 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005943
5944 // C++ [class.ctor]p3:
5945 // A constructor shall not be virtual (10.3) or static (9.4). A
5946 // constructor can be invoked for a const, volatile or const
5947 // volatile object. A constructor shall not be declared const,
5948 // volatile, or const volatile (9.3.2).
5949 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005950 if (!D.isInvalidType())
5951 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5952 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5953 << SourceRange(D.getIdentifierLoc());
5954 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005955 }
John McCalld931b082010-08-26 03:08:43 +00005956 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005957 if (!D.isInvalidType())
5958 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5959 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5960 << SourceRange(D.getIdentifierLoc());
5961 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005962 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005963 }
Mike Stump1eb44332009-09-09 15:08:12 +00005964
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005965 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005966 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005967 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005968 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5969 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005970 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005971 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5972 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005973 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005974 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5975 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005976 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005977 }
Mike Stump1eb44332009-09-09 15:08:12 +00005978
Douglas Gregorc938c162011-01-26 05:01:58 +00005979 // C++0x [class.ctor]p4:
5980 // A constructor shall not be declared with a ref-qualifier.
5981 if (FTI.hasRefQualifier()) {
5982 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5983 << FTI.RefQualifierIsLValueRef
5984 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5985 D.setInvalidType();
5986 }
5987
Douglas Gregor42a552f2008-11-05 20:51:48 +00005988 // Rebuild the function type "R" without any type qualifiers (in
5989 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005990 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005991 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005992 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5993 return R;
5994
5995 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5996 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005997 EPI.RefQualifier = RQ_None;
5998
Richard Smith07b0fdc2013-03-18 21:12:30 +00005999 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006000}
6001
Douglas Gregor72b505b2008-12-16 21:30:33 +00006002/// CheckConstructor - Checks a fully-formed constructor for
6003/// well-formedness, issuing any diagnostics required. Returns true if
6004/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00006005void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00006006 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00006007 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6008 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00006009 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006010
6011 // C++ [class.copy]p3:
6012 // A declaration of a constructor for a class X is ill-formed if
6013 // its first parameter is of type (optionally cv-qualified) X and
6014 // either there are no other parameters or else all other
6015 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00006016 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006017 ((Constructor->getNumParams() == 1) ||
6018 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00006019 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6020 Constructor->getTemplateSpecializationKind()
6021 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006022 QualType ParamType = Constructor->getParamDecl(0)->getType();
6023 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6024 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00006025 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006026 const char *ConstRef
6027 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6028 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00006029 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006030 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00006031
6032 // FIXME: Rather that making the constructor invalid, we should endeavor
6033 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00006034 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006035 }
6036 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00006037}
6038
John McCall15442822010-08-04 01:04:25 +00006039/// CheckDestructor - Checks a fully-formed destructor definition for
6040/// well-formedness, issuing any diagnostics required. Returns true
6041/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006042bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006043 CXXRecordDecl *RD = Destructor->getParent();
6044
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006045 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006046 SourceLocation Loc;
6047
6048 if (!Destructor->isImplicit())
6049 Loc = Destructor->getLocation();
6050 else
6051 Loc = RD->getLocation();
6052
6053 // If we have a virtual destructor, look up the deallocation function
6054 FunctionDecl *OperatorDelete = 0;
6055 DeclarationName Name =
6056 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006057 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00006058 return true;
John McCall5efd91a2010-07-03 18:33:00 +00006059
Eli Friedman5f2987c2012-02-02 03:46:19 +00006060 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00006061
6062 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00006063 }
Anders Carlsson37909802009-11-30 21:24:50 +00006064
6065 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00006066}
6067
Mike Stump1eb44332009-09-09 15:08:12 +00006068static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006069FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6070 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6071 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006072 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006073}
6074
Douglas Gregor42a552f2008-11-05 20:51:48 +00006075/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6076/// the well-formednes of the destructor declarator @p D with type @p
6077/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006078/// emit diagnostics and set the declarator to invalid. Even if this happens,
6079/// will be updated to reflect a well-formed type for the destructor and
6080/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00006081QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006082 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006083 // C++ [class.dtor]p1:
6084 // [...] A typedef-name that names a class is a class-name
6085 // (7.1.3); however, a typedef-name that names a class shall not
6086 // be used as the identifier in the declarator for a destructor
6087 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006088 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006089 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006090 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006091 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006092 else if (const TemplateSpecializationType *TST =
6093 DeclaratorType->getAs<TemplateSpecializationType>())
6094 if (TST->isTypeAlias())
6095 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6096 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006097
6098 // C++ [class.dtor]p2:
6099 // A destructor is used to destroy objects of its class type. A
6100 // destructor takes no parameters, and no return type can be
6101 // specified for it (not even void). The address of a destructor
6102 // shall not be taken. A destructor shall not be static. A
6103 // destructor can be invoked for a const, volatile or const
6104 // volatile object. A destructor shall not be declared const,
6105 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006106 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006107 if (!D.isInvalidType())
6108 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6109 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006110 << SourceRange(D.getIdentifierLoc())
6111 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6112
John McCalld931b082010-08-26 03:08:43 +00006113 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006114 }
Chris Lattner65401802009-04-25 08:28:21 +00006115 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006116 // Destructors don't have return types, but the parser will
6117 // happily parse something like:
6118 //
6119 // class X {
6120 // float ~X();
6121 // };
6122 //
6123 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006124 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6125 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6126 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006127 }
Mike Stump1eb44332009-09-09 15:08:12 +00006128
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006129 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006130 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006131 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006132 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6133 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006134 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006135 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6136 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006137 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006138 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6139 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006140 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006141 }
6142
Douglas Gregorc938c162011-01-26 05:01:58 +00006143 // C++0x [class.dtor]p2:
6144 // A destructor shall not be declared with a ref-qualifier.
6145 if (FTI.hasRefQualifier()) {
6146 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6147 << FTI.RefQualifierIsLValueRef
6148 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6149 D.setInvalidType();
6150 }
6151
Douglas Gregor42a552f2008-11-05 20:51:48 +00006152 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006153 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006154 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6155
6156 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006157 FTI.freeArgs();
6158 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006159 }
6160
Mike Stump1eb44332009-09-09 15:08:12 +00006161 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006162 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006163 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006164 D.setInvalidType();
6165 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006166
6167 // Rebuild the function type "R" without any type qualifiers or
6168 // parameters (in case any of the errors above fired) and with
6169 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006170 // types.
John McCalle23cf432010-12-14 08:05:40 +00006171 if (!D.isInvalidType())
6172 return R;
6173
Douglas Gregord92ec472010-07-01 05:10:53 +00006174 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006175 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6176 EPI.Variadic = false;
6177 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006178 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006179 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006180}
6181
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006182/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6183/// well-formednes of the conversion function declarator @p D with
6184/// type @p R. If there are any errors in the declarator, this routine
6185/// will emit diagnostics and return true. Otherwise, it will return
6186/// false. Either way, the type @p R will be updated to reflect a
6187/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006188void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006189 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006190 // C++ [class.conv.fct]p1:
6191 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006192 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006193 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006194 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006195 if (!D.isInvalidType())
6196 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006197 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6198 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006199 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006200 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006201 }
John McCalla3f81372010-04-13 00:04:31 +00006202
6203 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6204
Chris Lattner6e475012009-04-25 08:35:12 +00006205 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006206 // Conversion functions don't have return types, but the parser will
6207 // happily parse something like:
6208 //
6209 // class X {
6210 // float operator bool();
6211 // };
6212 //
6213 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006214 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6215 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6216 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006217 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006218 }
6219
John McCalla3f81372010-04-13 00:04:31 +00006220 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6221
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006222 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006223 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006224 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6225
6226 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006227 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006228 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006229 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006230 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006231 D.setInvalidType();
6232 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006233
John McCalla3f81372010-04-13 00:04:31 +00006234 // Diagnose "&operator bool()" and other such nonsense. This
6235 // is actually a gcc extension which we don't support.
6236 if (Proto->getResultType() != ConvType) {
6237 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6238 << Proto->getResultType();
6239 D.setInvalidType();
6240 ConvType = Proto->getResultType();
6241 }
6242
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006243 // C++ [class.conv.fct]p4:
6244 // The conversion-type-id shall not represent a function type nor
6245 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006246 if (ConvType->isArrayType()) {
6247 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6248 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006249 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006250 } else if (ConvType->isFunctionType()) {
6251 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6252 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006253 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006254 }
6255
6256 // Rebuild the function type "R" without any parameters (in case any
6257 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006258 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006259 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006260 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006261
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006262 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006263 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006264 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006265 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006266 diag::warn_cxx98_compat_explicit_conversion_functions :
6267 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006268 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006269}
6270
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006271/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6272/// the declaration of the given C++ conversion function. This routine
6273/// is responsible for recording the conversion function in the C++
6274/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006275Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006276 assert(Conversion && "Expected to receive a conversion function declaration");
6277
Douglas Gregor9d350972008-12-12 08:25:50 +00006278 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006279
6280 // Make sure we aren't redeclaring the conversion function.
6281 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006282
6283 // C++ [class.conv.fct]p1:
6284 // [...] A conversion function is never used to convert a
6285 // (possibly cv-qualified) object to the (possibly cv-qualified)
6286 // same object type (or a reference to it), to a (possibly
6287 // cv-qualified) base class of that type (or a reference to it),
6288 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006289 // FIXME: Suppress this warning if the conversion function ends up being a
6290 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006291 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006292 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006293 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006294 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006295 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6296 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006297 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006298 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006299 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6300 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006301 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006302 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006303 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006304 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006305 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006306 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006307 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006308 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006309 }
6310
Douglas Gregore80622f2010-09-29 04:25:11 +00006311 if (FunctionTemplateDecl *ConversionTemplate
6312 = Conversion->getDescribedFunctionTemplate())
6313 return ConversionTemplate;
6314
John McCalld226f652010-08-21 09:40:31 +00006315 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006316}
6317
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006318//===----------------------------------------------------------------------===//
6319// Namespace Handling
6320//===----------------------------------------------------------------------===//
6321
Richard Smithd1a55a62012-10-04 22:13:39 +00006322/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6323/// reopened.
6324static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6325 SourceLocation Loc,
6326 IdentifierInfo *II, bool *IsInline,
6327 NamespaceDecl *PrevNS) {
6328 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006329
Richard Smithc969e6a2012-10-05 01:46:25 +00006330 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6331 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6332 // inline namespaces, with the intention of bringing names into namespace std.
6333 //
6334 // We support this just well enough to get that case working; this is not
6335 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006336 if (*IsInline && II && II->getName().startswith("__atomic") &&
6337 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006338 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006339 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6340 NS = NS->getPreviousDecl())
6341 NS->setInline(*IsInline);
6342 // Patch up the lookup table for the containing namespace. This isn't really
6343 // correct, but it's good enough for this particular case.
6344 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6345 E = PrevNS->decls_end(); I != E; ++I)
6346 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6347 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6348 return;
6349 }
6350
6351 if (PrevNS->isInline())
6352 // The user probably just forgot the 'inline', so suggest that it
6353 // be added back.
6354 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6355 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6356 else
6357 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6358 << IsInline;
6359
6360 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6361 *IsInline = PrevNS->isInline();
6362}
John McCallea318642010-08-26 09:15:37 +00006363
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006364/// ActOnStartNamespaceDef - This is called at the start of a namespace
6365/// definition.
John McCalld226f652010-08-21 09:40:31 +00006366Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006367 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006368 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006369 SourceLocation IdentLoc,
6370 IdentifierInfo *II,
6371 SourceLocation LBrace,
6372 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006373 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6374 // For anonymous namespace, take the location of the left brace.
6375 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006376 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006377 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006378 bool IsStd = false;
6379 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006380 Scope *DeclRegionScope = NamespcScope->getParent();
6381
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006382 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006383 if (II) {
6384 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006385 // The identifier in an original-namespace-definition shall not
6386 // have been previously defined in the declarative region in
6387 // which the original-namespace-definition appears. The
6388 // identifier in an original-namespace-definition is the name of
6389 // the namespace. Subsequently in that declarative region, it is
6390 // treated as an original-namespace-name.
6391 //
6392 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006393 // look through using directives, just look for any ordinary names.
6394
6395 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006396 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6397 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006398 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006399 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6400 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6401 ++I) {
6402 if ((*I)->getIdentifierNamespace() & IDNS) {
6403 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006404 break;
6405 }
6406 }
6407
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006408 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6409
6410 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006411 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006412 if (IsInline != PrevNS->isInline())
6413 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6414 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006415 } else if (PrevDecl) {
6416 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006417 Diag(Loc, diag::err_redefinition_different_kind)
6418 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006419 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006420 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006421 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006422 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006423 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006424 // This is the first "real" definition of the namespace "std", so update
6425 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006426 PrevNS = getStdNamespace();
6427 IsStd = true;
6428 AddToKnown = !IsInline;
6429 } else {
6430 // We've seen this namespace for the first time.
6431 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006432 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006433 } else {
John McCall9aeed322009-10-01 00:25:31 +00006434 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006435
6436 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006437 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006438 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006439 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006440 } else {
6441 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006442 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006443 }
6444
Richard Smithd1a55a62012-10-04 22:13:39 +00006445 if (PrevNS && IsInline != PrevNS->isInline())
6446 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6447 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006448 }
6449
6450 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6451 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006452 if (IsInvalid)
6453 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006454
6455 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006456
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006457 // FIXME: Should we be merging attributes?
6458 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006459 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006460
6461 if (IsStd)
6462 StdNamespace = Namespc;
6463 if (AddToKnown)
6464 KnownNamespaces[Namespc] = false;
6465
6466 if (II) {
6467 PushOnScopeChains(Namespc, DeclRegionScope);
6468 } else {
6469 // Link the anonymous namespace into its parent.
6470 DeclContext *Parent = CurContext->getRedeclContext();
6471 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6472 TU->setAnonymousNamespace(Namespc);
6473 } else {
6474 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006475 }
John McCall9aeed322009-10-01 00:25:31 +00006476
Douglas Gregora4181472010-03-24 00:46:35 +00006477 CurContext->addDecl(Namespc);
6478
John McCall9aeed322009-10-01 00:25:31 +00006479 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6480 // behaves as if it were replaced by
6481 // namespace unique { /* empty body */ }
6482 // using namespace unique;
6483 // namespace unique { namespace-body }
6484 // where all occurrences of 'unique' in a translation unit are
6485 // replaced by the same identifier and this identifier differs
6486 // from all other identifiers in the entire program.
6487
6488 // We just create the namespace with an empty name and then add an
6489 // implicit using declaration, just like the standard suggests.
6490 //
6491 // CodeGen enforces the "universally unique" aspect by giving all
6492 // declarations semantically contained within an anonymous
6493 // namespace internal linkage.
6494
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006495 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006496 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006497 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006498 /* 'using' */ LBrace,
6499 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006500 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006501 /* identifier */ SourceLocation(),
6502 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006503 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006504 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006505 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006506 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006507 }
6508
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006509 ActOnDocumentableDecl(Namespc);
6510
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006511 // Although we could have an invalid decl (i.e. the namespace name is a
6512 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006513 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6514 // for the namespace has the declarations that showed up in that particular
6515 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006516 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006517 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006518}
6519
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006520/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6521/// is a namespace alias, returns the namespace it points to.
6522static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6523 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6524 return AD->getNamespace();
6525 return dyn_cast_or_null<NamespaceDecl>(D);
6526}
6527
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006528/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6529/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006530void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006531 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6532 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006533 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006534 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006535 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006536 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006537}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006538
John McCall384aff82010-08-25 07:42:41 +00006539CXXRecordDecl *Sema::getStdBadAlloc() const {
6540 return cast_or_null<CXXRecordDecl>(
6541 StdBadAlloc.get(Context.getExternalSource()));
6542}
6543
6544NamespaceDecl *Sema::getStdNamespace() const {
6545 return cast_or_null<NamespaceDecl>(
6546 StdNamespace.get(Context.getExternalSource()));
6547}
6548
Douglas Gregor66992202010-06-29 17:53:46 +00006549/// \brief Retrieve the special "std" namespace, which may require us to
6550/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006551NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006552 if (!StdNamespace) {
6553 // The "std" namespace has not yet been defined, so build one implicitly.
6554 StdNamespace = NamespaceDecl::Create(Context,
6555 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006556 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006557 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006558 &PP.getIdentifierTable().get("std"),
6559 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006560 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006561 }
6562
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006563 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006564}
6565
Sebastian Redl395e04d2012-01-17 22:49:33 +00006566bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006567 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006568 "Looking for std::initializer_list outside of C++.");
6569
6570 // We're looking for implicit instantiations of
6571 // template <typename E> class std::initializer_list.
6572
6573 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6574 return false;
6575
Sebastian Redl84760e32012-01-17 22:49:58 +00006576 ClassTemplateDecl *Template = 0;
6577 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006578
Sebastian Redl84760e32012-01-17 22:49:58 +00006579 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006580
Sebastian Redl84760e32012-01-17 22:49:58 +00006581 ClassTemplateSpecializationDecl *Specialization =
6582 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6583 if (!Specialization)
6584 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006585
Sebastian Redl84760e32012-01-17 22:49:58 +00006586 Template = Specialization->getSpecializedTemplate();
6587 Arguments = Specialization->getTemplateArgs().data();
6588 } else if (const TemplateSpecializationType *TST =
6589 Ty->getAs<TemplateSpecializationType>()) {
6590 Template = dyn_cast_or_null<ClassTemplateDecl>(
6591 TST->getTemplateName().getAsTemplateDecl());
6592 Arguments = TST->getArgs();
6593 }
6594 if (!Template)
6595 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006596
6597 if (!StdInitializerList) {
6598 // Haven't recognized std::initializer_list yet, maybe this is it.
6599 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6600 if (TemplateClass->getIdentifier() !=
6601 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006602 !getStdNamespace()->InEnclosingNamespaceSetOf(
6603 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006604 return false;
6605 // This is a template called std::initializer_list, but is it the right
6606 // template?
6607 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006608 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006609 return false;
6610 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6611 return false;
6612
6613 // It's the right template.
6614 StdInitializerList = Template;
6615 }
6616
6617 if (Template != StdInitializerList)
6618 return false;
6619
6620 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006621 if (Element)
6622 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006623 return true;
6624}
6625
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006626static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6627 NamespaceDecl *Std = S.getStdNamespace();
6628 if (!Std) {
6629 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6630 return 0;
6631 }
6632
6633 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6634 Loc, Sema::LookupOrdinaryName);
6635 if (!S.LookupQualifiedName(Result, Std)) {
6636 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6637 return 0;
6638 }
6639 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6640 if (!Template) {
6641 Result.suppressDiagnostics();
6642 // We found something weird. Complain about the first thing we found.
6643 NamedDecl *Found = *Result.begin();
6644 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6645 return 0;
6646 }
6647
6648 // We found some template called std::initializer_list. Now verify that it's
6649 // correct.
6650 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006651 if (Params->getMinRequiredArguments() != 1 ||
6652 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006653 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6654 return 0;
6655 }
6656
6657 return Template;
6658}
6659
6660QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6661 if (!StdInitializerList) {
6662 StdInitializerList = LookupStdInitializerList(*this, Loc);
6663 if (!StdInitializerList)
6664 return QualType();
6665 }
6666
6667 TemplateArgumentListInfo Args(Loc, Loc);
6668 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6669 Context.getTrivialTypeSourceInfo(Element,
6670 Loc)));
6671 return Context.getCanonicalType(
6672 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6673}
6674
Sebastian Redl98d36062012-01-17 22:50:14 +00006675bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6676 // C++ [dcl.init.list]p2:
6677 // A constructor is an initializer-list constructor if its first parameter
6678 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6679 // std::initializer_list<E> for some type E, and either there are no other
6680 // parameters or else all other parameters have default arguments.
6681 if (Ctor->getNumParams() < 1 ||
6682 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6683 return false;
6684
6685 QualType ArgType = Ctor->getParamDecl(0)->getType();
6686 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6687 ArgType = RT->getPointeeType().getUnqualifiedType();
6688
6689 return isStdInitializerList(ArgType, 0);
6690}
6691
Douglas Gregor9172aa62011-03-26 22:25:30 +00006692/// \brief Determine whether a using statement is in a context where it will be
6693/// apply in all contexts.
6694static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6695 switch (CurContext->getDeclKind()) {
6696 case Decl::TranslationUnit:
6697 return true;
6698 case Decl::LinkageSpec:
6699 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6700 default:
6701 return false;
6702 }
6703}
6704
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006705namespace {
6706
6707// Callback to only accept typo corrections that are namespaces.
6708class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006709public:
6710 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6711 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006712 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006713 return false;
6714 }
6715};
6716
6717}
6718
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006719static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6720 CXXScopeSpec &SS,
6721 SourceLocation IdentLoc,
6722 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006723 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006724 R.clear();
6725 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006726 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006727 Validator)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006728 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00006729 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6730 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006731 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00006732 S.diagnoseTypo(Corrected,
6733 S.PDiag(diag::err_using_directive_member_suggest)
6734 << Ident << DC << DroppedSpecifier << SS.getRange(),
6735 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006736 } else {
Richard Smith2d670972013-08-17 00:46:16 +00006737 S.diagnoseTypo(Corrected,
6738 S.PDiag(diag::err_using_directive_suggest) << Ident,
6739 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006740 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006741 R.addDecl(Corrected.getCorrectionDecl());
6742 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006743 }
6744 return false;
6745}
6746
John McCalld226f652010-08-21 09:40:31 +00006747Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006748 SourceLocation UsingLoc,
6749 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006750 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006751 SourceLocation IdentLoc,
6752 IdentifierInfo *NamespcName,
6753 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006754 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6755 assert(NamespcName && "Invalid NamespcName.");
6756 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006757
6758 // This can only happen along a recovery path.
6759 while (S->getFlags() & Scope::TemplateParamScope)
6760 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006761 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006762
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006763 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006764 NestedNameSpecifier *Qualifier = 0;
6765 if (SS.isSet())
6766 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6767
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006768 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006769 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6770 LookupParsedName(R, S, &SS);
6771 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006772 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006773
Douglas Gregor66992202010-06-29 17:53:46 +00006774 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006775 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006776 // Allow "using namespace std;" or "using namespace ::std;" even if
6777 // "std" hasn't been defined yet, for GCC compatibility.
6778 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6779 NamespcName->isStr("std")) {
6780 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006781 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006782 R.resolveKind();
6783 }
6784 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006785 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006786 }
6787
John McCallf36e02d2009-10-09 21:13:30 +00006788 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006789 NamedDecl *Named = R.getFoundDecl();
6790 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6791 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006792 // C++ [namespace.udir]p1:
6793 // A using-directive specifies that the names in the nominated
6794 // namespace can be used in the scope in which the
6795 // using-directive appears after the using-directive. During
6796 // unqualified name lookup (3.4.1), the names appear as if they
6797 // were declared in the nearest enclosing namespace which
6798 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006799 // namespace. [Note: in this context, "contains" means "contains
6800 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006801
6802 // Find enclosing context containing both using-directive and
6803 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006804 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006805 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6806 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6807 CommonAncestor = CommonAncestor->getParent();
6808
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006809 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006810 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006811 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006812
Douglas Gregor9172aa62011-03-26 22:25:30 +00006813 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00006814 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006815 Diag(IdentLoc, diag::warn_using_directive_in_header);
6816 }
6817
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006818 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006819 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006820 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006821 }
6822
Richard Smith6b3d3e52013-02-20 19:22:51 +00006823 if (UDir)
6824 ProcessDeclAttributeList(S, UDir, AttrList);
6825
John McCalld226f652010-08-21 09:40:31 +00006826 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006827}
6828
6829void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006830 // If the scope has an associated entity and the using directive is at
6831 // namespace or translation unit scope, add the UsingDirectiveDecl into
6832 // its lookup structure so qualified name lookup can find it.
6833 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6834 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006835 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006836 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006837 // Otherwise, it is at block sope. The using-directives will affect lookup
6838 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006839 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006840}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006841
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006842
John McCalld226f652010-08-21 09:40:31 +00006843Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006844 AccessSpecifier AS,
6845 bool HasUsingKeyword,
6846 SourceLocation UsingLoc,
6847 CXXScopeSpec &SS,
6848 UnqualifiedId &Name,
6849 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006850 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00006851 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006852 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006853
Douglas Gregor12c118a2009-11-04 16:30:06 +00006854 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006855 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006856 case UnqualifiedId::IK_Identifier:
6857 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006858 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006859 case UnqualifiedId::IK_ConversionFunctionId:
6860 break;
6861
6862 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006863 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006864 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006865 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006866 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006867 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006868 diag::err_using_decl_constructor)
6869 << SS.getRange();
6870
Richard Smith80ad52f2013-01-02 11:42:31 +00006871 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006872
John McCalld226f652010-08-21 09:40:31 +00006873 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006874
6875 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006876 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006877 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006878 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006879
6880 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006881 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006882 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006883 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006884 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006885
6886 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6887 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006888 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006889 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006890
Richard Smith07b0fdc2013-03-18 21:12:30 +00006891 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006892 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00006893 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00006894 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6895 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006896 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006897 }
6898
Douglas Gregor56c04582010-12-16 00:46:58 +00006899 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6900 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6901 return 0;
6902
John McCall9488ea12009-11-17 05:59:44 +00006903 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006904 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006905 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006906 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006907 if (UD)
6908 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006909
John McCalld226f652010-08-21 09:40:31 +00006910 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006911}
6912
Douglas Gregor09acc982010-07-07 23:08:52 +00006913/// \brief Determine whether a using declaration considers the given
6914/// declarations as "equivalent", e.g., if they are redeclarations of
6915/// the same entity or are both typedefs of the same type.
6916static bool
6917IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6918 bool &SuppressRedeclaration) {
6919 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6920 SuppressRedeclaration = false;
6921 return true;
6922 }
6923
Richard Smith162e1c12011-04-15 14:24:37 +00006924 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6925 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006926 SuppressRedeclaration = true;
6927 return Context.hasSameType(TD1->getUnderlyingType(),
6928 TD2->getUnderlyingType());
6929 }
6930
6931 return false;
6932}
6933
6934
John McCall9f54ad42009-12-10 09:41:52 +00006935/// Determines whether to create a using shadow decl for a particular
6936/// decl, given the set of decls existing prior to this using lookup.
6937bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6938 const LookupResult &Previous) {
6939 // Diagnose finding a decl which is not from a base class of the
6940 // current class. We do this now because there are cases where this
6941 // function will silently decide not to build a shadow decl, which
6942 // will pre-empt further diagnostics.
6943 //
6944 // We don't need to do this in C++0x because we do the check once on
6945 // the qualifier.
6946 //
6947 // FIXME: diagnose the following if we care enough:
6948 // struct A { int foo; };
6949 // struct B : A { using A::foo; };
6950 // template <class T> struct C : A {};
6951 // template <class T> struct D : C<T> { using B::foo; } // <---
6952 // This is invalid (during instantiation) in C++03 because B::foo
6953 // resolves to the using decl in B, which is not a base class of D<T>.
6954 // We can't diagnose it immediately because C<T> is an unknown
6955 // specialization. The UsingShadowDecl in D<T> then points directly
6956 // to A::foo, which will look well-formed when we instantiate.
6957 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006958 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006959 DeclContext *OrigDC = Orig->getDeclContext();
6960
6961 // Handle enums and anonymous structs.
6962 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6963 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6964 while (OrigRec->isAnonymousStructOrUnion())
6965 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6966
6967 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6968 if (OrigDC == CurContext) {
6969 Diag(Using->getLocation(),
6970 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006971 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006972 Diag(Orig->getLocation(), diag::note_using_decl_target);
6973 return true;
6974 }
6975
Douglas Gregordc355712011-02-25 00:36:19 +00006976 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006977 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006978 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006979 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006980 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006981 Diag(Orig->getLocation(), diag::note_using_decl_target);
6982 return true;
6983 }
6984 }
6985
6986 if (Previous.empty()) return false;
6987
6988 NamedDecl *Target = Orig;
6989 if (isa<UsingShadowDecl>(Target))
6990 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6991
John McCalld7533ec2009-12-11 02:33:26 +00006992 // If the target happens to be one of the previous declarations, we
6993 // don't have a conflict.
6994 //
6995 // FIXME: but we might be increasing its access, in which case we
6996 // should redeclare it.
6997 NamedDecl *NonTag = 0, *Tag = 0;
6998 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6999 I != E; ++I) {
7000 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00007001 bool Result;
7002 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
7003 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00007004
7005 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7006 }
7007
John McCall9f54ad42009-12-10 09:41:52 +00007008 if (Target->isFunctionOrFunctionTemplate()) {
7009 FunctionDecl *FD;
7010 if (isa<FunctionTemplateDecl>(Target))
7011 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7012 else
7013 FD = cast<FunctionDecl>(Target);
7014
7015 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00007016 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00007017 case Ovl_Overload:
7018 return false;
7019
7020 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00007021 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007022 break;
7023
7024 // We found a decl with the exact signature.
7025 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007026 // If we're in a record, we want to hide the target, so we
7027 // return true (without a diagnostic) to tell the caller not to
7028 // build a shadow decl.
7029 if (CurContext->isRecord())
7030 return true;
7031
7032 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00007033 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007034 break;
7035 }
7036
7037 Diag(Target->getLocation(), diag::note_using_decl_target);
7038 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7039 return true;
7040 }
7041
7042 // Target is not a function.
7043
John McCall9f54ad42009-12-10 09:41:52 +00007044 if (isa<TagDecl>(Target)) {
7045 // No conflict between a tag and a non-tag.
7046 if (!Tag) return false;
7047
John McCall41ce66f2009-12-10 19:51:03 +00007048 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007049 Diag(Target->getLocation(), diag::note_using_decl_target);
7050 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7051 return true;
7052 }
7053
7054 // No conflict between a tag and a non-tag.
7055 if (!NonTag) return false;
7056
John McCall41ce66f2009-12-10 19:51:03 +00007057 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007058 Diag(Target->getLocation(), diag::note_using_decl_target);
7059 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7060 return true;
7061}
7062
John McCall9488ea12009-11-17 05:59:44 +00007063/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00007064UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00007065 UsingDecl *UD,
7066 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00007067
7068 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00007069 NamedDecl *Target = Orig;
7070 if (isa<UsingShadowDecl>(Target)) {
7071 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7072 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00007073 }
7074
7075 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00007076 = UsingShadowDecl::Create(Context, CurContext,
7077 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00007078 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00007079
7080 Shadow->setAccess(UD->getAccess());
7081 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7082 Shadow->setInvalidDecl();
7083
John McCall9488ea12009-11-17 05:59:44 +00007084 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007085 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007086 else
John McCall604e7f12009-12-08 07:46:18 +00007087 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007088
John McCall604e7f12009-12-08 07:46:18 +00007089
John McCall9f54ad42009-12-10 09:41:52 +00007090 return Shadow;
7091}
John McCall604e7f12009-12-08 07:46:18 +00007092
John McCall9f54ad42009-12-10 09:41:52 +00007093/// Hides a using shadow declaration. This is required by the current
7094/// using-decl implementation when a resolvable using declaration in a
7095/// class is followed by a declaration which would hide or override
7096/// one or more of the using decl's targets; for example:
7097///
7098/// struct Base { void foo(int); };
7099/// struct Derived : Base {
7100/// using Base::foo;
7101/// void foo(int);
7102/// };
7103///
7104/// The governing language is C++03 [namespace.udecl]p12:
7105///
7106/// When a using-declaration brings names from a base class into a
7107/// derived class scope, member functions in the derived class
7108/// override and/or hide member functions with the same name and
7109/// parameter types in a base class (rather than conflicting).
7110///
7111/// There are two ways to implement this:
7112/// (1) optimistically create shadow decls when they're not hidden
7113/// by existing declarations, or
7114/// (2) don't create any shadow decls (or at least don't make them
7115/// visible) until we've fully parsed/instantiated the class.
7116/// The problem with (1) is that we might have to retroactively remove
7117/// a shadow decl, which requires several O(n) operations because the
7118/// decl structures are (very reasonably) not designed for removal.
7119/// (2) avoids this but is very fiddly and phase-dependent.
7120void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007121 if (Shadow->getDeclName().getNameKind() ==
7122 DeclarationName::CXXConversionFunctionName)
7123 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7124
John McCall9f54ad42009-12-10 09:41:52 +00007125 // Remove it from the DeclContext...
7126 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007127
John McCall9f54ad42009-12-10 09:41:52 +00007128 // ...and the scope, if applicable...
7129 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007130 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007131 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007132 }
7133
John McCall9f54ad42009-12-10 09:41:52 +00007134 // ...and the using decl.
7135 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7136
7137 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007138 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007139}
7140
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007141namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007142class UsingValidatorCCC : public CorrectionCandidateCallback {
7143public:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007144 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation)
7145 : HasTypenameKeyword(HasTypenameKeyword),
7146 IsInstantiation(IsInstantiation) {}
7147
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007148 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7149 NamedDecl *ND = Candidate.getCorrectionDecl();
7150
7151 // Keywords are not valid here.
7152 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007153 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007154
7155 // Completely unqualified names are invalid for a 'using' declaration.
7156 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7157 return false;
7158
7159 if (isa<TypeDecl>(ND))
7160 return HasTypenameKeyword || !IsInstantiation;
7161
7162 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007163 }
7164
7165private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007166 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007167 bool IsInstantiation;
7168};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007169} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007170
John McCall7ba107a2009-11-18 02:36:19 +00007171/// Builds a using declaration.
7172///
7173/// \param IsInstantiation - Whether this call arises from an
7174/// instantiation of an unresolved using declaration. We treat
7175/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007176NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7177 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007178 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007179 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007180 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007181 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007182 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007183 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007184 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007185 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007186 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007187
Anders Carlsson550b14b2009-08-28 05:49:21 +00007188 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007189
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007190 if (SS.isEmpty()) {
7191 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007192 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007193 }
Mike Stump1eb44332009-09-09 15:08:12 +00007194
John McCall9f54ad42009-12-10 09:41:52 +00007195 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007196 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007197 ForRedeclaration);
7198 Previous.setHideTags(false);
7199 if (S) {
7200 LookupName(Previous, S);
7201
7202 // It is really dumb that we have to do this.
7203 LookupResult::Filter F = Previous.makeFilter();
7204 while (F.hasNext()) {
7205 NamedDecl *D = F.next();
7206 if (!isDeclInScope(D, CurContext, S))
7207 F.erase();
7208 }
7209 F.done();
7210 } else {
7211 assert(IsInstantiation && "no scope in non-instantiation");
7212 assert(CurContext->isRecord() && "scope not record in instantiation");
7213 LookupQualifiedName(Previous, CurContext);
7214 }
7215
John McCall9f54ad42009-12-10 09:41:52 +00007216 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007217 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7218 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007219 return 0;
7220
7221 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007222 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7223 return 0;
7224
John McCallaf8e6ed2009-11-12 03:15:40 +00007225 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007226 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007227 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007228 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007229 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007230 // FIXME: not all declaration name kinds are legal here
7231 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7232 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007233 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007234 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007235 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007236 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7237 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007238 }
John McCalled976492009-12-04 22:46:56 +00007239 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007240 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007241 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007242 }
John McCalled976492009-12-04 22:46:56 +00007243 D->setAccess(AS);
7244 CurContext->addDecl(D);
7245
7246 if (!LookupContext) return D;
7247 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007248
John McCall77bb1aa2010-05-01 00:40:08 +00007249 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007250 UD->setInvalidDecl();
7251 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007252 }
7253
Richard Smithc5a89a12012-04-02 01:30:27 +00007254 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007255 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007256 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007257 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007258 return UD;
7259 }
7260
7261 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007262
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007263 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007264
John McCall604e7f12009-12-08 07:46:18 +00007265 // Unlike most lookups, we don't always want to hide tag
7266 // declarations: tag names are visible through the using declaration
7267 // even if hidden by ordinary names, *except* in a dependent context
7268 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007269 if (!IsInstantiation)
7270 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007271
John McCallb9abd8722012-04-07 03:04:20 +00007272 // For the purposes of this lookup, we have a base object type
7273 // equal to that of the current context.
7274 if (CurContext->isRecord()) {
7275 R.setBaseObjectType(
7276 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7277 }
7278
John McCalla24dc2e2009-11-17 02:14:36 +00007279 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007280
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007281 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007282 if (R.empty()) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007283 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation);
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007284 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7285 R.getLookupKind(), S, &SS, CCC)){
7286 // We reject any correction for which ND would be NULL.
7287 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007288 R.setLookupName(Corrected.getCorrection());
7289 R.addDecl(ND);
Richard Smith2d670972013-08-17 00:46:16 +00007290 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007291 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007292 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7293 << NameInfo.getName() << LookupContext << 0
7294 << SS.getRange());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007295 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007296 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007297 << NameInfo.getName() << LookupContext << SS.getRange();
7298 UD->setInvalidDecl();
7299 return UD;
7300 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007301 }
7302
John McCalled976492009-12-04 22:46:56 +00007303 if (R.isAmbiguous()) {
7304 UD->setInvalidDecl();
7305 return UD;
7306 }
Mike Stump1eb44332009-09-09 15:08:12 +00007307
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007308 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007309 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007310 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007311 Diag(IdentLoc, diag::err_using_typename_non_type);
7312 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7313 Diag((*I)->getUnderlyingDecl()->getLocation(),
7314 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007315 UD->setInvalidDecl();
7316 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007317 }
7318 } else {
7319 // If we asked for a non-typename and we got a type, error out,
7320 // but only if this is an instantiation of an unresolved using
7321 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007322 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007323 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7324 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007325 UD->setInvalidDecl();
7326 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007327 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007328 }
7329
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007330 // C++0x N2914 [namespace.udecl]p6:
7331 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007332 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007333 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7334 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007335 UD->setInvalidDecl();
7336 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007337 }
Mike Stump1eb44332009-09-09 15:08:12 +00007338
John McCall9f54ad42009-12-10 09:41:52 +00007339 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7340 if (!CheckUsingShadowDecl(UD, *I, Previous))
7341 BuildUsingShadowDecl(S, UD, *I);
7342 }
John McCall9488ea12009-11-17 05:59:44 +00007343
7344 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007345}
7346
Sebastian Redlf677ea32011-02-05 19:23:19 +00007347/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007348bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007349 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007350
Douglas Gregordc355712011-02-25 00:36:19 +00007351 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007352 assert(SourceType &&
7353 "Using decl naming constructor doesn't have type in scope spec.");
7354 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7355
7356 // Check whether the named type is a direct base class.
7357 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7358 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7359 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7360 BaseIt != BaseE; ++BaseIt) {
7361 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7362 if (CanonicalSourceType == BaseType)
7363 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007364 if (BaseIt->getType()->isDependentType())
7365 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007366 }
7367
7368 if (BaseIt == BaseE) {
7369 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007370 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007371 diag::err_using_decl_constructor_not_in_direct_base)
7372 << UD->getNameInfo().getSourceRange()
7373 << QualType(SourceType, 0) << TargetClass;
7374 return true;
7375 }
7376
Richard Smithc5a89a12012-04-02 01:30:27 +00007377 if (!CurContext->isDependentContext())
7378 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007379
7380 return false;
7381}
7382
John McCall9f54ad42009-12-10 09:41:52 +00007383/// Checks that the given using declaration is not an invalid
7384/// redeclaration. Note that this is checking only for the using decl
7385/// itself, not for any ill-formedness among the UsingShadowDecls.
7386bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007387 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007388 const CXXScopeSpec &SS,
7389 SourceLocation NameLoc,
7390 const LookupResult &Prev) {
7391 // C++03 [namespace.udecl]p8:
7392 // C++0x [namespace.udecl]p10:
7393 // A using-declaration is a declaration and can therefore be used
7394 // repeatedly where (and only where) multiple declarations are
7395 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007396 //
John McCall8a726212010-11-29 18:01:58 +00007397 // That's in non-member contexts.
7398 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007399 return false;
7400
7401 NestedNameSpecifier *Qual
7402 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7403
7404 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7405 NamedDecl *D = *I;
7406
7407 bool DTypename;
7408 NestedNameSpecifier *DQual;
7409 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007410 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007411 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007412 } else if (UnresolvedUsingValueDecl *UD
7413 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7414 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007415 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007416 } else if (UnresolvedUsingTypenameDecl *UD
7417 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7418 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007419 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007420 } else continue;
7421
7422 // using decls differ if one says 'typename' and the other doesn't.
7423 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007424 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007425
7426 // using decls differ if they name different scopes (but note that
7427 // template instantiation can cause this check to trigger when it
7428 // didn't before instantiation).
7429 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7430 Context.getCanonicalNestedNameSpecifier(DQual))
7431 continue;
7432
7433 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007434 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007435 return true;
7436 }
7437
7438 return false;
7439}
7440
John McCall604e7f12009-12-08 07:46:18 +00007441
John McCalled976492009-12-04 22:46:56 +00007442/// Checks that the given nested-name qualifier used in a using decl
7443/// in the current context is appropriately related to the current
7444/// scope. If an error is found, diagnoses it and returns true.
7445bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7446 const CXXScopeSpec &SS,
7447 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007448 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007449
John McCall604e7f12009-12-08 07:46:18 +00007450 if (!CurContext->isRecord()) {
7451 // C++03 [namespace.udecl]p3:
7452 // C++0x [namespace.udecl]p8:
7453 // A using-declaration for a class member shall be a member-declaration.
7454
7455 // If we weren't able to compute a valid scope, it must be a
7456 // dependent class scope.
7457 if (!NamedContext || NamedContext->isRecord()) {
7458 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7459 << SS.getRange();
7460 return true;
7461 }
7462
7463 // Otherwise, everything is known to be fine.
7464 return false;
7465 }
7466
7467 // The current scope is a record.
7468
7469 // If the named context is dependent, we can't decide much.
7470 if (!NamedContext) {
7471 // FIXME: in C++0x, we can diagnose if we can prove that the
7472 // nested-name-specifier does not refer to a base class, which is
7473 // still possible in some cases.
7474
7475 // Otherwise we have to conservatively report that things might be
7476 // okay.
7477 return false;
7478 }
7479
7480 if (!NamedContext->isRecord()) {
7481 // Ideally this would point at the last name in the specifier,
7482 // but we don't have that level of source info.
7483 Diag(SS.getRange().getBegin(),
7484 diag::err_using_decl_nested_name_specifier_is_not_class)
7485 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7486 return true;
7487 }
7488
Douglas Gregor6fb07292010-12-21 07:41:49 +00007489 if (!NamedContext->isDependentContext() &&
7490 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7491 return true;
7492
Richard Smith80ad52f2013-01-02 11:42:31 +00007493 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007494 // C++0x [namespace.udecl]p3:
7495 // In a using-declaration used as a member-declaration, the
7496 // nested-name-specifier shall name a base class of the class
7497 // being defined.
7498
7499 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7500 cast<CXXRecordDecl>(NamedContext))) {
7501 if (CurContext == NamedContext) {
7502 Diag(NameLoc,
7503 diag::err_using_decl_nested_name_specifier_is_current_class)
7504 << SS.getRange();
7505 return true;
7506 }
7507
7508 Diag(SS.getRange().getBegin(),
7509 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7510 << (NestedNameSpecifier*) SS.getScopeRep()
7511 << cast<CXXRecordDecl>(CurContext)
7512 << SS.getRange();
7513 return true;
7514 }
7515
7516 return false;
7517 }
7518
7519 // C++03 [namespace.udecl]p4:
7520 // A using-declaration used as a member-declaration shall refer
7521 // to a member of a base class of the class being defined [etc.].
7522
7523 // Salient point: SS doesn't have to name a base class as long as
7524 // lookup only finds members from base classes. Therefore we can
7525 // diagnose here only if we can prove that that can't happen,
7526 // i.e. if the class hierarchies provably don't intersect.
7527
7528 // TODO: it would be nice if "definitely valid" results were cached
7529 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7530 // need to be repeated.
7531
7532 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007533 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007534
7535 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7536 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7537 Data->Bases.insert(Base);
7538 return true;
7539 }
7540
7541 bool hasDependentBases(const CXXRecordDecl *Class) {
7542 return !Class->forallBases(collect, this);
7543 }
7544
7545 /// Returns true if the base is dependent or is one of the
7546 /// accumulated base classes.
7547 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7548 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7549 return !Data->Bases.count(Base);
7550 }
7551
7552 bool mightShareBases(const CXXRecordDecl *Class) {
7553 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7554 }
7555 };
7556
7557 UserData Data;
7558
7559 // Returns false if we find a dependent base.
7560 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7561 return false;
7562
7563 // Returns false if the class has a dependent base or if it or one
7564 // of its bases is present in the base set of the current context.
7565 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7566 return false;
7567
7568 Diag(SS.getRange().getBegin(),
7569 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7570 << (NestedNameSpecifier*) SS.getScopeRep()
7571 << cast<CXXRecordDecl>(CurContext)
7572 << SS.getRange();
7573
7574 return true;
John McCalled976492009-12-04 22:46:56 +00007575}
7576
Richard Smith162e1c12011-04-15 14:24:37 +00007577Decl *Sema::ActOnAliasDeclaration(Scope *S,
7578 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007579 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007580 SourceLocation UsingLoc,
7581 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007582 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007583 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007584 // Skip up to the relevant declaration scope.
7585 while (S->getFlags() & Scope::TemplateParamScope)
7586 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007587 assert((S->getFlags() & Scope::DeclScope) &&
7588 "got alias-declaration outside of declaration scope");
7589
7590 if (Type.isInvalid())
7591 return 0;
7592
7593 bool Invalid = false;
7594 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7595 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007596 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007597
7598 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7599 return 0;
7600
7601 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007602 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007603 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007604 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7605 TInfo->getTypeLoc().getBeginLoc());
7606 }
Richard Smith162e1c12011-04-15 14:24:37 +00007607
7608 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7609 LookupName(Previous, S);
7610
7611 // Warn about shadowing the name of a template parameter.
7612 if (Previous.isSingleResult() &&
7613 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007614 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007615 Previous.clear();
7616 }
7617
7618 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7619 "name in alias declaration must be an identifier");
7620 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7621 Name.StartLocation,
7622 Name.Identifier, TInfo);
7623
7624 NewTD->setAccess(AS);
7625
7626 if (Invalid)
7627 NewTD->setInvalidDecl();
7628
Richard Smith6b3d3e52013-02-20 19:22:51 +00007629 ProcessDeclAttributeList(S, NewTD, AttrList);
7630
Richard Smith3e4c6c42011-05-05 21:57:07 +00007631 CheckTypedefForVariablyModifiedType(S, NewTD);
7632 Invalid |= NewTD->isInvalidDecl();
7633
Richard Smith162e1c12011-04-15 14:24:37 +00007634 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007635
7636 NamedDecl *NewND;
7637 if (TemplateParamLists.size()) {
7638 TypeAliasTemplateDecl *OldDecl = 0;
7639 TemplateParameterList *OldTemplateParams = 0;
7640
7641 if (TemplateParamLists.size() != 1) {
7642 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007643 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7644 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007645 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007646 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007647
7648 // Only consider previous declarations in the same scope.
7649 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7650 /*ExplicitInstantiationOrSpecialization*/false);
7651 if (!Previous.empty()) {
7652 Redeclaration = true;
7653
7654 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7655 if (!OldDecl && !Invalid) {
7656 Diag(UsingLoc, diag::err_redefinition_different_kind)
7657 << Name.Identifier;
7658
7659 NamedDecl *OldD = Previous.getRepresentativeDecl();
7660 if (OldD->getLocation().isValid())
7661 Diag(OldD->getLocation(), diag::note_previous_definition);
7662
7663 Invalid = true;
7664 }
7665
7666 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7667 if (TemplateParameterListsAreEqual(TemplateParams,
7668 OldDecl->getTemplateParameters(),
7669 /*Complain=*/true,
7670 TPL_TemplateMatch))
7671 OldTemplateParams = OldDecl->getTemplateParameters();
7672 else
7673 Invalid = true;
7674
7675 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7676 if (!Invalid &&
7677 !Context.hasSameType(OldTD->getUnderlyingType(),
7678 NewTD->getUnderlyingType())) {
7679 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7680 // but we can't reasonably accept it.
7681 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7682 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7683 if (OldTD->getLocation().isValid())
7684 Diag(OldTD->getLocation(), diag::note_previous_definition);
7685 Invalid = true;
7686 }
7687 }
7688 }
7689
7690 // Merge any previous default template arguments into our parameters,
7691 // and check the parameter list.
7692 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7693 TPC_TypeAliasTemplate))
7694 return 0;
7695
7696 TypeAliasTemplateDecl *NewDecl =
7697 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7698 Name.Identifier, TemplateParams,
7699 NewTD);
7700
7701 NewDecl->setAccess(AS);
7702
7703 if (Invalid)
7704 NewDecl->setInvalidDecl();
7705 else if (OldDecl)
7706 NewDecl->setPreviousDeclaration(OldDecl);
7707
7708 NewND = NewDecl;
7709 } else {
7710 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7711 NewND = NewTD;
7712 }
Richard Smith162e1c12011-04-15 14:24:37 +00007713
7714 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007715 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007716
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007717 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007718 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007719}
7720
John McCalld226f652010-08-21 09:40:31 +00007721Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007722 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007723 SourceLocation AliasLoc,
7724 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007725 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007726 SourceLocation IdentLoc,
7727 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007728
Anders Carlsson81c85c42009-03-28 23:53:49 +00007729 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007730 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7731 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007732
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007733 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007734 NamedDecl *PrevDecl
7735 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7736 ForRedeclaration);
7737 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7738 PrevDecl = 0;
7739
7740 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007741 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007742 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007743 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007744 // FIXME: At some point, we'll want to create the (redundant)
7745 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007746 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007747 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007748 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007749 }
Mike Stump1eb44332009-09-09 15:08:12 +00007750
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007751 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7752 diag::err_redefinition_different_kind;
7753 Diag(AliasLoc, DiagID) << Alias;
7754 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007755 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007756 }
7757
John McCalla24dc2e2009-11-17 02:14:36 +00007758 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007759 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007760
John McCallf36e02d2009-10-09 21:13:30 +00007761 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007762 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007763 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007764 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007765 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007766 }
Mike Stump1eb44332009-09-09 15:08:12 +00007767
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007768 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007769 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007770 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007771 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007772
John McCall3dbd3d52010-02-16 06:53:13 +00007773 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007774 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007775}
7776
Sean Hunt001cad92011-05-10 00:49:42 +00007777Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007778Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7779 CXXMethodDecl *MD) {
7780 CXXRecordDecl *ClassDecl = MD->getParent();
7781
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007782 // C++ [except.spec]p14:
7783 // An implicitly declared special member function (Clause 12) shall have an
7784 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007785 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007786 if (ClassDecl->isInvalidDecl())
7787 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007788
Sebastian Redl60618fa2011-03-12 11:50:43 +00007789 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007790 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7791 BEnd = ClassDecl->bases_end();
7792 B != BEnd; ++B) {
7793 if (B->isVirtual()) // Handled below.
7794 continue;
7795
Douglas Gregor18274032010-07-03 00:47:00 +00007796 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7797 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007798 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7799 // If this is a deleted function, add it anyway. This might be conformant
7800 // with the standard. This might not. I'm not sure. It might not matter.
7801 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007802 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007803 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007804 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007805
7806 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007807 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7808 BEnd = ClassDecl->vbases_end();
7809 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007810 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7811 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007812 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7813 // If this is a deleted function, add it anyway. This might be conformant
7814 // with the standard. This might not. I'm not sure. It might not matter.
7815 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007816 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007817 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007818 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007819
7820 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007821 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7822 FEnd = ClassDecl->field_end();
7823 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007824 if (F->hasInClassInitializer()) {
7825 if (Expr *E = F->getInClassInitializer())
7826 ExceptSpec.CalledExpr(E);
7827 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007828 // DR1351:
7829 // If the brace-or-equal-initializer of a non-static data member
7830 // invokes a defaulted default constructor of its class or of an
7831 // enclosing class in a potentially evaluated subexpression, the
7832 // program is ill-formed.
7833 //
7834 // This resolution is unworkable: the exception specification of the
7835 // default constructor can be needed in an unevaluated context, in
7836 // particular, in the operand of a noexcept-expression, and we can be
7837 // unable to compute an exception specification for an enclosed class.
7838 //
7839 // We do not allow an in-class initializer to require the evaluation
7840 // of the exception specification for any in-class initializer whose
7841 // definition is not lexically complete.
7842 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007843 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007844 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007845 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7846 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7847 // If this is a deleted function, add it anyway. This might be conformant
7848 // with the standard. This might not. I'm not sure. It might not matter.
7849 // In particular, the problem is that this function never gets called. It
7850 // might just be ill-formed because this function attempts to refer to
7851 // a deleted function here.
7852 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007853 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007854 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007855 }
John McCalle23cf432010-12-14 08:05:40 +00007856
Sean Hunt001cad92011-05-10 00:49:42 +00007857 return ExceptSpec;
7858}
7859
Richard Smith07b0fdc2013-03-18 21:12:30 +00007860Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007861Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7862 CXXRecordDecl *ClassDecl = CD->getParent();
7863
7864 // C++ [except.spec]p14:
7865 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007866 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007867 if (ClassDecl->isInvalidDecl())
7868 return ExceptSpec;
7869
7870 // Inherited constructor.
7871 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7872 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7873 // FIXME: Copying or moving the parameters could add extra exceptions to the
7874 // set, as could the default arguments for the inherited constructor. This
7875 // will be addressed when we implement the resolution of core issue 1351.
7876 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7877
7878 // Direct base-class constructors.
7879 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7880 BEnd = ClassDecl->bases_end();
7881 B != BEnd; ++B) {
7882 if (B->isVirtual()) // Handled below.
7883 continue;
7884
7885 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7886 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7887 if (BaseClassDecl == InheritedDecl)
7888 continue;
7889 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7890 if (Constructor)
7891 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7892 }
7893 }
7894
7895 // Virtual base-class constructors.
7896 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7897 BEnd = ClassDecl->vbases_end();
7898 B != BEnd; ++B) {
7899 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7900 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7901 if (BaseClassDecl == InheritedDecl)
7902 continue;
7903 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7904 if (Constructor)
7905 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7906 }
7907 }
7908
7909 // Field constructors.
7910 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7911 FEnd = ClassDecl->field_end();
7912 F != FEnd; ++F) {
7913 if (F->hasInClassInitializer()) {
7914 if (Expr *E = F->getInClassInitializer())
7915 ExceptSpec.CalledExpr(E);
7916 else if (!F->isInvalidDecl())
7917 Diag(CD->getLocation(),
7918 diag::err_in_class_initializer_references_def_ctor) << CD;
7919 } else if (const RecordType *RecordTy
7920 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7921 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7922 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7923 if (Constructor)
7924 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7925 }
7926 }
7927
Richard Smith07b0fdc2013-03-18 21:12:30 +00007928 return ExceptSpec;
7929}
7930
Richard Smithafb49182012-11-29 01:34:07 +00007931namespace {
7932/// RAII object to register a special member as being currently declared.
7933struct DeclaringSpecialMember {
7934 Sema &S;
7935 Sema::SpecialMemberDecl D;
7936 bool WasAlreadyBeingDeclared;
7937
7938 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7939 : S(S), D(RD, CSM) {
7940 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7941 if (WasAlreadyBeingDeclared)
7942 // This almost never happens, but if it does, ensure that our cache
7943 // doesn't contain a stale result.
7944 S.SpecialMemberCache.clear();
7945
7946 // FIXME: Register a note to be produced if we encounter an error while
7947 // declaring the special member.
7948 }
7949 ~DeclaringSpecialMember() {
7950 if (!WasAlreadyBeingDeclared)
7951 S.SpecialMembersBeingDeclared.erase(D);
7952 }
7953
7954 /// \brief Are we already trying to declare this special member?
7955 bool isAlreadyBeingDeclared() const {
7956 return WasAlreadyBeingDeclared;
7957 }
7958};
7959}
7960
Sean Hunt001cad92011-05-10 00:49:42 +00007961CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7962 CXXRecordDecl *ClassDecl) {
7963 // C++ [class.ctor]p5:
7964 // A default constructor for a class X is a constructor of class X
7965 // that can be called without an argument. If there is no
7966 // user-declared constructor for class X, a default constructor is
7967 // implicitly declared. An implicitly-declared default constructor
7968 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007969 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007970 "Should not build implicit default constructor!");
7971
Richard Smithafb49182012-11-29 01:34:07 +00007972 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7973 if (DSM.isAlreadyBeingDeclared())
7974 return 0;
7975
Richard Smith7756afa2012-06-10 05:43:50 +00007976 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7977 CXXDefaultConstructor,
7978 false);
7979
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007980 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007981 CanQualType ClassType
7982 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007983 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007984 DeclarationName Name
7985 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007986 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007987 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007988 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007989 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007990 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007991 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007992 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007993 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007994
7995 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00007996 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00007997 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007998
Richard Smithbc2a35d2012-12-08 08:32:28 +00007999 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8000 // constructors is easy to compute.
8001 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8002
8003 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008004 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008005
Douglas Gregor18274032010-07-03 00:47:00 +00008006 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00008007 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00008008
Douglas Gregor23c94db2010-07-02 17:43:08 +00008009 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00008010 PushOnScopeChains(DefaultCon, S, false);
8011 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00008012
Douglas Gregor32df23e2010-07-01 22:02:46 +00008013 return DefaultCon;
8014}
8015
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008016void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8017 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00008018 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008019 !Constructor->doesThisDeclarationHaveABody() &&
8020 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00008021 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008022
Anders Carlssonf6513ed2010-04-23 16:04:08 +00008023 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00008024 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00008025
Eli Friedman9a14db32012-10-18 20:14:08 +00008026 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008027 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00008028 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008029 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008030 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00008031 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00008032 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008033 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00008034 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008035
8036 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008037 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008038
Eli Friedman86164e82013-09-05 00:02:25 +00008039 Constructor->markUsed(Context);
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008040 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008041
8042 if (ASTMutationListener *L = getASTMutationListener()) {
8043 L->CompletedImplicitDefinition(Constructor);
8044 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008045}
8046
Richard Smith7a614d82011-06-11 17:19:42 +00008047void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00008048 // Check that any explicitly-defaulted methods have exception specifications
8049 // compatible with their implicit exception specifications.
8050 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00008051}
8052
Richard Smith4841ca52013-04-10 05:48:59 +00008053namespace {
8054/// Information on inheriting constructors to declare.
8055class InheritingConstructorInfo {
8056public:
8057 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8058 : SemaRef(SemaRef), Derived(Derived) {
8059 // Mark the constructors that we already have in the derived class.
8060 //
8061 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8062 // unless there is a user-declared constructor with the same signature in
8063 // the class where the using-declaration appears.
8064 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8065 }
8066
8067 void inheritAll(CXXRecordDecl *RD) {
8068 visitAll(RD, &InheritingConstructorInfo::inherit);
8069 }
8070
8071private:
8072 /// Information about an inheriting constructor.
8073 struct InheritingConstructor {
8074 InheritingConstructor()
8075 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8076
8077 /// If \c true, a constructor with this signature is already declared
8078 /// in the derived class.
8079 bool DeclaredInDerived;
8080
8081 /// The constructor which is inherited.
8082 const CXXConstructorDecl *BaseCtor;
8083
8084 /// The derived constructor we declared.
8085 CXXConstructorDecl *DerivedCtor;
8086 };
8087
8088 /// Inheriting constructors with a given canonical type. There can be at
8089 /// most one such non-template constructor, and any number of templated
8090 /// constructors.
8091 struct InheritingConstructorsForType {
8092 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008093 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8094 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008095
8096 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8097 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8098 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8099 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8100 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8101 false, S.TPL_TemplateMatch))
8102 return Templates[I].second;
8103 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8104 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008105 }
Richard Smith4841ca52013-04-10 05:48:59 +00008106
8107 return NonTemplate;
8108 }
8109 };
8110
8111 /// Get or create the inheriting constructor record for a constructor.
8112 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8113 QualType CtorType) {
8114 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8115 .getEntry(SemaRef, Ctor);
8116 }
8117
8118 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8119
8120 /// Process all constructors for a class.
8121 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8122 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8123 CtorE = RD->ctor_end();
8124 CtorIt != CtorE; ++CtorIt)
8125 (this->*Callback)(*CtorIt);
8126 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8127 I(RD->decls_begin()), E(RD->decls_end());
8128 I != E; ++I) {
8129 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8130 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8131 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008132 }
8133 }
Richard Smith4841ca52013-04-10 05:48:59 +00008134
8135 /// Note that a constructor (or constructor template) was declared in Derived.
8136 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8137 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8138 }
8139
8140 /// Inherit a single constructor.
8141 void inherit(const CXXConstructorDecl *Ctor) {
8142 const FunctionProtoType *CtorType =
8143 Ctor->getType()->castAs<FunctionProtoType>();
8144 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8145 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8146
8147 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8148
8149 // Core issue (no number yet): the ellipsis is always discarded.
8150 if (EPI.Variadic) {
8151 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8152 SemaRef.Diag(Ctor->getLocation(),
8153 diag::note_using_decl_constructor_ellipsis);
8154 EPI.Variadic = false;
8155 }
8156
8157 // Declare a constructor for each number of parameters.
8158 //
8159 // C++11 [class.inhctor]p1:
8160 // The candidate set of inherited constructors from the class X named in
8161 // the using-declaration consists of [... modulo defects ...] for each
8162 // constructor or constructor template of X, the set of constructors or
8163 // constructor templates that results from omitting any ellipsis parameter
8164 // specification and successively omitting parameters with a default
8165 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008166 unsigned MinParams = minParamsToInherit(Ctor);
8167 unsigned Params = Ctor->getNumParams();
8168 if (Params >= MinParams) {
8169 do
8170 declareCtor(UsingLoc, Ctor,
8171 SemaRef.Context.getFunctionType(
8172 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8173 while (Params > MinParams &&
8174 Ctor->getParamDecl(--Params)->hasDefaultArg());
8175 }
Richard Smith4841ca52013-04-10 05:48:59 +00008176 }
8177
8178 /// Find the using-declaration which specified that we should inherit the
8179 /// constructors of \p Base.
8180 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8181 // No fancy lookup required; just look for the base constructor name
8182 // directly within the derived class.
8183 ASTContext &Context = SemaRef.Context;
8184 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8185 Context.getCanonicalType(Context.getRecordType(Base)));
8186 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8187 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8188 }
8189
8190 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8191 // C++11 [class.inhctor]p3:
8192 // [F]or each constructor template in the candidate set of inherited
8193 // constructors, a constructor template is implicitly declared
8194 if (Ctor->getDescribedFunctionTemplate())
8195 return 0;
8196
8197 // For each non-template constructor in the candidate set of inherited
8198 // constructors other than a constructor having no parameters or a
8199 // copy/move constructor having a single parameter, a constructor is
8200 // implicitly declared [...]
8201 if (Ctor->getNumParams() == 0)
8202 return 1;
8203 if (Ctor->isCopyOrMoveConstructor())
8204 return 2;
8205
8206 // Per discussion on core reflector, never inherit a constructor which
8207 // would become a default, copy, or move constructor of Derived either.
8208 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8209 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8210 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8211 }
8212
8213 /// Declare a single inheriting constructor, inheriting the specified
8214 /// constructor, with the given type.
8215 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8216 QualType DerivedType) {
8217 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8218
8219 // C++11 [class.inhctor]p3:
8220 // ... a constructor is implicitly declared with the same constructor
8221 // characteristics unless there is a user-declared constructor with
8222 // the same signature in the class where the using-declaration appears
8223 if (Entry.DeclaredInDerived)
8224 return;
8225
8226 // C++11 [class.inhctor]p7:
8227 // If two using-declarations declare inheriting constructors with the
8228 // same signature, the program is ill-formed
8229 if (Entry.DerivedCtor) {
8230 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8231 // Only diagnose this once per constructor.
8232 if (Entry.DerivedCtor->isInvalidDecl())
8233 return;
8234 Entry.DerivedCtor->setInvalidDecl();
8235
8236 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8237 SemaRef.Diag(BaseCtor->getLocation(),
8238 diag::note_using_decl_constructor_conflict_current_ctor);
8239 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8240 diag::note_using_decl_constructor_conflict_previous_ctor);
8241 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8242 diag::note_using_decl_constructor_conflict_previous_using);
8243 } else {
8244 // Core issue (no number): if the same inheriting constructor is
8245 // produced by multiple base class constructors from the same base
8246 // class, the inheriting constructor is defined as deleted.
8247 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8248 }
8249
8250 return;
8251 }
8252
8253 ASTContext &Context = SemaRef.Context;
8254 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8255 Context.getCanonicalType(Context.getRecordType(Derived)));
8256 DeclarationNameInfo NameInfo(Name, UsingLoc);
8257
8258 TemplateParameterList *TemplateParams = 0;
8259 if (const FunctionTemplateDecl *FTD =
8260 BaseCtor->getDescribedFunctionTemplate()) {
8261 TemplateParams = FTD->getTemplateParameters();
8262 // We're reusing template parameters from a different DeclContext. This
8263 // is questionable at best, but works out because the template depth in
8264 // both places is guaranteed to be 0.
8265 // FIXME: Rebuild the template parameters in the new context, and
8266 // transform the function type to refer to them.
8267 }
8268
8269 // Build type source info pointing at the using-declaration. This is
8270 // required by template instantiation.
8271 TypeSourceInfo *TInfo =
8272 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8273 FunctionProtoTypeLoc ProtoLoc =
8274 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8275
8276 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8277 Context, Derived, UsingLoc, NameInfo, DerivedType,
8278 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8279 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8280
8281 // Build an unevaluated exception specification for this constructor.
8282 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8283 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8284 EPI.ExceptionSpecType = EST_Unevaluated;
8285 EPI.ExceptionSpecDecl = DerivedCtor;
8286 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8287 FPT->getArgTypes(), EPI));
8288
8289 // Build the parameter declarations.
8290 SmallVector<ParmVarDecl *, 16> ParamDecls;
8291 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8292 TypeSourceInfo *TInfo =
8293 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8294 ParmVarDecl *PD = ParmVarDecl::Create(
8295 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8296 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8297 PD->setScopeInfo(0, I);
8298 PD->setImplicit();
8299 ParamDecls.push_back(PD);
8300 ProtoLoc.setArg(I, PD);
8301 }
8302
8303 // Set up the new constructor.
8304 DerivedCtor->setAccess(BaseCtor->getAccess());
8305 DerivedCtor->setParams(ParamDecls);
8306 DerivedCtor->setInheritedConstructor(BaseCtor);
8307 if (BaseCtor->isDeleted())
8308 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8309
8310 // If this is a constructor template, build the template declaration.
8311 if (TemplateParams) {
8312 FunctionTemplateDecl *DerivedTemplate =
8313 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8314 TemplateParams, DerivedCtor);
8315 DerivedTemplate->setAccess(BaseCtor->getAccess());
8316 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8317 Derived->addDecl(DerivedTemplate);
8318 } else {
8319 Derived->addDecl(DerivedCtor);
8320 }
8321
8322 Entry.BaseCtor = BaseCtor;
8323 Entry.DerivedCtor = DerivedCtor;
8324 }
8325
8326 Sema &SemaRef;
8327 CXXRecordDecl *Derived;
8328 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8329 MapType Map;
8330};
8331}
8332
8333void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8334 // Defer declaring the inheriting constructors until the class is
8335 // instantiated.
8336 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008337 return;
8338
Richard Smith4841ca52013-04-10 05:48:59 +00008339 // Find base classes from which we might inherit constructors.
8340 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8341 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8342 BaseE = ClassDecl->bases_end();
8343 BaseIt != BaseE; ++BaseIt)
8344 if (BaseIt->getInheritConstructors())
8345 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008346
Richard Smith4841ca52013-04-10 05:48:59 +00008347 // Go no further if we're not inheriting any constructors.
8348 if (InheritedBases.empty())
8349 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008350
Richard Smith4841ca52013-04-10 05:48:59 +00008351 // Declare the inherited constructors.
8352 InheritingConstructorInfo ICI(*this, ClassDecl);
8353 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8354 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008355}
8356
Richard Smith07b0fdc2013-03-18 21:12:30 +00008357void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8358 CXXConstructorDecl *Constructor) {
8359 CXXRecordDecl *ClassDecl = Constructor->getParent();
8360 assert(Constructor->getInheritedConstructor() &&
8361 !Constructor->doesThisDeclarationHaveABody() &&
8362 !Constructor->isDeleted());
8363
8364 SynthesizedFunctionScope Scope(*this, Constructor);
8365 DiagnosticErrorTrap Trap(Diags);
8366 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8367 Trap.hasErrorOccurred()) {
8368 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8369 << Context.getTagDeclType(ClassDecl);
8370 Constructor->setInvalidDecl();
8371 return;
8372 }
8373
8374 SourceLocation Loc = Constructor->getLocation();
8375 Constructor->setBody(new (Context) CompoundStmt(Loc));
8376
Eli Friedman86164e82013-09-05 00:02:25 +00008377 Constructor->markUsed(Context);
Richard Smith07b0fdc2013-03-18 21:12:30 +00008378 MarkVTableUsed(CurrentLocation, ClassDecl);
8379
8380 if (ASTMutationListener *L = getASTMutationListener()) {
8381 L->CompletedImplicitDefinition(Constructor);
8382 }
8383}
8384
8385
Sean Huntcb45a0f2011-05-12 22:46:25 +00008386Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008387Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8388 CXXRecordDecl *ClassDecl = MD->getParent();
8389
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008390 // C++ [except.spec]p14:
8391 // An implicitly declared special member function (Clause 12) shall have
8392 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008393 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008394 if (ClassDecl->isInvalidDecl())
8395 return ExceptSpec;
8396
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008397 // Direct base-class destructors.
8398 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8399 BEnd = ClassDecl->bases_end();
8400 B != BEnd; ++B) {
8401 if (B->isVirtual()) // Handled below.
8402 continue;
8403
8404 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008405 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008406 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008407 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008408
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008409 // Virtual base-class destructors.
8410 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8411 BEnd = ClassDecl->vbases_end();
8412 B != BEnd; ++B) {
8413 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008414 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008415 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008416 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008417
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008418 // Field destructors.
8419 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8420 FEnd = ClassDecl->field_end();
8421 F != FEnd; ++F) {
8422 if (const RecordType *RecordTy
8423 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008424 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008425 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008426 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008427
Sean Huntcb45a0f2011-05-12 22:46:25 +00008428 return ExceptSpec;
8429}
8430
8431CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8432 // C++ [class.dtor]p2:
8433 // If a class has no user-declared destructor, a destructor is
8434 // declared implicitly. An implicitly-declared destructor is an
8435 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008436 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008437
Richard Smithafb49182012-11-29 01:34:07 +00008438 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8439 if (DSM.isAlreadyBeingDeclared())
8440 return 0;
8441
Douglas Gregor4923aa22010-07-02 20:37:36 +00008442 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008443 CanQualType ClassType
8444 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008445 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008446 DeclarationName Name
8447 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008448 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008449 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008450 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8451 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008452 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008453 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008454 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008455 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008456
8457 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008458 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008459 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008460
Richard Smithbc2a35d2012-12-08 08:32:28 +00008461 AddOverriddenMethods(ClassDecl, Destructor);
8462
8463 // We don't need to use SpecialMemberIsTrivial here; triviality for
8464 // destructors is easy to compute.
8465 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8466
8467 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008468 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008469
Douglas Gregor4923aa22010-07-02 20:37:36 +00008470 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008471 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008472
Douglas Gregor4923aa22010-07-02 20:37:36 +00008473 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008474 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008475 PushOnScopeChains(Destructor, S, false);
8476 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008477
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008478 return Destructor;
8479}
8480
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008481void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008482 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008483 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008484 !Destructor->doesThisDeclarationHaveABody() &&
8485 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008486 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008487 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008488 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008489
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008490 if (Destructor->isInvalidDecl())
8491 return;
8492
Eli Friedman9a14db32012-10-18 20:14:08 +00008493 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008494
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008495 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008496 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8497 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008498
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008499 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008500 Diag(CurrentLocation, diag::note_member_synthesized_at)
8501 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8502
8503 Destructor->setInvalidDecl();
8504 return;
8505 }
8506
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008507 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008508 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman86164e82013-09-05 00:02:25 +00008509 Destructor->markUsed(Context);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008510 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008511
8512 if (ASTMutationListener *L = getASTMutationListener()) {
8513 L->CompletedImplicitDefinition(Destructor);
8514 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008515}
8516
Richard Smitha4156b82012-04-21 18:42:51 +00008517/// \brief Perform any semantic analysis which needs to be delayed until all
8518/// pending class member declarations have been parsed.
8519void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008520 // If the context is an invalid C++ class, just suppress these checks.
8521 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8522 if (Record->isInvalidDecl()) {
8523 DelayedDestructorExceptionSpecChecks.clear();
8524 return;
8525 }
8526 }
8527
Richard Smitha4156b82012-04-21 18:42:51 +00008528 // Perform any deferred checking of exception specifications for virtual
8529 // destructors.
8530 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8531 i != e; ++i) {
8532 const CXXDestructorDecl *Dtor =
8533 DelayedDestructorExceptionSpecChecks[i].first;
8534 assert(!Dtor->getParent()->isDependentType() &&
8535 "Should not ever add destructors of templates into the list.");
8536 CheckOverridingFunctionExceptionSpec(Dtor,
8537 DelayedDestructorExceptionSpecChecks[i].second);
8538 }
8539 DelayedDestructorExceptionSpecChecks.clear();
8540}
8541
Richard Smithb9d0b762012-07-27 04:22:15 +00008542void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8543 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008544 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008545 "adjusting dtor exception specs was introduced in c++11");
8546
Sebastian Redl0ee33912011-05-19 05:13:44 +00008547 // C++11 [class.dtor]p3:
8548 // A declaration of a destructor that does not have an exception-
8549 // specification is implicitly considered to have the same exception-
8550 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008551 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008552 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008553 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008554 return;
8555
Chandler Carruth3f224b22011-09-20 04:55:26 +00008556 // Replace the destructor's type, building off the existing one. Fortunately,
8557 // the only thing of interest in the destructor type is its extended info.
8558 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008559 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8560 EPI.ExceptionSpecType = EST_Unevaluated;
8561 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008562 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008563
Sebastian Redl0ee33912011-05-19 05:13:44 +00008564 // FIXME: If the destructor has a body that could throw, and the newly created
8565 // spec doesn't allow exceptions, we should emit a warning, because this
8566 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008567 // However, we don't have a body or an exception specification yet, so it
8568 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008569}
8570
Pavel Labath66ea35d2013-08-30 08:52:28 +00008571namespace {
8572/// \brief An abstract base class for all helper classes used in building the
8573// copy/move operators. These classes serve as factory functions and help us
8574// avoid using the same Expr* in the AST twice.
8575class ExprBuilder {
8576 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8577 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8578
8579protected:
8580 static Expr *assertNotNull(Expr *E) {
8581 assert(E && "Expression construction must not fail.");
8582 return E;
8583 }
8584
8585public:
8586 ExprBuilder() {}
8587 virtual ~ExprBuilder() {}
8588
8589 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8590};
8591
8592class RefBuilder: public ExprBuilder {
8593 VarDecl *Var;
8594 QualType VarType;
8595
8596public:
8597 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8598 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8599 }
8600
8601 RefBuilder(VarDecl *Var, QualType VarType)
8602 : Var(Var), VarType(VarType) {}
8603};
8604
8605class ThisBuilder: public ExprBuilder {
8606public:
8607 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8608 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8609 }
8610};
8611
8612class CastBuilder: public ExprBuilder {
8613 const ExprBuilder &Builder;
8614 QualType Type;
8615 ExprValueKind Kind;
8616 const CXXCastPath &Path;
8617
8618public:
8619 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8620 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8621 CK_UncheckedDerivedToBase, Kind,
8622 &Path).take());
8623 }
8624
8625 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8626 const CXXCastPath &Path)
8627 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8628};
8629
8630class DerefBuilder: public ExprBuilder {
8631 const ExprBuilder &Builder;
8632
8633public:
8634 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8635 return assertNotNull(
8636 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8637 }
8638
8639 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8640};
8641
8642class MemberBuilder: public ExprBuilder {
8643 const ExprBuilder &Builder;
8644 QualType Type;
8645 CXXScopeSpec SS;
8646 bool IsArrow;
8647 LookupResult &MemberLookup;
8648
8649public:
8650 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8651 return assertNotNull(S.BuildMemberReferenceExpr(
8652 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8653 MemberLookup, 0).take());
8654 }
8655
8656 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8657 LookupResult &MemberLookup)
8658 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8659 MemberLookup(MemberLookup) {}
8660};
8661
8662class MoveCastBuilder: public ExprBuilder {
8663 const ExprBuilder &Builder;
8664
8665public:
8666 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8667 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8668 }
8669
8670 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8671};
8672
8673class LvalueConvBuilder: public ExprBuilder {
8674 const ExprBuilder &Builder;
8675
8676public:
8677 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8678 return assertNotNull(
8679 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8680 }
8681
8682 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8683};
8684
8685class SubscriptBuilder: public ExprBuilder {
8686 const ExprBuilder &Base;
8687 const ExprBuilder &Index;
8688
8689public:
8690 virtual Expr *build(Sema &S, SourceLocation Loc) const
8691 LLVM_OVERRIDE {
8692 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8693 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8694 }
8695
8696 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8697 : Base(Base), Index(Index) {}
8698};
8699
8700} // end anonymous namespace
8701
Richard Smith8c889532012-11-14 00:50:40 +00008702/// When generating a defaulted copy or move assignment operator, if a field
8703/// should be copied with __builtin_memcpy rather than via explicit assignments,
8704/// do so. This optimization only applies for arrays of scalars, and for arrays
8705/// of class type where the selected copy/move-assignment operator is trivial.
8706static StmtResult
8707buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008708 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00008709 // Compute the size of the memory buffer to be copied.
8710 QualType SizeType = S.Context.getSizeType();
8711 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8712 S.Context.getTypeSizeInChars(T).getQuantity());
8713
8714 // Take the address of the field references for "from" and "to". We
8715 // directly construct UnaryOperators here because semantic analysis
8716 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008717 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008718 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8719 S.Context.getPointerType(From->getType()),
8720 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00008721 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008722 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8723 S.Context.getPointerType(To->getType()),
8724 VK_RValue, OK_Ordinary, Loc);
8725
8726 const Type *E = T->getBaseElementTypeUnsafe();
8727 bool NeedsCollectableMemCpy =
8728 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8729
8730 // Create a reference to the __builtin_objc_memmove_collectable function
8731 StringRef MemCpyName = NeedsCollectableMemCpy ?
8732 "__builtin_objc_memmove_collectable" :
8733 "__builtin_memcpy";
8734 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8735 Sema::LookupOrdinaryName);
8736 S.LookupName(R, S.TUScope, true);
8737
8738 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8739 if (!MemCpy)
8740 // Something went horribly wrong earlier, and we will have complained
8741 // about it.
8742 return StmtError();
8743
8744 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8745 VK_RValue, Loc, 0);
8746 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8747
8748 Expr *CallArgs[] = {
8749 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8750 };
8751 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8752 Loc, CallArgs, Loc);
8753
8754 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8755 return S.Owned(Call.takeAs<Stmt>());
8756}
8757
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008758/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008759/// \c To.
8760///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008761/// This routine is used to copy/move the members of a class with an
8762/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008763/// copied are arrays, this routine builds for loops to copy them.
8764///
8765/// \param S The Sema object used for type-checking.
8766///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008767/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008768///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008769/// \param T The type of the expressions being copied/moved. Both expressions
8770/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008771///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008772/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008773///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008774/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008775///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008776/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008777/// Otherwise, it's a non-static member subobject.
8778///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008779/// \param Copying Whether we're copying or moving.
8780///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008781/// \param Depth Internal parameter recording the depth of the recursion.
8782///
Richard Smith8c889532012-11-14 00:50:40 +00008783/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8784/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008785static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008786buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008787 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008788 bool CopyingBaseSubobject, bool Copying,
8789 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008790 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008791 // Each subobject is assigned in the manner appropriate to its type:
8792 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008793 // - if the subobject is of class type, as if by a call to operator= with
8794 // the subobject as the object expression and the corresponding
8795 // subobject of x as a single function argument (as if by explicit
8796 // qualification; that is, ignoring any possible virtual overriding
8797 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008798 //
8799 // C++03 [class.copy]p13:
8800 // - if the subobject is of class type, the copy assignment operator for
8801 // the class is used (as if by explicit qualification; that is,
8802 // ignoring any possible virtual overriding functions in more derived
8803 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008804 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8805 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008806
Douglas Gregor06a9f362010-05-01 20:49:11 +00008807 // Look for operator=.
8808 DeclarationName Name
8809 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8810 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8811 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008812
Richard Smith044c8aa2012-11-13 00:54:12 +00008813 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8814 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008815 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008816 LookupResult::Filter F = OpLookup.makeFilter();
8817 while (F.hasNext()) {
8818 NamedDecl *D = F.next();
8819 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8820 if (Method->isCopyAssignmentOperator() ||
8821 (!Copying && Method->isMoveAssignmentOperator()))
8822 continue;
8823
8824 F.erase();
8825 }
8826 F.done();
John McCallb0207482010-03-16 06:11:48 +00008827 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008828
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008829 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008830 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008831 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008832 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008833 // ambiguities), we need to cast "this" to that subobject type; to
8834 // ensure that we don't go through the virtual call mechanism, we need
8835 // to qualify the operator= name with the base class (see below). However,
8836 // this means that if the base class has a protected copy assignment
8837 // operator, the protected member access check will fail. So, we
8838 // rewrite "protected" access to "public" access in this case, since we
8839 // know by construction that we're calling from a derived class.
8840 if (CopyingBaseSubobject) {
8841 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8842 L != LEnd; ++L) {
8843 if (L.getAccess() == AS_protected)
8844 L.setAccess(AS_public);
8845 }
8846 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008847
Douglas Gregor06a9f362010-05-01 20:49:11 +00008848 // Create the nested-name-specifier that will be used to qualify the
8849 // reference to operator=; this is required to suppress the virtual
8850 // call mechanism.
8851 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008852 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008853 SS.MakeTrivial(S.Context,
8854 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008855 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008856 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008857
Douglas Gregor06a9f362010-05-01 20:49:11 +00008858 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008859 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00008860 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
8861 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008862 /*FirstQualifierInScope=*/0,
8863 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008864 /*TemplateArgs=*/0,
8865 /*SuppressQualifierCheck=*/true);
8866 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008867 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008868
Douglas Gregor06a9f362010-05-01 20:49:11 +00008869 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008870
Pavel Labath66ea35d2013-08-30 08:52:28 +00008871 Expr *FromInst = From.build(S, Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008872 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008873 OpEqualRef.takeAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00008874 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008875 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008876 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008877
Richard Smith8c889532012-11-14 00:50:40 +00008878 // If we built a call to a trivial 'operator=' while copying an array,
8879 // bail out. We'll replace the whole shebang with a memcpy.
8880 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8881 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8882 return StmtResult((Stmt*)0);
8883
Richard Smith044c8aa2012-11-13 00:54:12 +00008884 // Convert to an expression-statement, and clean up any produced
8885 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008886 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008887 }
John McCallb0207482010-03-16 06:11:48 +00008888
Richard Smith044c8aa2012-11-13 00:54:12 +00008889 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008890 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008891 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008892 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008893 ExprResult Assignment = S.CreateBuiltinBinOp(
8894 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008895 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008896 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008897 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008898 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008899
8900 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008901 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008902
Douglas Gregor06a9f362010-05-01 20:49:11 +00008903 // Construct a loop over the array bounds, e.g.,
8904 //
8905 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8906 //
8907 // that will copy each of the array elements.
8908 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008909
Douglas Gregor06a9f362010-05-01 20:49:11 +00008910 // Create the iteration variable.
8911 IdentifierInfo *IterationVarName = 0;
8912 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008913 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008914 llvm::raw_svector_ostream OS(Str);
8915 OS << "__i" << Depth;
8916 IterationVarName = &S.Context.Idents.get(OS.str());
8917 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008918 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008919 IterationVarName, SizeType,
8920 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008921 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008922
Douglas Gregor06a9f362010-05-01 20:49:11 +00008923 // Initialize the iteration variable to zero.
8924 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008925 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008926
Pavel Labath66ea35d2013-08-30 08:52:28 +00008927 // Creates a reference to the iteration variable.
8928 RefBuilder IterationVarRef(IterationVar, SizeType);
8929 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00008930
Douglas Gregor06a9f362010-05-01 20:49:11 +00008931 // Create the DeclStmt that holds the iteration variable.
8932 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008933
Douglas Gregor06a9f362010-05-01 20:49:11 +00008934 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008935 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
8936 MoveCastBuilder FromIndexMove(FromIndexCopy);
8937 const ExprBuilder *FromIndex;
8938 if (Copying)
8939 FromIndex = &FromIndexCopy;
8940 else
8941 FromIndex = &FromIndexMove;
8942
8943 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008944
8945 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008946 StmtResult Copy =
8947 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00008948 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00008949 Copying, Depth + 1);
8950 // Bail out if copying fails or if we determined that we should use memcpy.
8951 if (Copy.isInvalid() || !Copy.get())
8952 return Copy;
8953
8954 // Create the comparison against the array bound.
8955 llvm::APInt Upper
8956 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8957 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00008958 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00008959 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8960 BO_NE, S.Context.BoolTy,
8961 VK_RValue, OK_Ordinary, Loc, false);
8962
8963 // Create the pre-increment of the iteration variable.
8964 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00008965 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
8966 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008967
Douglas Gregor06a9f362010-05-01 20:49:11 +00008968 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008969 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008970 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008971 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008972 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008973}
8974
Richard Smith8c889532012-11-14 00:50:40 +00008975static StmtResult
8976buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008977 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008978 bool CopyingBaseSubobject, bool Copying) {
8979 // Maybe we should use a memcpy?
8980 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8981 T.isTriviallyCopyableType(S.Context))
8982 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8983
8984 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8985 CopyingBaseSubobject,
8986 Copying, 0));
8987
8988 // If we ended up picking a trivial assignment operator for an array of a
8989 // non-trivially-copyable class type, just emit a memcpy.
8990 if (!Result.isInvalid() && !Result.get())
8991 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8992
8993 return Result;
8994}
8995
Richard Smithb9d0b762012-07-27 04:22:15 +00008996Sema::ImplicitExceptionSpecification
8997Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8998 CXXRecordDecl *ClassDecl = MD->getParent();
8999
9000 ImplicitExceptionSpecification ExceptSpec(*this);
9001 if (ClassDecl->isInvalidDecl())
9002 return ExceptSpec;
9003
9004 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9005 assert(T->getNumArgs() == 1 && "not a copy assignment op");
9006 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9007
Douglas Gregorb87786f2010-07-01 17:48:08 +00009008 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00009009 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00009010 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00009011
9012 // It is unspecified whether or not an implicit copy assignment operator
9013 // attempts to deduplicate calls to assignment operators of virtual bases are
9014 // made. As such, this exception specification is effectively unspecified.
9015 // Based on a similar decision made for constness in C++0x, we're erring on
9016 // the side of assuming such calls to be made regardless of whether they
9017 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00009018 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9019 BaseEnd = ClassDecl->bases_end();
9020 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00009021 if (Base->isVirtual())
9022 continue;
9023
Douglas Gregora376d102010-07-02 21:50:04 +00009024 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00009025 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009026 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9027 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009028 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00009029 }
Sean Hunt661c67a2011-06-21 23:42:56 +00009030
9031 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9032 BaseEnd = ClassDecl->vbases_end();
9033 Base != BaseEnd; ++Base) {
9034 CXXRecordDecl *BaseClassDecl
9035 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9036 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9037 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009038 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00009039 }
9040
Douglas Gregorb87786f2010-07-01 17:48:08 +00009041 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9042 FieldEnd = ClassDecl->field_end();
9043 Field != FieldEnd;
9044 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009045 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00009046 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9047 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009048 LookupCopyingAssignment(FieldClassDecl,
9049 ArgQuals | FieldType.getCVRQualifiers(),
9050 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009051 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009052 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00009053 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009054
Richard Smithb9d0b762012-07-27 04:22:15 +00009055 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00009056}
9057
9058CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9059 // Note: The following rules are largely analoguous to the copy
9060 // constructor rules. Note that virtual bases are not taken into account
9061 // for determining the argument type of the operator. Note also that
9062 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00009063 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00009064
Richard Smithafb49182012-11-29 01:34:07 +00009065 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9066 if (DSM.isAlreadyBeingDeclared())
9067 return 0;
9068
Sean Hunt30de05c2011-05-14 05:23:20 +00009069 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9070 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00009071 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9072 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00009073 ArgType = ArgType.withConst();
9074 ArgType = Context.getLValueReferenceType(ArgType);
9075
Richard Smitha8942d72013-05-07 03:19:20 +00009076 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9077 CXXCopyAssignment,
9078 Const);
9079
Douglas Gregord3c35902010-07-01 16:36:15 +00009080 // An implicitly-declared copy assignment operator is an inline public
9081 // member of its class.
9082 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009083 SourceLocation ClassLoc = ClassDecl->getLocation();
9084 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009085 CXXMethodDecl *CopyAssignment =
9086 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9087 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9088 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00009089 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00009090 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00009091 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00009092
9093 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009094 FunctionProtoType::ExtProtoInfo EPI =
9095 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009096 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009097
Douglas Gregord3c35902010-07-01 16:36:15 +00009098 // Add the parameter to the operator.
9099 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009100 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00009101 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009102 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009103 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00009104
Richard Smithbc2a35d2012-12-08 08:32:28 +00009105 AddOverriddenMethods(ClassDecl, CopyAssignment);
9106
9107 CopyAssignment->setTrivial(
9108 ClassDecl->needsOverloadResolutionForCopyAssignment()
9109 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9110 : ClassDecl->hasTrivialCopyAssignment());
9111
Richard Smitha8942d72013-05-07 03:19:20 +00009112 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00009113 // .... If the class definition does not explicitly declare a copy
9114 // assignment operator, there is no user-declared move constructor, and
9115 // there is no user-declared move assignment operator, a copy assignment
9116 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009117 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009118 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009119
Richard Smithbc2a35d2012-12-08 08:32:28 +00009120 // Note that we have added this copy-assignment operator.
9121 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9122
9123 if (Scope *S = getScopeForContext(ClassDecl))
9124 PushOnScopeChains(CopyAssignment, S, false);
9125 ClassDecl->addDecl(CopyAssignment);
9126
Douglas Gregord3c35902010-07-01 16:36:15 +00009127 return CopyAssignment;
9128}
9129
Richard Smith36155c12013-06-13 03:23:42 +00009130/// Diagnose an implicit copy operation for a class which is odr-used, but
9131/// which is deprecated because the class has a user-declared copy constructor,
9132/// copy assignment operator, or destructor.
9133static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9134 SourceLocation UseLoc) {
9135 assert(CopyOp->isImplicit());
9136
9137 CXXRecordDecl *RD = CopyOp->getParent();
9138 CXXMethodDecl *UserDeclaredOperation = 0;
9139
9140 // In Microsoft mode, assignment operations don't affect constructors and
9141 // vice versa.
9142 if (RD->hasUserDeclaredDestructor()) {
9143 UserDeclaredOperation = RD->getDestructor();
9144 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9145 RD->hasUserDeclaredCopyConstructor() &&
9146 !S.getLangOpts().MicrosoftMode) {
9147 // Find any user-declared copy constructor.
9148 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9149 E = RD->ctor_end(); I != E; ++I) {
9150 if (I->isCopyConstructor()) {
9151 UserDeclaredOperation = *I;
9152 break;
9153 }
9154 }
9155 assert(UserDeclaredOperation);
9156 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9157 RD->hasUserDeclaredCopyAssignment() &&
9158 !S.getLangOpts().MicrosoftMode) {
9159 // Find any user-declared move assignment operator.
9160 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9161 E = RD->method_end(); I != E; ++I) {
9162 if (I->isCopyAssignmentOperator()) {
9163 UserDeclaredOperation = *I;
9164 break;
9165 }
9166 }
9167 assert(UserDeclaredOperation);
9168 }
9169
9170 if (UserDeclaredOperation) {
9171 S.Diag(UserDeclaredOperation->getLocation(),
9172 diag::warn_deprecated_copy_operation)
9173 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9174 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9175 S.Diag(UseLoc, diag::note_member_synthesized_at)
9176 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9177 : Sema::CXXCopyAssignment)
9178 << RD;
9179 }
9180}
9181
Douglas Gregor06a9f362010-05-01 20:49:11 +00009182void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9183 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00009184 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009185 CopyAssignOperator->isOverloadedOperator() &&
9186 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009187 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9188 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009189 "DefineImplicitCopyAssignment called for wrong function");
9190
9191 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9192
9193 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9194 CopyAssignOperator->setInvalidDecl();
9195 return;
9196 }
Richard Smith36155c12013-06-13 03:23:42 +00009197
9198 // C++11 [class.copy]p18:
9199 // The [definition of an implicitly declared copy assignment operator] is
9200 // deprecated if the class has a user-declared copy constructor or a
9201 // user-declared destructor.
9202 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9203 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9204
Eli Friedman86164e82013-09-05 00:02:25 +00009205 CopyAssignOperator->markUsed(Context);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009206
Eli Friedman9a14db32012-10-18 20:14:08 +00009207 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009208 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009209
9210 // C++0x [class.copy]p30:
9211 // The implicitly-defined or explicitly-defaulted copy assignment operator
9212 // for a non-union class X performs memberwise copy assignment of its
9213 // subobjects. The direct base classes of X are assigned first, in the
9214 // order of their declaration in the base-specifier-list, and then the
9215 // immediate non-static data members of X are assigned, in the order in
9216 // which they were declared in the class definition.
9217
9218 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009219 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009220
9221 // The parameter for the "other" object, which we are copying from.
9222 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9223 Qualifiers OtherQuals = Other->getType().getQualifiers();
9224 QualType OtherRefType = Other->getType();
9225 if (const LValueReferenceType *OtherRef
9226 = OtherRefType->getAs<LValueReferenceType>()) {
9227 OtherRefType = OtherRef->getPointeeType();
9228 OtherQuals = OtherRefType.getQualifiers();
9229 }
9230
9231 // Our location for everything implicitly-generated.
9232 SourceLocation Loc = CopyAssignOperator->getLocation();
9233
Pavel Labath66ea35d2013-08-30 08:52:28 +00009234 // Builds a DeclRefExpr for the "other" object.
9235 RefBuilder OtherRef(Other, OtherRefType);
9236
9237 // Builds the "this" pointer.
9238 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009239
9240 // Assign base classes.
9241 bool Invalid = false;
9242 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9243 E = ClassDecl->bases_end(); Base != E; ++Base) {
9244 // Form the assignment:
9245 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9246 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009247 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009248 Invalid = true;
9249 continue;
9250 }
9251
John McCallf871d0c2010-08-07 06:22:56 +00009252 CXXCastPath BasePath;
9253 BasePath.push_back(Base);
9254
Douglas Gregor06a9f362010-05-01 20:49:11 +00009255 // Construct the "from" expression, which is an implicit cast to the
9256 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009257 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9258 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009259
9260 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009261 DerefBuilder DerefThis(This);
9262 CastBuilder To(DerefThis,
9263 Context.getCVRQualifiedType(
9264 BaseType, CopyAssignOperator->getTypeQualifiers()),
9265 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009266
9267 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009268 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009269 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009270 /*CopyingBaseSubobject=*/true,
9271 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009272 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009273 Diag(CurrentLocation, diag::note_member_synthesized_at)
9274 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9275 CopyAssignOperator->setInvalidDecl();
9276 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009277 }
9278
9279 // Success! Record the copy.
9280 Statements.push_back(Copy.takeAs<Expr>());
9281 }
9282
Douglas Gregor06a9f362010-05-01 20:49:11 +00009283 // Assign non-static members.
9284 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9285 FieldEnd = ClassDecl->field_end();
9286 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009287 if (Field->isUnnamedBitfield())
9288 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009289
9290 if (Field->isInvalidDecl()) {
9291 Invalid = true;
9292 continue;
9293 }
9294
Douglas Gregor06a9f362010-05-01 20:49:11 +00009295 // Check for members of reference type; we can't copy those.
9296 if (Field->getType()->isReferenceType()) {
9297 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9298 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9299 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009300 Diag(CurrentLocation, diag::note_member_synthesized_at)
9301 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009302 Invalid = true;
9303 continue;
9304 }
9305
9306 // Check for members of const-qualified, non-class type.
9307 QualType BaseType = Context.getBaseElementType(Field->getType());
9308 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9309 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9310 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9311 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009312 Diag(CurrentLocation, diag::note_member_synthesized_at)
9313 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009314 Invalid = true;
9315 continue;
9316 }
John McCallb77115d2011-06-17 00:18:42 +00009317
9318 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009319 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9320 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009321
9322 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009323 if (FieldType->isIncompleteArrayType()) {
9324 assert(ClassDecl->hasFlexibleArrayMember() &&
9325 "Incomplete array type is not valid");
9326 continue;
9327 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009328
9329 // Build references to the field in the object we're copying from and to.
9330 CXXScopeSpec SS; // Intentionally empty
9331 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9332 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009333 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009334 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009335
9336 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9337
9338 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009339
Douglas Gregor06a9f362010-05-01 20:49:11 +00009340 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009341 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009342 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009343 /*CopyingBaseSubobject=*/false,
9344 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009345 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009346 Diag(CurrentLocation, diag::note_member_synthesized_at)
9347 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9348 CopyAssignOperator->setInvalidDecl();
9349 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009350 }
9351
9352 // Success! Record the copy.
9353 Statements.push_back(Copy.takeAs<Stmt>());
9354 }
9355
9356 if (!Invalid) {
9357 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009358 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009359
John McCall60d7b3a2010-08-24 06:29:42 +00009360 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009361 if (Return.isInvalid())
9362 Invalid = true;
9363 else {
9364 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009365
9366 if (Trap.hasErrorOccurred()) {
9367 Diag(CurrentLocation, diag::note_member_synthesized_at)
9368 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9369 Invalid = true;
9370 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009371 }
9372 }
9373
9374 if (Invalid) {
9375 CopyAssignOperator->setInvalidDecl();
9376 return;
9377 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009378
9379 StmtResult Body;
9380 {
9381 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009382 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009383 /*isStmtExpr=*/false);
9384 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9385 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009386 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009387
9388 if (ASTMutationListener *L = getASTMutationListener()) {
9389 L->CompletedImplicitDefinition(CopyAssignOperator);
9390 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009391}
9392
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009393Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009394Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9395 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009396
Richard Smithb9d0b762012-07-27 04:22:15 +00009397 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009398 if (ClassDecl->isInvalidDecl())
9399 return ExceptSpec;
9400
9401 // C++0x [except.spec]p14:
9402 // An implicitly declared special member function (Clause 12) shall have an
9403 // exception-specification. [...]
9404
9405 // It is unspecified whether or not an implicit move assignment operator
9406 // attempts to deduplicate calls to assignment operators of virtual bases are
9407 // made. As such, this exception specification is effectively unspecified.
9408 // Based on a similar decision made for constness in C++0x, we're erring on
9409 // the side of assuming such calls to be made regardless of whether they
9410 // actually happen.
9411 // Note that a move constructor is not implicitly declared when there are
9412 // virtual bases, but it can still be user-declared and explicitly defaulted.
9413 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9414 BaseEnd = ClassDecl->bases_end();
9415 Base != BaseEnd; ++Base) {
9416 if (Base->isVirtual())
9417 continue;
9418
9419 CXXRecordDecl *BaseClassDecl
9420 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9421 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009422 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009423 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009424 }
9425
9426 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9427 BaseEnd = ClassDecl->vbases_end();
9428 Base != BaseEnd; ++Base) {
9429 CXXRecordDecl *BaseClassDecl
9430 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9431 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009432 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009433 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009434 }
9435
9436 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9437 FieldEnd = ClassDecl->field_end();
9438 Field != FieldEnd;
9439 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009440 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009441 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009442 if (CXXMethodDecl *MoveAssign =
9443 LookupMovingAssignment(FieldClassDecl,
9444 FieldType.getCVRQualifiers(),
9445 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009446 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009447 }
9448 }
9449
9450 return ExceptSpec;
9451}
9452
Richard Smith1c931be2012-04-02 18:40:40 +00009453/// Determine whether the class type has any direct or indirect virtual base
9454/// classes which have a non-trivial move assignment operator.
9455static bool
9456hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9457 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9458 BaseEnd = ClassDecl->vbases_end();
9459 Base != BaseEnd; ++Base) {
9460 CXXRecordDecl *BaseClass =
9461 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9462
9463 // Try to declare the move assignment. If it would be deleted, then the
9464 // class does not have a non-trivial move assignment.
9465 if (BaseClass->needsImplicitMoveAssignment())
9466 S.DeclareImplicitMoveAssignment(BaseClass);
9467
Richard Smith426391c2012-11-16 00:53:38 +00009468 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009469 return true;
9470 }
9471
9472 return false;
9473}
9474
9475/// Determine whether the given type either has a move constructor or is
9476/// trivially copyable.
9477static bool
9478hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9479 Type = S.Context.getBaseElementType(Type);
9480
9481 // FIXME: Technically, non-trivially-copyable non-class types, such as
9482 // reference types, are supposed to return false here, but that appears
9483 // to be a standard defect.
9484 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009485 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009486 return true;
9487
9488 if (Type.isTriviallyCopyableType(S.Context))
9489 return true;
9490
9491 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009492 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9493 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009494 if (ClassDecl->needsImplicitMoveConstructor())
9495 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009496 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009497 }
9498
Richard Smithe5411b72012-12-01 02:35:44 +00009499 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9500 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009501 if (ClassDecl->needsImplicitMoveAssignment())
9502 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009503 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009504}
9505
9506/// Determine whether all non-static data members and direct or virtual bases
9507/// of class \p ClassDecl have either a move operation, or are trivially
9508/// copyable.
9509static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9510 bool IsConstructor) {
9511 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9512 BaseEnd = ClassDecl->bases_end();
9513 Base != BaseEnd; ++Base) {
9514 if (Base->isVirtual())
9515 continue;
9516
9517 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9518 return false;
9519 }
9520
9521 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9522 BaseEnd = ClassDecl->vbases_end();
9523 Base != BaseEnd; ++Base) {
9524 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9525 return false;
9526 }
9527
9528 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9529 FieldEnd = ClassDecl->field_end();
9530 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009531 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009532 return false;
9533 }
9534
9535 return true;
9536}
9537
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009538CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009539 // C++11 [class.copy]p20:
9540 // If the definition of a class X does not explicitly declare a move
9541 // assignment operator, one will be implicitly declared as defaulted
9542 // if and only if:
9543 //
9544 // - [first 4 bullets]
9545 assert(ClassDecl->needsImplicitMoveAssignment());
9546
Richard Smithafb49182012-11-29 01:34:07 +00009547 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9548 if (DSM.isAlreadyBeingDeclared())
9549 return 0;
9550
Richard Smith1c931be2012-04-02 18:40:40 +00009551 // [Checked after we build the declaration]
9552 // - the move assignment operator would not be implicitly defined as
9553 // deleted,
9554
9555 // [DR1402]:
9556 // - X has no direct or indirect virtual base class with a non-trivial
9557 // move assignment operator, and
9558 // - each of X's non-static data members and direct or virtual base classes
9559 // has a type that either has a move assignment operator or is trivially
9560 // copyable.
9561 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9562 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9563 ClassDecl->setFailedImplicitMoveAssignment();
9564 return 0;
9565 }
9566
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009567 // Note: The following rules are largely analoguous to the move
9568 // constructor rules.
9569
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009570 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9571 QualType RetType = Context.getLValueReferenceType(ArgType);
9572 ArgType = Context.getRValueReferenceType(ArgType);
9573
Richard Smitha8942d72013-05-07 03:19:20 +00009574 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9575 CXXMoveAssignment,
9576 false);
9577
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009578 // An implicitly-declared move assignment operator is an inline public
9579 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009580 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9581 SourceLocation ClassLoc = ClassDecl->getLocation();
9582 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009583 CXXMethodDecl *MoveAssignment =
9584 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9585 /*TInfo=*/0, /*StorageClass=*/SC_None,
9586 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009587 MoveAssignment->setAccess(AS_public);
9588 MoveAssignment->setDefaulted();
9589 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009590
Richard Smithb9d0b762012-07-27 04:22:15 +00009591 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009592 FunctionProtoType::ExtProtoInfo EPI =
9593 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009594 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009595
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009596 // Add the parameter to the operator.
9597 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9598 ClassLoc, ClassLoc, /*Id=*/0,
9599 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009600 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009601 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009602
Richard Smithbc2a35d2012-12-08 08:32:28 +00009603 AddOverriddenMethods(ClassDecl, MoveAssignment);
9604
9605 MoveAssignment->setTrivial(
9606 ClassDecl->needsOverloadResolutionForMoveAssignment()
9607 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9608 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009609
9610 // C++0x [class.copy]p9:
9611 // If the definition of a class X does not explicitly declare a move
9612 // assignment operator, one will be implicitly declared as defaulted if and
9613 // only if:
9614 // [...]
9615 // - the move assignment operator would not be implicitly defined as
9616 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009617 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009618 // Cache this result so that we don't try to generate this over and over
9619 // on every lookup, leaking memory and wasting time.
9620 ClassDecl->setFailedImplicitMoveAssignment();
9621 return 0;
9622 }
9623
Richard Smithbc2a35d2012-12-08 08:32:28 +00009624 // Note that we have added this copy-assignment operator.
9625 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9626
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009627 if (Scope *S = getScopeForContext(ClassDecl))
9628 PushOnScopeChains(MoveAssignment, S, false);
9629 ClassDecl->addDecl(MoveAssignment);
9630
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009631 return MoveAssignment;
9632}
9633
9634void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9635 CXXMethodDecl *MoveAssignOperator) {
9636 assert((MoveAssignOperator->isDefaulted() &&
9637 MoveAssignOperator->isOverloadedOperator() &&
9638 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009639 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9640 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009641 "DefineImplicitMoveAssignment called for wrong function");
9642
9643 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9644
9645 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9646 MoveAssignOperator->setInvalidDecl();
9647 return;
9648 }
9649
Eli Friedman86164e82013-09-05 00:02:25 +00009650 MoveAssignOperator->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009651
Eli Friedman9a14db32012-10-18 20:14:08 +00009652 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009653 DiagnosticErrorTrap Trap(Diags);
9654
9655 // C++0x [class.copy]p28:
9656 // The implicitly-defined or move assignment operator for a non-union class
9657 // X performs memberwise move assignment of its subobjects. The direct base
9658 // classes of X are assigned first, in the order of their declaration in the
9659 // base-specifier-list, and then the immediate non-static data members of X
9660 // are assigned, in the order in which they were declared in the class
9661 // definition.
9662
9663 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009664 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009665
9666 // The parameter for the "other" object, which we are move from.
9667 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9668 QualType OtherRefType = Other->getType()->
9669 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009670 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009671 "Bad argument type of defaulted move assignment");
9672
9673 // Our location for everything implicitly-generated.
9674 SourceLocation Loc = MoveAssignOperator->getLocation();
9675
Pavel Labath66ea35d2013-08-30 08:52:28 +00009676 // Builds a reference to the "other" object.
9677 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009678 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009679 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009680
Pavel Labath66ea35d2013-08-30 08:52:28 +00009681 // Builds the "this" pointer.
9682 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +00009683
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009684 // Assign base classes.
9685 bool Invalid = false;
9686 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9687 E = ClassDecl->bases_end(); Base != E; ++Base) {
9688 // Form the assignment:
9689 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9690 QualType BaseType = Base->getType().getUnqualifiedType();
9691 if (!BaseType->isRecordType()) {
9692 Invalid = true;
9693 continue;
9694 }
9695
9696 CXXCastPath BasePath;
9697 BasePath.push_back(Base);
9698
9699 // Construct the "from" expression, which is an implicit cast to the
9700 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009701 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009702
9703 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009704 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009705
9706 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009707 CastBuilder To(DerefThis,
9708 Context.getCVRQualifiedType(
9709 BaseType, MoveAssignOperator->getTypeQualifiers()),
9710 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009711
9712 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009713 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009714 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009715 /*CopyingBaseSubobject=*/true,
9716 /*Copying=*/false);
9717 if (Move.isInvalid()) {
9718 Diag(CurrentLocation, diag::note_member_synthesized_at)
9719 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9720 MoveAssignOperator->setInvalidDecl();
9721 return;
9722 }
9723
9724 // Success! Record the move.
9725 Statements.push_back(Move.takeAs<Expr>());
9726 }
9727
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009728 // Assign non-static members.
9729 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9730 FieldEnd = ClassDecl->field_end();
9731 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009732 if (Field->isUnnamedBitfield())
9733 continue;
9734
Eli Friedman8150da32013-06-07 01:48:56 +00009735 if (Field->isInvalidDecl()) {
9736 Invalid = true;
9737 continue;
9738 }
9739
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009740 // Check for members of reference type; we can't move those.
9741 if (Field->getType()->isReferenceType()) {
9742 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9743 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9744 Diag(Field->getLocation(), diag::note_declared_at);
9745 Diag(CurrentLocation, diag::note_member_synthesized_at)
9746 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9747 Invalid = true;
9748 continue;
9749 }
9750
9751 // Check for members of const-qualified, non-class type.
9752 QualType BaseType = Context.getBaseElementType(Field->getType());
9753 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9754 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9755 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9756 Diag(Field->getLocation(), diag::note_declared_at);
9757 Diag(CurrentLocation, diag::note_member_synthesized_at)
9758 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9759 Invalid = true;
9760 continue;
9761 }
9762
9763 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009764 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9765 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009766
9767 QualType FieldType = Field->getType().getNonReferenceType();
9768 if (FieldType->isIncompleteArrayType()) {
9769 assert(ClassDecl->hasFlexibleArrayMember() &&
9770 "Incomplete array type is not valid");
9771 continue;
9772 }
9773
9774 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009775 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9776 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009777 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009778 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009779 MemberBuilder From(MoveOther, OtherRefType,
9780 /*IsArrow=*/false, MemberLookup);
9781 MemberBuilder To(This, getCurrentThisType(),
9782 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009783
Pavel Labath66ea35d2013-08-30 08:52:28 +00009784 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009785 "Member reference with rvalue base must be rvalue except for reference "
9786 "members, which aren't allowed for move assignment.");
9787
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009788 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009789 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009790 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009791 /*CopyingBaseSubobject=*/false,
9792 /*Copying=*/false);
9793 if (Move.isInvalid()) {
9794 Diag(CurrentLocation, diag::note_member_synthesized_at)
9795 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9796 MoveAssignOperator->setInvalidDecl();
9797 return;
9798 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009799
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009800 // Success! Record the copy.
9801 Statements.push_back(Move.takeAs<Stmt>());
9802 }
9803
9804 if (!Invalid) {
9805 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009806 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009807
9808 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9809 if (Return.isInvalid())
9810 Invalid = true;
9811 else {
9812 Statements.push_back(Return.takeAs<Stmt>());
9813
9814 if (Trap.hasErrorOccurred()) {
9815 Diag(CurrentLocation, diag::note_member_synthesized_at)
9816 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9817 Invalid = true;
9818 }
9819 }
9820 }
9821
9822 if (Invalid) {
9823 MoveAssignOperator->setInvalidDecl();
9824 return;
9825 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009826
9827 StmtResult Body;
9828 {
9829 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009830 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009831 /*isStmtExpr=*/false);
9832 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9833 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009834 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9835
9836 if (ASTMutationListener *L = getASTMutationListener()) {
9837 L->CompletedImplicitDefinition(MoveAssignOperator);
9838 }
9839}
9840
Richard Smithb9d0b762012-07-27 04:22:15 +00009841Sema::ImplicitExceptionSpecification
9842Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9843 CXXRecordDecl *ClassDecl = MD->getParent();
9844
9845 ImplicitExceptionSpecification ExceptSpec(*this);
9846 if (ClassDecl->isInvalidDecl())
9847 return ExceptSpec;
9848
9849 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9850 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9851 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9852
Douglas Gregor0d405db2010-07-01 20:59:04 +00009853 // C++ [except.spec]p14:
9854 // An implicitly declared special member function (Clause 12) shall have an
9855 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009856 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9857 BaseEnd = ClassDecl->bases_end();
9858 Base != BaseEnd;
9859 ++Base) {
9860 // Virtual bases are handled below.
9861 if (Base->isVirtual())
9862 continue;
9863
Douglas Gregor22584312010-07-02 23:41:54 +00009864 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009865 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009866 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009867 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009868 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009869 }
9870 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9871 BaseEnd = ClassDecl->vbases_end();
9872 Base != BaseEnd;
9873 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009874 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009875 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009876 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009877 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009878 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009879 }
9880 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9881 FieldEnd = ClassDecl->field_end();
9882 Field != FieldEnd;
9883 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009884 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009885 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9886 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009887 LookupCopyingConstructor(FieldClassDecl,
9888 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009889 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009890 }
9891 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009892
Richard Smithb9d0b762012-07-27 04:22:15 +00009893 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009894}
9895
9896CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9897 CXXRecordDecl *ClassDecl) {
9898 // C++ [class.copy]p4:
9899 // If the class definition does not explicitly declare a copy
9900 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009901 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009902
Richard Smithafb49182012-11-29 01:34:07 +00009903 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9904 if (DSM.isAlreadyBeingDeclared())
9905 return 0;
9906
Sean Hunt49634cf2011-05-13 06:10:58 +00009907 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9908 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009909 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009910 if (Const)
9911 ArgType = ArgType.withConst();
9912 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009913
Richard Smith7756afa2012-06-10 05:43:50 +00009914 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9915 CXXCopyConstructor,
9916 Const);
9917
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009918 DeclarationName Name
9919 = Context.DeclarationNames.getCXXConstructorName(
9920 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009921 SourceLocation ClassLoc = ClassDecl->getLocation();
9922 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009923
9924 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009925 // member of its class.
9926 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009927 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009928 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009929 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009930 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009931 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009932
Richard Smithb9d0b762012-07-27 04:22:15 +00009933 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009934 FunctionProtoType::ExtProtoInfo EPI =
9935 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +00009936 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009937 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009938
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009939 // Add the parameter to the constructor.
9940 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009941 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009942 /*IdentifierInfo=*/0,
9943 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009944 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009945 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009946
Richard Smithbc2a35d2012-12-08 08:32:28 +00009947 CopyConstructor->setTrivial(
9948 ClassDecl->needsOverloadResolutionForCopyConstructor()
9949 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9950 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009951
Nico Weberafcc96a2012-01-23 03:19:29 +00009952 // C++11 [class.copy]p8:
9953 // ... If the class definition does not explicitly declare a copy
9954 // constructor, there is no user-declared move constructor, and there is no
9955 // user-declared move assignment operator, a copy constructor is implicitly
9956 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009957 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009958 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009959
Richard Smithbc2a35d2012-12-08 08:32:28 +00009960 // Note that we have declared this constructor.
9961 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9962
9963 if (Scope *S = getScopeForContext(ClassDecl))
9964 PushOnScopeChains(CopyConstructor, S, false);
9965 ClassDecl->addDecl(CopyConstructor);
9966
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009967 return CopyConstructor;
9968}
9969
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009970void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009971 CXXConstructorDecl *CopyConstructor) {
9972 assert((CopyConstructor->isDefaulted() &&
9973 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009974 !CopyConstructor->doesThisDeclarationHaveABody() &&
9975 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009976 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009977
Anders Carlsson63010a72010-04-23 16:24:12 +00009978 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009979 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009980
Richard Smith36155c12013-06-13 03:23:42 +00009981 // C++11 [class.copy]p7:
Benjamin Kramere5753592013-09-09 14:48:42 +00009982 // The [definition of an implicitly declared copy constructor] is
Richard Smith36155c12013-06-13 03:23:42 +00009983 // deprecated if the class has a user-declared copy assignment operator
9984 // or a user-declared destructor.
9985 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9986 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9987
Eli Friedman9a14db32012-10-18 20:14:08 +00009988 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009989 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009990
David Blaikie93c86172013-01-17 05:26:25 +00009991 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009992 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009993 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009994 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009995 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009996 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009997 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00009998 CopyConstructor->setBody(ActOnCompoundStmt(
9999 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10000 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +000010001 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010002
Eli Friedman86164e82013-09-05 00:02:25 +000010003 CopyConstructor->markUsed(Context);
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010004 if (ASTMutationListener *L = getASTMutationListener()) {
10005 L->CompletedImplicitDefinition(CopyConstructor);
10006 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010007}
10008
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010009Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010010Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10011 CXXRecordDecl *ClassDecl = MD->getParent();
10012
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010013 // C++ [except.spec]p14:
10014 // An implicitly declared special member function (Clause 12) shall have an
10015 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +000010016 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010017 if (ClassDecl->isInvalidDecl())
10018 return ExceptSpec;
10019
10020 // Direct base-class constructors.
10021 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10022 BEnd = ClassDecl->bases_end();
10023 B != BEnd; ++B) {
10024 if (B->isVirtual()) // Handled below.
10025 continue;
10026
10027 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10028 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010029 CXXConstructorDecl *Constructor =
10030 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010031 // If this is a deleted function, add it anyway. This might be conformant
10032 // with the standard. This might not. I'm not sure. It might not matter.
10033 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010034 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010035 }
10036 }
10037
10038 // Virtual base-class constructors.
10039 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10040 BEnd = ClassDecl->vbases_end();
10041 B != BEnd; ++B) {
10042 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10043 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010044 CXXConstructorDecl *Constructor =
10045 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010046 // If this is a deleted function, add it anyway. This might be conformant
10047 // with the standard. This might not. I'm not sure. It might not matter.
10048 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010049 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010050 }
10051 }
10052
10053 // Field constructors.
10054 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10055 FEnd = ClassDecl->field_end();
10056 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010057 QualType FieldType = Context.getBaseElementType(F->getType());
10058 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10059 CXXConstructorDecl *Constructor =
10060 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010061 // If this is a deleted function, add it anyway. This might be conformant
10062 // with the standard. This might not. I'm not sure. It might not matter.
10063 // In particular, the problem is that this function never gets called. It
10064 // might just be ill-formed because this function attempts to refer to
10065 // a deleted function here.
10066 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010067 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010068 }
10069 }
10070
10071 return ExceptSpec;
10072}
10073
10074CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10075 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010076 // C++11 [class.copy]p9:
10077 // If the definition of a class X does not explicitly declare a move
10078 // constructor, one will be implicitly declared as defaulted if and only if:
10079 //
10080 // - [first 4 bullets]
10081 assert(ClassDecl->needsImplicitMoveConstructor());
10082
Richard Smithafb49182012-11-29 01:34:07 +000010083 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10084 if (DSM.isAlreadyBeingDeclared())
10085 return 0;
10086
Richard Smith1c931be2012-04-02 18:40:40 +000010087 // [Checked after we build the declaration]
10088 // - the move assignment operator would not be implicitly defined as
10089 // deleted,
10090
10091 // [DR1402]:
10092 // - each of X's non-static data members and direct or virtual base classes
10093 // has a type that either has a move constructor or is trivially copyable.
10094 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
10095 ClassDecl->setFailedImplicitMoveConstructor();
10096 return 0;
10097 }
10098
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010099 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10100 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010101
Richard Smith7756afa2012-06-10 05:43:50 +000010102 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10103 CXXMoveConstructor,
10104 false);
10105
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010106 DeclarationName Name
10107 = Context.DeclarationNames.getCXXConstructorName(
10108 Context.getCanonicalType(ClassType));
10109 SourceLocation ClassLoc = ClassDecl->getLocation();
10110 DeclarationNameInfo NameInfo(Name, ClassLoc);
10111
Richard Smitha8942d72013-05-07 03:19:20 +000010112 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010113 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010114 // member of its class.
10115 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010116 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010117 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010118 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010119 MoveConstructor->setAccess(AS_public);
10120 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010121
Richard Smithb9d0b762012-07-27 04:22:15 +000010122 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010123 FunctionProtoType::ExtProtoInfo EPI =
10124 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010125 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010126 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010127
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010128 // Add the parameter to the constructor.
10129 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10130 ClassLoc, ClassLoc,
10131 /*IdentifierInfo=*/0,
10132 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010133 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010134 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010135
Richard Smithbc2a35d2012-12-08 08:32:28 +000010136 MoveConstructor->setTrivial(
10137 ClassDecl->needsOverloadResolutionForMoveConstructor()
10138 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10139 : ClassDecl->hasTrivialMoveConstructor());
10140
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010141 // C++0x [class.copy]p9:
10142 // If the definition of a class X does not explicitly declare a move
10143 // constructor, one will be implicitly declared as defaulted if and only if:
10144 // [...]
10145 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +000010146 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010147 // Cache this result so that we don't try to generate this over and over
10148 // on every lookup, leaking memory and wasting time.
10149 ClassDecl->setFailedImplicitMoveConstructor();
10150 return 0;
10151 }
10152
10153 // Note that we have declared this constructor.
10154 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10155
10156 if (Scope *S = getScopeForContext(ClassDecl))
10157 PushOnScopeChains(MoveConstructor, S, false);
10158 ClassDecl->addDecl(MoveConstructor);
10159
10160 return MoveConstructor;
10161}
10162
10163void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10164 CXXConstructorDecl *MoveConstructor) {
10165 assert((MoveConstructor->isDefaulted() &&
10166 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010167 !MoveConstructor->doesThisDeclarationHaveABody() &&
10168 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010169 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10170
10171 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10172 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10173
Eli Friedman9a14db32012-10-18 20:14:08 +000010174 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010175 DiagnosticErrorTrap Trap(Diags);
10176
David Blaikie93c86172013-01-17 05:26:25 +000010177 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010178 Trap.hasErrorOccurred()) {
10179 Diag(CurrentLocation, diag::note_member_synthesized_at)
10180 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10181 MoveConstructor->setInvalidDecl();
10182 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010183 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010184 MoveConstructor->setBody(ActOnCompoundStmt(
10185 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10186 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010187 }
10188
Eli Friedman86164e82013-09-05 00:02:25 +000010189 MoveConstructor->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010190
10191 if (ASTMutationListener *L = getASTMutationListener()) {
10192 L->CompletedImplicitDefinition(MoveConstructor);
10193 }
10194}
10195
Douglas Gregore4e68d42012-02-15 19:33:52 +000010196bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010197 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010198}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010199
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010200/// \brief Mark the call operator of the given lambda closure type as "used".
10201static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
10202 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +000010203 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +000010204 Lambda->lookup(
10205 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010206 CallOperator->setReferenced();
Eli Friedman86164e82013-09-05 00:02:25 +000010207 CallOperator->markUsed(S.Context);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010208}
10209
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010210void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10211 SourceLocation CurrentLocation,
10212 CXXConversionDecl *Conv)
10213{
Manuel Klimek152b4e42013-08-22 12:12:24 +000010214 CXXRecordDecl *Lambda = Conv->getParent();
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010215
10216 // Make sure that the lambda call operator is marked used.
Manuel Klimek152b4e42013-08-22 12:12:24 +000010217 markLambdaCallOperatorUsed(*this, Lambda);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010218
Eli Friedman86164e82013-09-05 00:02:25 +000010219 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010220
Eli Friedman9a14db32012-10-18 20:14:08 +000010221 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010222 DiagnosticErrorTrap Trap(Diags);
10223
Manuel Klimek152b4e42013-08-22 12:12:24 +000010224 // Return the address of the __invoke function.
10225 DeclarationName InvokeName = &Context.Idents.get("__invoke");
10226 CXXMethodDecl *Invoke
10227 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010228 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
10229 VK_LValue, Conv->getLocation()).take();
Manuel Klimek152b4e42013-08-22 12:12:24 +000010230 assert(FunctionRef && "Can't refer to __invoke function?");
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010231 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +000010232 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010233 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010234 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010235
Manuel Klimek152b4e42013-08-22 12:12:24 +000010236 // Fill in the __invoke function with a dummy implementation. IR generation
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010237 // will fill in the actual details.
Eli Friedman86164e82013-09-05 00:02:25 +000010238 Invoke->markUsed(Context);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010239 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +000010240 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010241
10242 if (ASTMutationListener *L = getASTMutationListener()) {
10243 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010244 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010245 }
10246}
10247
10248void Sema::DefineImplicitLambdaToBlockPointerConversion(
10249 SourceLocation CurrentLocation,
10250 CXXConversionDecl *Conv)
10251{
Eli Friedman86164e82013-09-05 00:02:25 +000010252 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010253
Eli Friedman9a14db32012-10-18 20:14:08 +000010254 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010255 DiagnosticErrorTrap Trap(Diags);
10256
Douglas Gregorac1303e2012-02-22 05:02:47 +000010257 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010258 Expr *This = ActOnCXXThis(CurrentLocation).take();
10259 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010260
Eli Friedman23f02672012-03-01 04:01:32 +000010261 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10262 Conv->getLocation(),
10263 Conv, DerefThis);
10264
10265 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10266 // behavior. Note that only the general conversion function does this
10267 // (since it's unusable otherwise); in the case where we inline the
10268 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010269 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010270 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10271 CK_CopyAndAutoreleaseBlockObject,
10272 BuildBlock.get(), 0, VK_RValue);
10273
10274 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010275 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010276 Conv->setInvalidDecl();
10277 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010278 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010279
Douglas Gregorac1303e2012-02-22 05:02:47 +000010280 // Create the return statement that returns the block from the conversion
10281 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010282 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010283 if (Return.isInvalid()) {
10284 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10285 Conv->setInvalidDecl();
10286 return;
10287 }
10288
10289 // Set the body of the conversion function.
10290 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010291 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010292 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010293 Conv->getLocation()));
10294
Douglas Gregorac1303e2012-02-22 05:02:47 +000010295 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010296 if (ASTMutationListener *L = getASTMutationListener()) {
10297 L->CompletedImplicitDefinition(Conv);
10298 }
10299}
10300
Douglas Gregorf52757d2012-03-10 06:53:13 +000010301/// \brief Determine whether the given list arguments contains exactly one
10302/// "real" (non-default) argument.
10303static bool hasOneRealArgument(MultiExprArg Args) {
10304 switch (Args.size()) {
10305 case 0:
10306 return false;
10307
10308 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010309 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010310 return false;
10311
10312 // fall through
10313 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010314 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010315 }
10316
10317 return false;
10318}
10319
John McCall60d7b3a2010-08-24 06:29:42 +000010320ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010321Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010322 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010323 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010324 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010325 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010326 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010327 unsigned ConstructKind,
10328 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010329 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010330
Douglas Gregor2f599792010-04-02 18:24:57 +000010331 // C++0x [class.copy]p34:
10332 // When certain criteria are met, an implementation is allowed to
10333 // omit the copy/move construction of a class object, even if the
10334 // copy/move constructor and/or destructor for the object have
10335 // side effects. [...]
10336 // - when a temporary class object that has not been bound to a
10337 // reference (12.2) would be copied/moved to a class object
10338 // with the same cv-unqualified type, the copy/move operation
10339 // can be omitted by constructing the temporary object
10340 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010341 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010342 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010343 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010344 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010345 }
Mike Stump1eb44332009-09-09 15:08:12 +000010346
10347 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010348 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010349 IsListInitialization, RequiresZeroInit,
10350 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010351}
10352
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010353/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10354/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010355ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010356Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10357 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010358 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010359 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010360 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010361 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010362 unsigned ConstructKind,
10363 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010364 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010365 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010366 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010367 HadMultipleCandidates,
10368 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010369 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10370 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010371}
10372
John McCall68c6c9a2010-02-02 09:10:11 +000010373void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010374 if (VD->isInvalidDecl()) return;
10375
John McCall68c6c9a2010-02-02 09:10:11 +000010376 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010377 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010378 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010379 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010380
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010381 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010382 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010383 CheckDestructorAccess(VD->getLocation(), Destructor,
10384 PDiag(diag::err_access_dtor_var)
10385 << VD->getDeclName()
10386 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010387 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010388
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010389 if (!VD->hasGlobalStorage()) return;
10390
10391 // Emit warning for non-trivial dtor in global scope (a real global,
10392 // class-static, function-static).
10393 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10394
10395 // TODO: this should be re-enabled for static locals by !CXAAtExit
10396 if (!VD->isStaticLocal())
10397 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010398}
10399
Douglas Gregor39da0b82009-09-09 23:08:42 +000010400/// \brief Given a constructor and the set of arguments provided for the
10401/// constructor, convert the arguments and add any required default arguments
10402/// to form a proper call to this constructor.
10403///
10404/// \returns true if an error occurred, false otherwise.
10405bool
10406Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10407 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010408 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010409 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010410 bool AllowExplicit,
10411 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010412 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10413 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010414 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010415
10416 const FunctionProtoType *Proto
10417 = Constructor->getType()->getAs<FunctionProtoType>();
10418 assert(Proto && "Constructor without a prototype?");
10419 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010420
10421 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010422 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010423 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010424 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010425 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010426
10427 VariadicCallType CallType =
10428 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010429 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010430 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010431 Proto, 0,
10432 llvm::makeArrayRef(Args, NumArgs),
10433 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010434 CallType, AllowExplicit,
10435 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010436 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010437
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010438 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010439
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010440 CheckConstructorCall(Constructor,
10441 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10442 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010443 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010444
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010445 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010446}
10447
Anders Carlsson20d45d22009-12-12 00:32:00 +000010448static inline bool
10449CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10450 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010451 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010452 if (isa<NamespaceDecl>(DC)) {
10453 return SemaRef.Diag(FnDecl->getLocation(),
10454 diag::err_operator_new_delete_declared_in_namespace)
10455 << FnDecl->getDeclName();
10456 }
10457
10458 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010459 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010460 return SemaRef.Diag(FnDecl->getLocation(),
10461 diag::err_operator_new_delete_declared_static)
10462 << FnDecl->getDeclName();
10463 }
10464
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010465 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010466}
10467
Anders Carlsson156c78e2009-12-13 17:53:43 +000010468static inline bool
10469CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10470 CanQualType ExpectedResultType,
10471 CanQualType ExpectedFirstParamType,
10472 unsigned DependentParamTypeDiag,
10473 unsigned InvalidParamTypeDiag) {
10474 QualType ResultType =
10475 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10476
10477 // Check that the result type is not dependent.
10478 if (ResultType->isDependentType())
10479 return SemaRef.Diag(FnDecl->getLocation(),
10480 diag::err_operator_new_delete_dependent_result_type)
10481 << FnDecl->getDeclName() << ExpectedResultType;
10482
10483 // Check that the result type is what we expect.
10484 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10485 return SemaRef.Diag(FnDecl->getLocation(),
10486 diag::err_operator_new_delete_invalid_result_type)
10487 << FnDecl->getDeclName() << ExpectedResultType;
10488
10489 // A function template must have at least 2 parameters.
10490 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10491 return SemaRef.Diag(FnDecl->getLocation(),
10492 diag::err_operator_new_delete_template_too_few_parameters)
10493 << FnDecl->getDeclName();
10494
10495 // The function decl must have at least 1 parameter.
10496 if (FnDecl->getNumParams() == 0)
10497 return SemaRef.Diag(FnDecl->getLocation(),
10498 diag::err_operator_new_delete_too_few_parameters)
10499 << FnDecl->getDeclName();
10500
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010501 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010502 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10503 if (FirstParamType->isDependentType())
10504 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10505 << FnDecl->getDeclName() << ExpectedFirstParamType;
10506
10507 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010508 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010509 ExpectedFirstParamType)
10510 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10511 << FnDecl->getDeclName() << ExpectedFirstParamType;
10512
10513 return false;
10514}
10515
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010516static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010517CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010518 // C++ [basic.stc.dynamic.allocation]p1:
10519 // A program is ill-formed if an allocation function is declared in a
10520 // namespace scope other than global scope or declared static in global
10521 // scope.
10522 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10523 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010524
10525 CanQualType SizeTy =
10526 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10527
10528 // C++ [basic.stc.dynamic.allocation]p1:
10529 // The return type shall be void*. The first parameter shall have type
10530 // std::size_t.
10531 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10532 SizeTy,
10533 diag::err_operator_new_dependent_param_type,
10534 diag::err_operator_new_param_type))
10535 return true;
10536
10537 // C++ [basic.stc.dynamic.allocation]p1:
10538 // The first parameter shall not have an associated default argument.
10539 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010540 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010541 diag::err_operator_new_default_arg)
10542 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10543
10544 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010545}
10546
10547static bool
Richard Smith444d3842012-10-20 08:26:51 +000010548CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010549 // C++ [basic.stc.dynamic.deallocation]p1:
10550 // A program is ill-formed if deallocation functions are declared in a
10551 // namespace scope other than global scope or declared static in global
10552 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010553 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10554 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010555
10556 // C++ [basic.stc.dynamic.deallocation]p2:
10557 // Each deallocation function shall return void and its first parameter
10558 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010559 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10560 SemaRef.Context.VoidPtrTy,
10561 diag::err_operator_delete_dependent_param_type,
10562 diag::err_operator_delete_param_type))
10563 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010564
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010565 return false;
10566}
10567
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010568/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10569/// of this overloaded operator is well-formed. If so, returns false;
10570/// otherwise, emits appropriate diagnostics and returns true.
10571bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010572 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010573 "Expected an overloaded operator declaration");
10574
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010575 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10576
Mike Stump1eb44332009-09-09 15:08:12 +000010577 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010578 // The allocation and deallocation functions, operator new,
10579 // operator new[], operator delete and operator delete[], are
10580 // described completely in 3.7.3. The attributes and restrictions
10581 // found in the rest of this subclause do not apply to them unless
10582 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010583 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010584 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010585
Anders Carlssona3ccda52009-12-12 00:26:23 +000010586 if (Op == OO_New || Op == OO_Array_New)
10587 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010588
10589 // C++ [over.oper]p6:
10590 // An operator function shall either be a non-static member
10591 // function or be a non-member function and have at least one
10592 // parameter whose type is a class, a reference to a class, an
10593 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010594 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10595 if (MethodDecl->isStatic())
10596 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010597 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010598 } else {
10599 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010600 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10601 ParamEnd = FnDecl->param_end();
10602 Param != ParamEnd; ++Param) {
10603 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010604 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10605 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010606 ClassOrEnumParam = true;
10607 break;
10608 }
10609 }
10610
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010611 if (!ClassOrEnumParam)
10612 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010613 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010614 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010615 }
10616
10617 // C++ [over.oper]p8:
10618 // An operator function cannot have default arguments (8.3.6),
10619 // except where explicitly stated below.
10620 //
Mike Stump1eb44332009-09-09 15:08:12 +000010621 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010622 // (C++ [over.call]p1).
10623 if (Op != OO_Call) {
10624 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10625 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010626 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010627 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010628 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010629 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010630 }
10631 }
10632
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010633 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10634 { false, false, false }
10635#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10636 , { Unary, Binary, MemberOnly }
10637#include "clang/Basic/OperatorKinds.def"
10638 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010639
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010640 bool CanBeUnaryOperator = OperatorUses[Op][0];
10641 bool CanBeBinaryOperator = OperatorUses[Op][1];
10642 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010643
10644 // C++ [over.oper]p8:
10645 // [...] Operator functions cannot have more or fewer parameters
10646 // than the number required for the corresponding operator, as
10647 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010648 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010649 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010650 if (Op != OO_Call &&
10651 ((NumParams == 1 && !CanBeUnaryOperator) ||
10652 (NumParams == 2 && !CanBeBinaryOperator) ||
10653 (NumParams < 1) || (NumParams > 2))) {
10654 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010655 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010656 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010657 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010658 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010659 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010660 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010661 assert(CanBeBinaryOperator &&
10662 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010663 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010664 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010665
Chris Lattner416e46f2008-11-21 07:57:12 +000010666 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010667 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010668 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010669
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010670 // Overloaded operators other than operator() cannot be variadic.
10671 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010672 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010673 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010674 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010675 }
10676
10677 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010678 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10679 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010680 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010681 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010682 }
10683
10684 // C++ [over.inc]p1:
10685 // The user-defined function called operator++ implements the
10686 // prefix and postfix ++ operator. If this function is a member
10687 // function with no parameters, or a non-member function with one
10688 // parameter of class or enumeration type, it defines the prefix
10689 // increment operator ++ for objects of that type. If the function
10690 // is a member function with one parameter (which shall be of type
10691 // int) or a non-member function with two parameters (the second
10692 // of which shall be of type int), it defines the postfix
10693 // increment operator ++ for objects of that type.
10694 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10695 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10696 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010697 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010698 ParamIsInt = BT->getKind() == BuiltinType::Int;
10699
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010700 if (!ParamIsInt)
10701 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010702 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010703 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010704 }
10705
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010706 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010707}
Chris Lattner5a003a42008-12-17 07:09:26 +000010708
Sean Hunta6c058d2010-01-13 09:01:02 +000010709/// CheckLiteralOperatorDeclaration - Check whether the declaration
10710/// of this literal operator function is well-formed. If so, returns
10711/// false; otherwise, emits appropriate diagnostics and returns true.
10712bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010713 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010714 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10715 << FnDecl->getDeclName();
10716 return true;
10717 }
10718
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010719 if (FnDecl->isExternC()) {
10720 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10721 return true;
10722 }
10723
Sean Hunta6c058d2010-01-13 09:01:02 +000010724 bool Valid = false;
10725
Richard Smith36f5cfe2012-03-09 08:00:36 +000010726 // This might be the definition of a literal operator template.
10727 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10728 // This might be a specialization of a literal operator template.
10729 if (!TpDecl)
10730 TpDecl = FnDecl->getPrimaryTemplate();
10731
Sean Hunt216c2782010-04-07 23:11:06 +000010732 // template <char...> type operator "" name() is the only valid template
10733 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010734 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010735 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010736 // Must have only one template parameter
10737 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10738 if (Params->size() == 1) {
10739 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010740 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010741
Sean Hunt216c2782010-04-07 23:11:06 +000010742 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010743 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10744 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10745 Valid = true;
10746 }
10747 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010748 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010749 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010750 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10751
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010752 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010753
Sean Hunt30019c02010-04-07 22:57:35 +000010754 // unsigned long long int, long double, and any character type are allowed
10755 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010756 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10757 Context.hasSameType(T, Context.LongDoubleTy) ||
10758 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010759 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010760 Context.hasSameType(T, Context.Char16Ty) ||
10761 Context.hasSameType(T, Context.Char32Ty)) {
10762 if (++Param == FnDecl->param_end())
10763 Valid = true;
10764 goto FinishedParams;
10765 }
10766
Sean Hunt30019c02010-04-07 22:57:35 +000010767 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010768 const PointerType *PT = T->getAs<PointerType>();
10769 if (!PT)
10770 goto FinishedParams;
10771 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010772 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010773 goto FinishedParams;
10774 T = T.getUnqualifiedType();
10775
10776 // Move on to the second parameter;
10777 ++Param;
10778
10779 // If there is no second parameter, the first must be a const char *
10780 if (Param == FnDecl->param_end()) {
10781 if (Context.hasSameType(T, Context.CharTy))
10782 Valid = true;
10783 goto FinishedParams;
10784 }
10785
10786 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10787 // are allowed as the first parameter to a two-parameter function
10788 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010789 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010790 Context.hasSameType(T, Context.Char16Ty) ||
10791 Context.hasSameType(T, Context.Char32Ty)))
10792 goto FinishedParams;
10793
10794 // The second and final parameter must be an std::size_t
10795 T = (*Param)->getType().getUnqualifiedType();
10796 if (Context.hasSameType(T, Context.getSizeType()) &&
10797 ++Param == FnDecl->param_end())
10798 Valid = true;
10799 }
10800
10801 // FIXME: This diagnostic is absolutely terrible.
10802FinishedParams:
10803 if (!Valid) {
10804 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10805 << FnDecl->getDeclName();
10806 return true;
10807 }
10808
Richard Smitha9e88b22012-03-09 08:16:22 +000010809 // A parameter-declaration-clause containing a default argument is not
10810 // equivalent to any of the permitted forms.
10811 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10812 ParamEnd = FnDecl->param_end();
10813 Param != ParamEnd; ++Param) {
10814 if ((*Param)->hasDefaultArg()) {
10815 Diag((*Param)->getDefaultArgRange().getBegin(),
10816 diag::err_literal_operator_default_argument)
10817 << (*Param)->getDefaultArgRange();
10818 break;
10819 }
10820 }
10821
Richard Smith2fb4ae32012-03-08 02:39:21 +000010822 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010823 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10824 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010825 // C++11 [usrlit.suffix]p1:
10826 // Literal suffix identifiers that do not start with an underscore
10827 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000010828 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10829 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000010830 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010831
Sean Hunta6c058d2010-01-13 09:01:02 +000010832 return false;
10833}
10834
Douglas Gregor074149e2009-01-05 19:45:36 +000010835/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10836/// linkage specification, including the language and (if present)
10837/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10838/// the location of the language string literal, which is provided
10839/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10840/// the '{' brace. Otherwise, this linkage specification does not
10841/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010842Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10843 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010844 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010845 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010846 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010847 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010848 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010849 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010850 Language = LinkageSpecDecl::lang_cxx;
10851 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010852 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010853 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010854 }
Mike Stump1eb44332009-09-09 15:08:12 +000010855
Chris Lattnercc98eac2008-12-17 07:13:27 +000010856 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010857
Douglas Gregor074149e2009-01-05 19:45:36 +000010858 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010859 ExternLoc, LangLoc, Language,
10860 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010861 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010862 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010863 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010864}
10865
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010866/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010867/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10868/// valid, it's the position of the closing '}' brace in a linkage
10869/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010870Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010871 Decl *LinkageSpec,
10872 SourceLocation RBraceLoc) {
10873 if (LinkageSpec) {
10874 if (RBraceLoc.isValid()) {
10875 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10876 LSDecl->setRBraceLoc(RBraceLoc);
10877 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010878 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010879 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010880 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010881}
10882
Michael Han684aa732013-02-22 17:15:32 +000010883Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10884 AttributeList *AttrList,
10885 SourceLocation SemiLoc) {
10886 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10887 // Attribute declarations appertain to empty declaration so we handle
10888 // them here.
10889 if (AttrList)
10890 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010891
Michael Han684aa732013-02-22 17:15:32 +000010892 CurContext->addDecl(ED);
10893 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010894}
10895
Douglas Gregord308e622009-05-18 20:51:54 +000010896/// \brief Perform semantic analysis for the variable declaration that
10897/// occurs within a C++ catch clause, returning the newly-created
10898/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010899VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010900 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010901 SourceLocation StartLoc,
10902 SourceLocation Loc,
10903 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010904 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010905 QualType ExDeclType = TInfo->getType();
10906
Sebastian Redl4b07b292008-12-22 19:15:10 +000010907 // Arrays and functions decay.
10908 if (ExDeclType->isArrayType())
10909 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10910 else if (ExDeclType->isFunctionType())
10911 ExDeclType = Context.getPointerType(ExDeclType);
10912
10913 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10914 // The exception-declaration shall not denote a pointer or reference to an
10915 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010916 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010917 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010918 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010919 Invalid = true;
10920 }
Douglas Gregord308e622009-05-18 20:51:54 +000010921
Sebastian Redl4b07b292008-12-22 19:15:10 +000010922 QualType BaseType = ExDeclType;
10923 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010924 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010925 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010926 BaseType = Ptr->getPointeeType();
10927 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010928 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010929 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010930 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010931 BaseType = Ref->getPointeeType();
10932 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010933 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010934 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010935 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010936 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010937 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010938
Mike Stump1eb44332009-09-09 15:08:12 +000010939 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010940 RequireNonAbstractType(Loc, ExDeclType,
10941 diag::err_abstract_type_in_decl,
10942 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010943 Invalid = true;
10944
John McCall5a180392010-07-24 00:37:23 +000010945 // Only the non-fragile NeXT runtime currently supports C++ catches
10946 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010947 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010948 QualType T = ExDeclType;
10949 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10950 T = RT->getPointeeType();
10951
10952 if (T->isObjCObjectType()) {
10953 Diag(Loc, diag::err_objc_object_catch);
10954 Invalid = true;
10955 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010956 // FIXME: should this be a test for macosx-fragile specifically?
10957 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010958 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010959 }
10960 }
10961
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010962 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010963 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010964 ExDecl->setExceptionVariable(true);
10965
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010966 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010967 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010968 Invalid = true;
10969
Douglas Gregorc41b8782011-07-06 18:14:43 +000010970 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010971 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010972 // Insulate this from anything else we might currently be parsing.
10973 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10974
Douglas Gregor6d182892010-03-05 23:38:39 +000010975 // C++ [except.handle]p16:
10976 // The object declared in an exception-declaration or, if the
10977 // exception-declaration does not specify a name, a temporary (12.2) is
10978 // copy-initialized (8.5) from the exception object. [...]
10979 // The object is destroyed when the handler exits, after the destruction
10980 // of any automatic objects initialized within the handler.
10981 //
10982 // We just pretend to initialize the object with itself, then make sure
10983 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010984 QualType initType = ExDeclType;
10985
10986 InitializedEntity entity =
10987 InitializedEntity::InitializeVariable(ExDecl);
10988 InitializationKind initKind =
10989 InitializationKind::CreateCopy(Loc, SourceLocation());
10990
10991 Expr *opaqueValue =
10992 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010993 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10994 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010995 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010996 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010997 else {
10998 // If the constructor used was non-trivial, set this as the
10999 // "initializer".
11000 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
11001 if (!construct->getConstructor()->isTrivial()) {
11002 Expr *init = MaybeCreateExprWithCleanups(construct);
11003 ExDecl->setInit(init);
11004 }
11005
11006 // And make sure it's destructable.
11007 FinalizeVarWithDestructor(ExDecl, recordType);
11008 }
Douglas Gregor6d182892010-03-05 23:38:39 +000011009 }
11010 }
11011
Douglas Gregord308e622009-05-18 20:51:54 +000011012 if (Invalid)
11013 ExDecl->setInvalidDecl();
11014
11015 return ExDecl;
11016}
11017
11018/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11019/// handler.
John McCalld226f652010-08-21 09:40:31 +000011020Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000011021 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000011022 bool Invalid = D.isInvalidType();
11023
11024 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000011025 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11026 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000011027 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11028 D.getIdentifierLoc());
11029 Invalid = true;
11030 }
11031
Sebastian Redl4b07b292008-12-22 19:15:10 +000011032 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000011033 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000011034 LookupOrdinaryName,
11035 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011036 // The scope should be freshly made just for us. There is just no way
11037 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000011038 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000011039 if (PrevDecl->isTemplateParameter()) {
11040 // Maybe we will complain about the shadowed template parameter.
11041 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000011042 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011043 }
11044 }
11045
Chris Lattnereaaebc72009-04-25 08:06:05 +000011046 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011047 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11048 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000011049 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011050 }
11051
Douglas Gregor83cb9422010-09-09 17:09:21 +000011052 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000011053 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011054 D.getIdentifierLoc(),
11055 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000011056 if (Invalid)
11057 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000011058
Sebastian Redl4b07b292008-12-22 19:15:10 +000011059 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011060 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000011061 PushOnScopeChains(ExDecl, S);
11062 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011063 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000011064
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011065 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000011066 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011067}
Anders Carlssonfb311762009-03-14 00:25:26 +000011068
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011069Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000011070 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000011071 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011072 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000011073 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000011074
Richard Smithe3f470a2012-07-11 22:37:56 +000011075 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11076 return 0;
11077
11078 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11079 AssertMessage, RParenLoc, false);
11080}
11081
11082Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11083 Expr *AssertExpr,
11084 StringLiteral *AssertMessage,
11085 SourceLocation RParenLoc,
11086 bool Failed) {
11087 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11088 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000011089 // In a static_assert-declaration, the constant-expression shall be a
11090 // constant expression that can be contextually converted to bool.
11091 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11092 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011093 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000011094
Richard Smithdaaefc52011-12-14 23:32:26 +000011095 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000011096 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011097 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000011098 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011099 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000011100
Richard Smithe3f470a2012-07-11 22:37:56 +000011101 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011102 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000011103 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000011104 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011105 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000011106 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000011107 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000011108 }
Anders Carlssonc3082412009-03-14 00:33:21 +000011109 }
Mike Stump1eb44332009-09-09 15:08:12 +000011110
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011111 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000011112 AssertExpr, AssertMessage, RParenLoc,
11113 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000011114
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011115 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000011116 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000011117}
Sebastian Redl50de12f2009-03-24 22:27:57 +000011118
Douglas Gregor1d869352010-04-07 16:53:43 +000011119/// \brief Perform semantic analysis of the given friend type declaration.
11120///
11121/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000011122FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000011123 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011124 TypeSourceInfo *TSInfo) {
11125 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11126
11127 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000011128 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000011129
Richard Smith6b130222011-10-18 21:39:00 +000011130 // C++03 [class.friend]p2:
11131 // An elaborated-type-specifier shall be used in a friend declaration
11132 // for a class.*
11133 //
11134 // * The class-key of the elaborated-type-specifier is required.
11135 if (!ActiveTemplateInstantiations.empty()) {
11136 // Do not complain about the form of friend template types during
11137 // template instantiation; we will already have complained when the
11138 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011139 } else {
11140 if (!T->isElaboratedTypeSpecifier()) {
11141 // If we evaluated the type to a record type, suggest putting
11142 // a tag in front.
11143 if (const RecordType *RT = T->getAs<RecordType>()) {
11144 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000011145
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011146 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000011147
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011148 Diag(TypeRange.getBegin(),
11149 getLangOpts().CPlusPlus11 ?
11150 diag::warn_cxx98_compat_unelaborated_friend_type :
11151 diag::ext_unelaborated_friend_type)
11152 << (unsigned) RD->getTagKind()
11153 << T
11154 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11155 InsertionText);
11156 } else {
11157 Diag(FriendLoc,
11158 getLangOpts().CPlusPlus11 ?
11159 diag::warn_cxx98_compat_nonclass_type_friend :
11160 diag::ext_nonclass_type_friend)
11161 << T
11162 << TypeRange;
11163 }
11164 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000011165 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000011166 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011167 diag::warn_cxx98_compat_enum_friend :
11168 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000011169 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000011170 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000011171 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011172
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011173 // C++11 [class.friend]p3:
11174 // A friend declaration that does not declare a function shall have one
11175 // of the following forms:
11176 // friend elaborated-type-specifier ;
11177 // friend simple-type-specifier ;
11178 // friend typename-specifier ;
11179 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11180 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11181 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011182
Douglas Gregor06245bf2010-04-07 17:57:12 +000011183 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011184 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011185 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011186 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011187}
11188
John McCall9a34edb2010-10-19 01:40:49 +000011189/// Handle a friend tag declaration where the scope specifier was
11190/// templated.
11191Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11192 unsigned TagSpec, SourceLocation TagLoc,
11193 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011194 IdentifierInfo *Name,
11195 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011196 AttributeList *Attr,
11197 MultiTemplateParamsArg TempParamLists) {
11198 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11199
11200 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011201 bool Invalid = false;
11202
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011203 if (TemplateParameterList *TemplateParams =
11204 MatchTemplateParametersToScopeSpecifier(
11205 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11206 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011207 if (TemplateParams->size() > 0) {
11208 // This is a declaration of a class template.
11209 if (Invalid)
11210 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011211
Eric Christopher4110e132011-07-21 05:34:24 +000011212 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11213 SS, Name, NameLoc, Attr,
11214 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011215 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011216 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011217 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011218 } else {
11219 // The "template<>" header is extraneous.
11220 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11221 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11222 isExplicitSpecialization = true;
11223 }
11224 }
11225
11226 if (Invalid) return 0;
11227
John McCall9a34edb2010-10-19 01:40:49 +000011228 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011229 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011230 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011231 isAllExplicitSpecializations = false;
11232 break;
11233 }
11234 }
11235
11236 // FIXME: don't ignore attributes.
11237
11238 // If it's explicit specializations all the way down, just forget
11239 // about the template header and build an appropriate non-templated
11240 // friend. TODO: for source fidelity, remember the headers.
11241 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011242 if (SS.isEmpty()) {
11243 bool Owned = false;
11244 bool IsDependent = false;
11245 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11246 Attr, AS_public,
11247 /*ModulePrivateLoc=*/SourceLocation(),
11248 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011249 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011250 /*ScopedEnumUsesClassTag=*/false,
11251 /*UnderlyingType=*/TypeResult());
11252 }
11253
Douglas Gregor2494dd02011-03-01 01:34:45 +000011254 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011255 ElaboratedTypeKeyword Keyword
11256 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011257 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011258 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011259 if (T.isNull())
11260 return 0;
11261
11262 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11263 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011264 DependentNameTypeLoc TL =
11265 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011266 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011267 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011268 TL.setNameLoc(NameLoc);
11269 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011270 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011271 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011272 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011273 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011274 }
11275
11276 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011277 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011278 Friend->setAccess(AS_public);
11279 CurContext->addDecl(Friend);
11280 return Friend;
11281 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011282
11283 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11284
11285
John McCall9a34edb2010-10-19 01:40:49 +000011286
11287 // Handle the case of a templated-scope friend class. e.g.
11288 // template <class T> class A<T>::B;
11289 // FIXME: we don't support these right now.
11290 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11291 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11292 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011293 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011294 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011295 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011296 TL.setNameLoc(NameLoc);
11297
11298 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011299 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011300 Friend->setAccess(AS_public);
11301 Friend->setUnsupportedFriend(true);
11302 CurContext->addDecl(Friend);
11303 return Friend;
11304}
11305
11306
John McCalldd4a3b02009-09-16 22:47:08 +000011307/// Handle a friend type declaration. This works in tandem with
11308/// ActOnTag.
11309///
11310/// Notes on friend class templates:
11311///
11312/// We generally treat friend class declarations as if they were
11313/// declaring a class. So, for example, the elaborated type specifier
11314/// in a friend declaration is required to obey the restrictions of a
11315/// class-head (i.e. no typedefs in the scope chain), template
11316/// parameters are required to match up with simple template-ids, &c.
11317/// However, unlike when declaring a template specialization, it's
11318/// okay to refer to a template specialization without an empty
11319/// template parameter declaration, e.g.
11320/// friend class A<T>::B<unsigned>;
11321/// We permit this as a special case; if there are any template
11322/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011323/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011324Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011325 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011326 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011327
11328 assert(DS.isFriendSpecified());
11329 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11330
John McCalldd4a3b02009-09-16 22:47:08 +000011331 // Try to convert the decl specifier to a type. This works for
11332 // friend templates because ActOnTag never produces a ClassTemplateDecl
11333 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011334 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011335 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11336 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011337 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011338 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011339
Douglas Gregor6ccab972010-12-16 01:14:37 +000011340 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11341 return 0;
11342
John McCalldd4a3b02009-09-16 22:47:08 +000011343 // This is definitely an error in C++98. It's probably meant to
11344 // be forbidden in C++0x, too, but the specification is just
11345 // poorly written.
11346 //
11347 // The problem is with declarations like the following:
11348 // template <T> friend A<T>::foo;
11349 // where deciding whether a class C is a friend or not now hinges
11350 // on whether there exists an instantiation of A that causes
11351 // 'foo' to equal C. There are restrictions on class-heads
11352 // (which we declare (by fiat) elaborated friend declarations to
11353 // be) that makes this tractable.
11354 //
11355 // FIXME: handle "template <> friend class A<T>;", which
11356 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011357 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011358 Diag(Loc, diag::err_tagless_friend_type_template)
11359 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011360 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011361 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011362
John McCall02cace72009-08-28 07:59:38 +000011363 // C++98 [class.friend]p1: A friend of a class is a function
11364 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011365 // This is fixed in DR77, which just barely didn't make the C++03
11366 // deadline. It's also a very silly restriction that seriously
11367 // affects inner classes and which nobody else seems to implement;
11368 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011369 //
11370 // But note that we could warn about it: it's always useless to
11371 // friend one of your own members (it's not, however, worthless to
11372 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011373
John McCalldd4a3b02009-09-16 22:47:08 +000011374 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011375 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011376 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011377 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011378 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011379 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011380 DS.getFriendSpecLoc());
11381 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011382 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011383
11384 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011385 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011386
John McCalldd4a3b02009-09-16 22:47:08 +000011387 D->setAccess(AS_public);
11388 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011389
John McCalld226f652010-08-21 09:40:31 +000011390 return D;
John McCall02cace72009-08-28 07:59:38 +000011391}
11392
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011393NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11394 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011395 const DeclSpec &DS = D.getDeclSpec();
11396
11397 assert(DS.isFriendSpecified());
11398 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11399
11400 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011401 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011402
11403 // C++ [class.friend]p1
11404 // A friend of a class is a function or class....
11405 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011406 // It *doesn't* see through dependent types, which is correct
11407 // according to [temp.arg.type]p3:
11408 // If a declaration acquires a function type through a
11409 // type dependent on a template-parameter and this causes
11410 // a declaration that does not use the syntactic form of a
11411 // function declarator to have a function type, the program
11412 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011413 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011414 Diag(Loc, diag::err_unexpected_friend);
11415
11416 // It might be worthwhile to try to recover by creating an
11417 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011418 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011419 }
11420
11421 // C++ [namespace.memdef]p3
11422 // - If a friend declaration in a non-local class first declares a
11423 // class or function, the friend class or function is a member
11424 // of the innermost enclosing namespace.
11425 // - The name of the friend is not found by simple name lookup
11426 // until a matching declaration is provided in that namespace
11427 // scope (either before or after the class declaration granting
11428 // friendship).
11429 // - If a friend function is called, its name may be found by the
11430 // name lookup that considers functions from namespaces and
11431 // classes associated with the types of the function arguments.
11432 // - When looking for a prior declaration of a class or a function
11433 // declared as a friend, scopes outside the innermost enclosing
11434 // namespace scope are not considered.
11435
John McCall337ec3d2010-10-12 23:13:28 +000011436 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011437 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11438 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011439 assert(Name);
11440
Douglas Gregor6ccab972010-12-16 01:14:37 +000011441 // Check for unexpanded parameter packs.
11442 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11443 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11444 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11445 return 0;
11446
John McCall67d1a672009-08-06 02:15:43 +000011447 // The context we found the declaration in, or in which we should
11448 // create the declaration.
11449 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011450 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011451 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011452 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011453
Richard Smith4e9686b2013-08-09 04:35:01 +000011454 // There are five cases here.
11455 // - There's no scope specifier and we're in a local class. Only look
11456 // for functions declared in the immediately-enclosing block scope.
11457 // We recover from invalid scope qualifiers as if they just weren't there.
11458 FunctionDecl *FunctionContainingLocalClass = 0;
11459 if ((SS.isInvalid() || !SS.isSet()) &&
11460 (FunctionContainingLocalClass =
11461 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11462 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000011463 // If a friend declaration appears in a local class and the name
11464 // specified is an unqualified name, a prior declaration is
11465 // looked up without considering scopes that are outside the
11466 // innermost enclosing non-class scope. For a friend function
11467 // declaration, if there is no prior declaration, the program is
11468 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000011469
11470 // Find the innermost enclosing non-class scope. This is the block
11471 // scope containing the local class definition (or for a nested class,
11472 // the outer local class).
11473 DCScope = S->getFnParent();
11474
11475 // Look up the function name in the scope.
11476 Previous.clear(LookupLocalFriendName);
11477 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11478
11479 if (!Previous.empty()) {
11480 // All possible previous declarations must have the same context:
11481 // either they were declared at block scope or they are members of
11482 // one of the enclosing local classes.
11483 DC = Previous.getRepresentativeDecl()->getDeclContext();
11484 } else {
11485 // This is ill-formed, but provide the context that we would have
11486 // declared the function in, if we were permitted to, for error recovery.
11487 DC = FunctionContainingLocalClass;
11488 }
11489
11490 // C++ [class.friend]p6:
11491 // A function can be defined in a friend declaration of a class if and
11492 // only if the class is a non-local class (9.8), the function name is
11493 // unqualified, and the function has namespace scope.
11494 if (D.isFunctionDefinition()) {
11495 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11496 }
11497
11498 // - There's no scope specifier, in which case we just go to the
11499 // appropriate scope and look for a function or function template
11500 // there as appropriate.
11501 } else if (SS.isInvalid() || !SS.isSet()) {
11502 // C++11 [namespace.memdef]p3:
11503 // If the name in a friend declaration is neither qualified nor
11504 // a template-id and the declaration is a function or an
11505 // elaborated-type-specifier, the lookup to determine whether
11506 // the entity has been previously declared shall not consider
11507 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000011508 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011509
John McCall29ae6e52010-10-13 05:45:15 +000011510 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011511 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011512
Rafael Espindola11dc6342013-04-25 20:12:36 +000011513 // Skip class contexts. If someone can cite chapter and verse
11514 // for this behavior, that would be nice --- it's what GCC and
11515 // EDG do, and it seems like a reasonable intent, but the spec
11516 // really only says that checks for unqualified existing
11517 // declarations should stop at the nearest enclosing namespace,
11518 // not that they should only consider the nearest enclosing
11519 // namespace.
11520 while (DC->isRecord())
11521 DC = DC->getParent();
11522
11523 DeclContext *LookupDC = DC;
11524 while (LookupDC->isTransparentContext())
11525 LookupDC = LookupDC->getParent();
11526
11527 while (true) {
11528 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011529
Rafael Espindola11dc6342013-04-25 20:12:36 +000011530 if (!Previous.empty()) {
11531 DC = LookupDC;
11532 break;
John McCall8a407372010-10-14 22:22:28 +000011533 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011534
11535 if (isTemplateId) {
11536 if (isa<TranslationUnitDecl>(LookupDC)) break;
11537 } else {
11538 if (LookupDC->isFileContext()) break;
11539 }
11540 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011541 }
11542
John McCall380aaa42010-10-13 06:22:15 +000011543 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011544
John McCall337ec3d2010-10-12 23:13:28 +000011545 // - There's a non-dependent scope specifier, in which case we
11546 // compute it and do a previous lookup there for a function
11547 // or function template.
11548 } else if (!SS.getScopeRep()->isDependent()) {
11549 DC = computeDeclContext(SS);
11550 if (!DC) return 0;
11551
11552 if (RequireCompleteDeclContext(SS, DC)) return 0;
11553
11554 LookupQualifiedName(Previous, DC);
11555
11556 // Ignore things found implicitly in the wrong scope.
11557 // TODO: better diagnostics for this case. Suggesting the right
11558 // qualified scope would be nice...
11559 LookupResult::Filter F = Previous.makeFilter();
11560 while (F.hasNext()) {
11561 NamedDecl *D = F.next();
11562 if (!DC->InEnclosingNamespaceSetOf(
11563 D->getDeclContext()->getRedeclContext()))
11564 F.erase();
11565 }
11566 F.done();
11567
11568 if (Previous.empty()) {
11569 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011570 Diag(Loc, diag::err_qualified_friend_not_found)
11571 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011572 return 0;
11573 }
11574
11575 // C++ [class.friend]p1: A friend of a class is a function or
11576 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011577 if (DC->Equals(CurContext))
11578 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011579 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011580 diag::warn_cxx98_compat_friend_is_member :
11581 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011582
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011583 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011584 // C++ [class.friend]p6:
11585 // A function can be defined in a friend declaration of a class if and
11586 // only if the class is a non-local class (9.8), the function name is
11587 // unqualified, and the function has namespace scope.
11588 SemaDiagnosticBuilder DB
11589 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11590
11591 DB << SS.getScopeRep();
11592 if (DC->isFileContext())
11593 DB << FixItHint::CreateRemoval(SS.getRange());
11594 SS.clear();
11595 }
John McCall337ec3d2010-10-12 23:13:28 +000011596
11597 // - There's a scope specifier that does not match any template
11598 // parameter lists, in which case we use some arbitrary context,
11599 // create a method or method template, and wait for instantiation.
11600 // - There's a scope specifier that does match some template
11601 // parameter lists, which we don't handle right now.
11602 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011603 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011604 // C++ [class.friend]p6:
11605 // A function can be defined in a friend declaration of a class if and
11606 // only if the class is a non-local class (9.8), the function name is
11607 // unqualified, and the function has namespace scope.
11608 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11609 << SS.getScopeRep();
11610 }
11611
John McCall337ec3d2010-10-12 23:13:28 +000011612 DC = CurContext;
11613 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011614 }
Douglas Gregor883af832011-10-10 01:11:59 +000011615
John McCall29ae6e52010-10-13 05:45:15 +000011616 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011617 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011618 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11619 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11620 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011621 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011622 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11623 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011624 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011625 }
John McCall67d1a672009-08-06 02:15:43 +000011626 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011627
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011628 // FIXME: This is an egregious hack to cope with cases where the scope stack
11629 // does not contain the declaration context, i.e., in an out-of-line
11630 // definition of a class.
11631 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11632 if (!DCScope) {
11633 FakeDCScope.setEntity(DC);
11634 DCScope = &FakeDCScope;
11635 }
Richard Smith4e9686b2013-08-09 04:35:01 +000011636
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011637 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011638 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011639 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011640 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011641
Douglas Gregor182ddf02009-09-28 00:08:27 +000011642 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011643
Richard Smith4e9686b2013-08-09 04:35:01 +000011644 // If we performed typo correction, we might have added a scope specifier
11645 // and changed the decl context.
11646 DC = ND->getDeclContext();
11647
John McCallab88d972009-08-31 22:39:49 +000011648 // Add the function declaration to the appropriate lookup tables,
11649 // adjusting the redeclarations list as necessary. We don't
11650 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011651 //
John McCallab88d972009-08-31 22:39:49 +000011652 // Also update the scope-based lookup if the target context's
11653 // lookup context is in lexical scope.
11654 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011655 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011656 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011657 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011658 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011659 }
John McCall02cace72009-08-28 07:59:38 +000011660
11661 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011662 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011663 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011664 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011665 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011666
John McCall1f2e1a92012-08-10 03:15:35 +000011667 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011668 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011669 } else {
11670 if (DC->isRecord()) CheckFriendAccess(ND);
11671
John McCall6102ca12010-10-16 06:59:13 +000011672 FunctionDecl *FD;
11673 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11674 FD = FTD->getTemplatedDecl();
11675 else
11676 FD = cast<FunctionDecl>(ND);
11677
David Majnemerf6a144f2013-06-25 23:09:30 +000011678 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11679 // default argument expression, that declaration shall be a definition
11680 // and shall be the only declaration of the function or function
11681 // template in the translation unit.
11682 if (functionDeclHasDefaultArgument(FD)) {
11683 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11684 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11685 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11686 } else if (!D.isFunctionDefinition())
11687 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11688 }
11689
John McCall6102ca12010-10-16 06:59:13 +000011690 // Mark templated-scope function declarations as unsupported.
11691 if (FD->getNumTemplateParameterLists())
11692 FrD->setUnsupportedFriend(true);
11693 }
John McCall337ec3d2010-10-12 23:13:28 +000011694
John McCalld226f652010-08-21 09:40:31 +000011695 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011696}
11697
John McCalld226f652010-08-21 09:40:31 +000011698void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11699 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011700
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011701 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011702 if (!Fn) {
11703 Diag(DelLoc, diag::err_deleted_non_function);
11704 return;
11705 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011706
Douglas Gregoref96ee02012-01-14 16:38:05 +000011707 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011708 // Don't consider the implicit declaration we generate for explicit
11709 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011710 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11711 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011712 Diag(DelLoc, diag::err_deleted_decl_not_first);
11713 Diag(Prev->getLocation(), diag::note_previous_declaration);
11714 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011715 // If the declaration wasn't the first, we delete the function anyway for
11716 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011717 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011718 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011719
11720 if (Fn->isDeleted())
11721 return;
11722
11723 // See if we're deleting a function which is already known to override a
11724 // non-deleted virtual function.
11725 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11726 bool IssuedDiagnostic = false;
11727 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11728 E = MD->end_overridden_methods();
11729 I != E; ++I) {
11730 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11731 if (!IssuedDiagnostic) {
11732 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11733 IssuedDiagnostic = true;
11734 }
11735 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11736 }
11737 }
11738 }
11739
Sean Hunt10620eb2011-05-06 20:44:56 +000011740 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011741}
Sebastian Redl13e88542009-04-27 21:33:24 +000011742
Sean Hunte4246a62011-05-12 06:15:49 +000011743void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011744 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011745
11746 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011747 if (MD->getParent()->isDependentType()) {
11748 MD->setDefaulted();
11749 MD->setExplicitlyDefaulted();
11750 return;
11751 }
11752
Sean Hunte4246a62011-05-12 06:15:49 +000011753 CXXSpecialMember Member = getSpecialMember(MD);
11754 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011755 if (!MD->isInvalidDecl())
11756 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000011757 return;
11758 }
11759
11760 MD->setDefaulted();
11761 MD->setExplicitlyDefaulted();
11762
Sean Huntcd10dec2011-05-23 23:14:04 +000011763 // If this definition appears within the record, do the checking when
11764 // the record is complete.
11765 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011766 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011767 // Find the uninstantiated declaration that actually had the '= default'
11768 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011769 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011770
Richard Smith12fef492013-03-27 00:22:47 +000011771 // If the method was defaulted on its first declaration, we will have
11772 // already performed the checking in CheckCompletedCXXClass. Such a
11773 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011774 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011775 return;
11776
Richard Smithb9d0b762012-07-27 04:22:15 +000011777 CheckExplicitlyDefaultedSpecialMember(MD);
11778
Richard Smith1d28caf2012-12-11 01:14:52 +000011779 // The exception specification is needed because we are defining the
11780 // function.
11781 ResolveExceptionSpec(DefaultLoc,
11782 MD->getType()->castAs<FunctionProtoType>());
11783
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011784 if (MD->isInvalidDecl())
11785 return;
11786
Sean Hunte4246a62011-05-12 06:15:49 +000011787 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011788 case CXXDefaultConstructor:
11789 DefineImplicitDefaultConstructor(DefaultLoc,
11790 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000011791 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011792 case CXXCopyConstructor:
11793 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000011794 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011795 case CXXCopyAssignment:
11796 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000011797 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011798 case CXXDestructor:
11799 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000011800 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011801 case CXXMoveConstructor:
11802 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000011803 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011804 case CXXMoveAssignment:
11805 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011806 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011807 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011808 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011809 }
11810 } else {
11811 Diag(DefaultLoc, diag::err_default_special_members);
11812 }
11813}
11814
Sebastian Redl13e88542009-04-27 21:33:24 +000011815static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011816 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011817 Stmt *SubStmt = *CI;
11818 if (!SubStmt)
11819 continue;
11820 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011821 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011822 diag::err_return_in_constructor_handler);
11823 if (!isa<Expr>(SubStmt))
11824 SearchForReturnInStmt(Self, SubStmt);
11825 }
11826}
11827
11828void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11829 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11830 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11831 SearchForReturnInStmt(*this, Handler);
11832 }
11833}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011834
David Blaikie299adab2013-01-18 23:03:15 +000011835bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011836 const CXXMethodDecl *Old) {
11837 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11838 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11839
11840 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11841
11842 // If the calling conventions match, everything is fine
11843 if (NewCC == OldCC)
11844 return false;
11845
Reid Kleckneref072032013-08-27 23:08:25 +000011846 Diag(New->getLocation(),
11847 diag::err_conflicting_overriding_cc_attributes)
11848 << New->getDeclName() << New->getType() << Old->getType();
11849 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11850 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011851}
11852
Mike Stump1eb44332009-09-09 15:08:12 +000011853bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011854 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011855 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11856 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011857
Chandler Carruth73857792010-02-15 11:53:20 +000011858 if (Context.hasSameType(NewTy, OldTy) ||
11859 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011860 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011861
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011862 // Check if the return types are covariant
11863 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011864
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011865 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011866 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11867 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011868 NewClassTy = NewPT->getPointeeType();
11869 OldClassTy = OldPT->getPointeeType();
11870 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011871 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11872 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11873 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11874 NewClassTy = NewRT->getPointeeType();
11875 OldClassTy = OldRT->getPointeeType();
11876 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011877 }
11878 }
Mike Stump1eb44332009-09-09 15:08:12 +000011879
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011880 // The return types aren't either both pointers or references to a class type.
11881 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011882 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011883 diag::err_different_return_type_for_overriding_virtual_function)
11884 << New->getDeclName() << NewTy << OldTy;
11885 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011886
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011887 return true;
11888 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011889
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011890 // C++ [class.virtual]p6:
11891 // If the return type of D::f differs from the return type of B::f, the
11892 // class type in the return type of D::f shall be complete at the point of
11893 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011894 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11895 if (!RT->isBeingDefined() &&
11896 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011897 diag::err_covariant_return_incomplete,
11898 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011899 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011900 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011901
Douglas Gregora4923eb2009-11-16 21:35:15 +000011902 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011903 // Check if the new class derives from the old class.
11904 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11905 Diag(New->getLocation(),
11906 diag::err_covariant_return_not_derived)
11907 << New->getDeclName() << NewTy << OldTy;
11908 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11909 return true;
11910 }
Mike Stump1eb44332009-09-09 15:08:12 +000011911
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011912 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011913 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011914 diag::err_covariant_return_inaccessible_base,
11915 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11916 // FIXME: Should this point to the return type?
11917 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011918 // FIXME: this note won't trigger for delayed access control
11919 // diagnostics, and it's impossible to get an undelayed error
11920 // here from access control during the original parse because
11921 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011922 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11923 return true;
11924 }
11925 }
Mike Stump1eb44332009-09-09 15:08:12 +000011926
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011927 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011928 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011929 Diag(New->getLocation(),
11930 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011931 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011932 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11933 return true;
11934 };
Mike Stump1eb44332009-09-09 15:08:12 +000011935
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011936
11937 // The new class type must have the same or less qualifiers as the old type.
11938 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11939 Diag(New->getLocation(),
11940 diag::err_covariant_return_type_class_type_more_qualified)
11941 << New->getDeclName() << NewTy << OldTy;
11942 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11943 return true;
11944 };
Mike Stump1eb44332009-09-09 15:08:12 +000011945
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011946 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011947}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011948
Douglas Gregor4ba31362009-12-01 17:24:26 +000011949/// \brief Mark the given method pure.
11950///
11951/// \param Method the method to be marked pure.
11952///
11953/// \param InitRange the source range that covers the "0" initializer.
11954bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011955 SourceLocation EndLoc = InitRange.getEnd();
11956 if (EndLoc.isValid())
11957 Method->setRangeEnd(EndLoc);
11958
Douglas Gregor4ba31362009-12-01 17:24:26 +000011959 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11960 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011961 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011962 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011963
11964 if (!Method->isInvalidDecl())
11965 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11966 << Method->getDeclName() << InitRange;
11967 return true;
11968}
11969
Douglas Gregor552e2992012-02-21 02:22:07 +000011970/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011971static bool isStaticDataMember(const Decl *D) {
11972 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
11973 return Var->isStaticDataMember();
11974
11975 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000011976}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011977
John McCall731ad842009-12-19 09:28:58 +000011978/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11979/// an initializer for the out-of-line declaration 'Dcl'. The scope
11980/// is a fresh scope pushed for just this purpose.
11981///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011982/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11983/// static data member of class X, names should be looked up in the scope of
11984/// class X.
John McCalld226f652010-08-21 09:40:31 +000011985void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011986 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011987 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011988
John McCall731ad842009-12-19 09:28:58 +000011989 // We should only get called for declarations with scope specifiers, like:
11990 // int foo::bar;
11991 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011992 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011993
11994 // If we are parsing the initializer for a static data member, push a
11995 // new expression evaluation context that is associated with this static
11996 // data member.
11997 if (isStaticDataMember(D))
11998 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011999}
12000
12001/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000012002/// initializer for the out-of-line declaration 'D'.
12003void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012004 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012005 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012006
Douglas Gregor552e2992012-02-21 02:22:07 +000012007 if (isStaticDataMember(D))
12008 PopExpressionEvaluationContext();
12009
John McCall731ad842009-12-19 09:28:58 +000012010 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012011 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012012}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012013
12014/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12015/// C++ if/switch/while/for statement.
12016/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000012017DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012018 // C++ 6.4p2:
12019 // The declarator shall not specify a function or an array.
12020 // The type-specifier-seq shall not contain typedef and shall not declare a
12021 // new class or enumeration.
12022 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12023 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012024
12025 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000012026 if (!Dcl)
12027 return true;
12028
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012029 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12030 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012031 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000012032 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012033 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012034
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012035 return Dcl;
12036}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012037
Douglas Gregordfe65432011-07-28 19:11:31 +000012038void Sema::LoadExternalVTableUses() {
12039 if (!ExternalSource)
12040 return;
12041
12042 SmallVector<ExternalVTableUse, 4> VTables;
12043 ExternalSource->ReadUsedVTables(VTables);
12044 SmallVector<VTableUse, 4> NewUses;
12045 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12046 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12047 = VTablesUsed.find(VTables[I].Record);
12048 // Even if a definition wasn't required before, it may be required now.
12049 if (Pos != VTablesUsed.end()) {
12050 if (!Pos->second && VTables[I].DefinitionRequired)
12051 Pos->second = true;
12052 continue;
12053 }
12054
12055 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12056 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12057 }
12058
12059 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12060}
12061
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012062void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12063 bool DefinitionRequired) {
12064 // Ignore any vtable uses in unevaluated operands or for classes that do
12065 // not have a vtable.
12066 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000012067 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000012068 return;
12069
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012070 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000012071 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012072 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12073 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12074 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12075 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000012076 // If we already had an entry, check to see if we are promoting this vtable
12077 // to required a definition. If so, we need to reappend to the VTableUses
12078 // list, since we may have already processed the first entry.
12079 if (DefinitionRequired && !Pos.first->second) {
12080 Pos.first->second = true;
12081 } else {
12082 // Otherwise, we can early exit.
12083 return;
12084 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012085 }
12086
12087 // Local classes need to have their virtual members marked
12088 // immediately. For all other classes, we mark their virtual members
12089 // at the end of the translation unit.
12090 if (Class->isLocalClass())
12091 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000012092 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012093 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000012094}
12095
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012096bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000012097 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012098 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000012099 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000012100
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012101 // Note: The VTableUses vector could grow as a result of marking
12102 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000012103 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012104 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000012105 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012106 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000012107 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012108 if (!Class)
12109 continue;
12110
12111 SourceLocation Loc = VTableUses[I].second;
12112
Richard Smithb9d0b762012-07-27 04:22:15 +000012113 bool DefineVTable = true;
12114
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012115 // If this class has a key function, but that key function is
12116 // defined in another translation unit, we don't need to emit the
12117 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000012118 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000012119 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000012120 // The key function is in another translation unit.
12121 DefineVTable = false;
12122 TemplateSpecializationKind TSK =
12123 KeyFunction->getTemplateSpecializationKind();
12124 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12125 TSK != TSK_ImplicitInstantiation &&
12126 "Instantiations don't have key functions");
12127 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012128 } else if (!KeyFunction) {
12129 // If we have a class with no key function that is the subject
12130 // of an explicit instantiation declaration, suppress the
12131 // vtable; it will live with the explicit instantiation
12132 // definition.
12133 bool IsExplicitInstantiationDeclaration
12134 = Class->getTemplateSpecializationKind()
12135 == TSK_ExplicitInstantiationDeclaration;
12136 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12137 REnd = Class->redecls_end();
12138 R != REnd; ++R) {
12139 TemplateSpecializationKind TSK
12140 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12141 if (TSK == TSK_ExplicitInstantiationDeclaration)
12142 IsExplicitInstantiationDeclaration = true;
12143 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12144 IsExplicitInstantiationDeclaration = false;
12145 break;
12146 }
12147 }
12148
12149 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000012150 DefineVTable = false;
12151 }
12152
12153 // The exception specifications for all virtual members may be needed even
12154 // if we are not providing an authoritative form of the vtable in this TU.
12155 // We may choose to emit it available_externally anyway.
12156 if (!DefineVTable) {
12157 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12158 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012159 }
12160
12161 // Mark all of the virtual members of this class as referenced, so
12162 // that we can build a vtable. Then, tell the AST consumer that a
12163 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012164 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012165 MarkVirtualMembersReferenced(Loc, Class);
12166 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12167 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12168
12169 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012170 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012171 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000012172 const FunctionDecl *KeyFunctionDef = 0;
12173 if (!KeyFunction ||
12174 (KeyFunction->hasBody(KeyFunctionDef) &&
12175 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012176 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12177 TSK_ExplicitInstantiationDefinition
12178 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12179 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012180 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012181 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012182 VTableUses.clear();
12183
Douglas Gregor78844032011-04-22 22:25:37 +000012184 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012185}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012186
Richard Smithb9d0b762012-07-27 04:22:15 +000012187void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12188 const CXXRecordDecl *RD) {
12189 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12190 E = RD->method_end(); I != E; ++I)
12191 if ((*I)->isVirtual() && !(*I)->isPure())
12192 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12193}
12194
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012195void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12196 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012197 // Mark all functions which will appear in RD's vtable as used.
12198 CXXFinalOverriderMap FinalOverriders;
12199 RD->getFinalOverriders(FinalOverriders);
12200 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12201 E = FinalOverriders.end();
12202 I != E; ++I) {
12203 for (OverridingMethods::const_iterator OI = I->second.begin(),
12204 OE = I->second.end();
12205 OI != OE; ++OI) {
12206 assert(OI->second.size() > 0 && "no final overrider");
12207 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012208
Richard Smithff817f72012-07-07 06:59:51 +000012209 // C++ [basic.def.odr]p2:
12210 // [...] A virtual member function is used if it is not pure. [...]
12211 if (!Overrider->isPure())
12212 MarkFunctionReferenced(Loc, Overrider);
12213 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012214 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012215
12216 // Only classes that have virtual bases need a VTT.
12217 if (RD->getNumVBases() == 0)
12218 return;
12219
12220 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12221 e = RD->bases_end(); i != e; ++i) {
12222 const CXXRecordDecl *Base =
12223 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012224 if (Base->getNumVBases() == 0)
12225 continue;
12226 MarkVirtualMembersReferenced(Loc, Base);
12227 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012228}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012229
12230/// SetIvarInitializers - This routine builds initialization ASTs for the
12231/// Objective-C implementation whose ivars need be initialized.
12232void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012233 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012234 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012235 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012236 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012237 CollectIvarsToConstructOrDestruct(OID, ivars);
12238 if (ivars.empty())
12239 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012240 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012241 for (unsigned i = 0; i < ivars.size(); i++) {
12242 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012243 if (Field->isInvalidDecl())
12244 continue;
12245
Sean Huntcbb67482011-01-08 20:30:50 +000012246 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012247 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12248 InitializationKind InitKind =
12249 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012250
12251 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12252 ExprResult MemberInit =
12253 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012254 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012255 // Note, MemberInit could actually come back empty if no initialization
12256 // is required (e.g., because it would call a trivial default constructor)
12257 if (!MemberInit.get() || MemberInit.isInvalid())
12258 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012259
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012260 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012261 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12262 SourceLocation(),
12263 MemberInit.takeAs<Expr>(),
12264 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012265 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012266
12267 // Be sure that the destructor is accessible and is marked as referenced.
12268 if (const RecordType *RecordTy
12269 = Context.getBaseElementType(Field->getType())
12270 ->getAs<RecordType>()) {
12271 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012272 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012273 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012274 CheckDestructorAccess(Field->getLocation(), Destructor,
12275 PDiag(diag::err_access_dtor_ivar)
12276 << Context.getBaseElementType(Field->getType()));
12277 }
12278 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012279 }
12280 ObjCImplementation->setIvarInitializers(Context,
12281 AllToInit.data(), AllToInit.size());
12282 }
12283}
Sean Huntfe57eef2011-05-04 05:57:24 +000012284
Sean Huntebcbe1d2011-05-04 23:29:54 +000012285static
12286void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12287 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12288 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12289 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12290 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012291 if (Ctor->isInvalidDecl())
12292 return;
12293
Richard Smitha8eaf002012-08-23 06:16:52 +000012294 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12295
12296 // Target may not be determinable yet, for instance if this is a dependent
12297 // call in an uninstantiated template.
12298 if (Target) {
12299 const FunctionDecl *FNTarget = 0;
12300 (void)Target->hasBody(FNTarget);
12301 Target = const_cast<CXXConstructorDecl*>(
12302 cast_or_null<CXXConstructorDecl>(FNTarget));
12303 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012304
12305 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12306 // Avoid dereferencing a null pointer here.
12307 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12308
12309 if (!Current.insert(Canonical))
12310 return;
12311
12312 // We know that beyond here, we aren't chaining into a cycle.
12313 if (!Target || !Target->isDelegatingConstructor() ||
12314 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012315 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012316 Current.clear();
12317 // We've hit a cycle.
12318 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12319 Current.count(TCanonical)) {
12320 // If we haven't diagnosed this cycle yet, do so now.
12321 if (!Invalid.count(TCanonical)) {
12322 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012323 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012324 << Ctor;
12325
Richard Smitha8eaf002012-08-23 06:16:52 +000012326 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012327 if (TCanonical != Canonical)
12328 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12329
12330 CXXConstructorDecl *C = Target;
12331 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012332 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012333 (void)C->getTargetConstructor()->hasBody(FNTarget);
12334 assert(FNTarget && "Ctor cycle through bodiless function");
12335
Richard Smitha8eaf002012-08-23 06:16:52 +000012336 C = const_cast<CXXConstructorDecl*>(
12337 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012338 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12339 }
12340 }
12341
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012342 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012343 Current.clear();
12344 } else {
12345 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12346 }
12347}
12348
12349
Sean Huntfe57eef2011-05-04 05:57:24 +000012350void Sema::CheckDelegatingCtorCycles() {
12351 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12352
Douglas Gregor0129b562011-07-27 21:57:17 +000012353 for (DelegatingCtorDeclsType::iterator
12354 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012355 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012356 I != E; ++I)
12357 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012358
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012359 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12360 CE = Invalid.end();
12361 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012362 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012363}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012364
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012365namespace {
12366 /// \brief AST visitor that finds references to the 'this' expression.
12367 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12368 Sema &S;
12369
12370 public:
12371 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12372
12373 bool VisitCXXThisExpr(CXXThisExpr *E) {
12374 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12375 << E->isImplicit();
12376 return false;
12377 }
12378 };
12379}
12380
12381bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12382 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12383 if (!TSInfo)
12384 return false;
12385
12386 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012387 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012388 if (!ProtoTL)
12389 return false;
12390
12391 // C++11 [expr.prim.general]p3:
12392 // [The expression this] shall not appear before the optional
12393 // cv-qualifier-seq and it shall not appear within the declaration of a
12394 // static member function (although its type and value category are defined
12395 // within a static member function as they are within a non-static member
12396 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012397 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012398 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012399 FindCXXThisExpr Finder(*this);
12400
12401 // If the return type came after the cv-qualifier-seq, check it now.
12402 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012403 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012404 return true;
12405
12406 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012407 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12408 return true;
12409
12410 return checkThisInStaticMemberFunctionAttributes(Method);
12411}
12412
12413bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12414 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12415 if (!TSInfo)
12416 return false;
12417
12418 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012419 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012420 if (!ProtoTL)
12421 return false;
12422
David Blaikie39e6ab42013-02-18 22:06:02 +000012423 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012424 FindCXXThisExpr Finder(*this);
12425
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012426 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012427 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012428 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012429 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012430 case EST_DynamicNone:
12431 case EST_MSAny:
12432 case EST_None:
12433 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012434
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012435 case EST_ComputedNoexcept:
12436 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12437 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012438
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012439 case EST_Dynamic:
12440 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012441 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012442 E != EEnd; ++E) {
12443 if (!Finder.TraverseType(*E))
12444 return true;
12445 }
12446 break;
12447 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012448
12449 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012450}
12451
12452bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12453 FindCXXThisExpr Finder(*this);
12454
12455 // Check attributes.
12456 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12457 A != AEnd; ++A) {
12458 // FIXME: This should be emitted by tblgen.
12459 Expr *Arg = 0;
12460 ArrayRef<Expr *> Args;
12461 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12462 Arg = G->getArg();
12463 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12464 Arg = G->getArg();
12465 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12466 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12467 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12468 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12469 else if (ExclusiveLockFunctionAttr *ELF
12470 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12471 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12472 else if (SharedLockFunctionAttr *SLF
12473 = dyn_cast<SharedLockFunctionAttr>(*A))
12474 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12475 else if (ExclusiveTrylockFunctionAttr *ETLF
12476 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12477 Arg = ETLF->getSuccessValue();
12478 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12479 } else if (SharedTrylockFunctionAttr *STLF
12480 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12481 Arg = STLF->getSuccessValue();
12482 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12483 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12484 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12485 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12486 Arg = LR->getArg();
12487 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12488 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12489 else if (ExclusiveLocksRequiredAttr *ELR
12490 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12491 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12492 else if (SharedLocksRequiredAttr *SLR
12493 = dyn_cast<SharedLocksRequiredAttr>(*A))
12494 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12495
12496 if (Arg && !Finder.TraverseStmt(Arg))
12497 return true;
12498
12499 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12500 if (!Finder.TraverseStmt(Args[I]))
12501 return true;
12502 }
12503 }
12504
12505 return false;
12506}
12507
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012508void
12509Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12510 ArrayRef<ParsedType> DynamicExceptions,
12511 ArrayRef<SourceRange> DynamicExceptionRanges,
12512 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012513 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012514 FunctionProtoType::ExtProtoInfo &EPI) {
12515 Exceptions.clear();
12516 EPI.ExceptionSpecType = EST;
12517 if (EST == EST_Dynamic) {
12518 Exceptions.reserve(DynamicExceptions.size());
12519 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12520 // FIXME: Preserve type source info.
12521 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12522
12523 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12524 collectUnexpandedParameterPacks(ET, Unexpanded);
12525 if (!Unexpanded.empty()) {
12526 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12527 UPPC_ExceptionType,
12528 Unexpanded);
12529 continue;
12530 }
12531
12532 // Check that the type is valid for an exception spec, and
12533 // drop it if not.
12534 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12535 Exceptions.push_back(ET);
12536 }
12537 EPI.NumExceptions = Exceptions.size();
12538 EPI.Exceptions = Exceptions.data();
12539 return;
12540 }
12541
12542 if (EST == EST_ComputedNoexcept) {
12543 // If an error occurred, there's no expression here.
12544 if (NoexceptExpr) {
12545 assert((NoexceptExpr->isTypeDependent() ||
12546 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12547 Context.BoolTy) &&
12548 "Parser should have made sure that the expression is boolean");
12549 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12550 EPI.ExceptionSpecType = EST_BasicNoexcept;
12551 return;
12552 }
12553
12554 if (!NoexceptExpr->isValueDependent())
12555 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012556 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012557 /*AllowFold*/ false).take();
12558 EPI.NoexceptExpr = NoexceptExpr;
12559 }
12560 return;
12561 }
12562}
12563
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012564/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12565Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12566 // Implicitly declared functions (e.g. copy constructors) are
12567 // __host__ __device__
12568 if (D->isImplicit())
12569 return CFT_HostDevice;
12570
12571 if (D->hasAttr<CUDAGlobalAttr>())
12572 return CFT_Global;
12573
12574 if (D->hasAttr<CUDADeviceAttr>()) {
12575 if (D->hasAttr<CUDAHostAttr>())
12576 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012577 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012578 }
12579
12580 return CFT_Host;
12581}
12582
12583bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12584 CUDAFunctionTarget CalleeTarget) {
12585 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12586 // Callable from the device only."
12587 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12588 return true;
12589
12590 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12591 // Callable from the host only."
12592 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12593 // Callable from the host only."
12594 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12595 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12596 return true;
12597
12598 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12599 return true;
12600
12601 return false;
12602}
John McCall76da55d2013-04-16 07:28:30 +000012603
12604/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12605///
12606MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12607 SourceLocation DeclStart,
12608 Declarator &D, Expr *BitWidth,
12609 InClassInitStyle InitStyle,
12610 AccessSpecifier AS,
12611 AttributeList *MSPropertyAttr) {
12612 IdentifierInfo *II = D.getIdentifier();
12613 if (!II) {
12614 Diag(DeclStart, diag::err_anonymous_property);
12615 return NULL;
12616 }
12617 SourceLocation Loc = D.getIdentifierLoc();
12618
12619 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12620 QualType T = TInfo->getType();
12621 if (getLangOpts().CPlusPlus) {
12622 CheckExtraCXXDefaultArguments(D);
12623
12624 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12625 UPPC_DataMemberType)) {
12626 D.setInvalidType();
12627 T = Context.IntTy;
12628 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12629 }
12630 }
12631
12632 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12633
12634 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12635 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12636 diag::err_invalid_thread)
12637 << DeclSpec::getSpecifierName(TSCS);
12638
12639 // Check to see if this name was declared as a member previously
12640 NamedDecl *PrevDecl = 0;
12641 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12642 LookupName(Previous, S);
12643 switch (Previous.getResultKind()) {
12644 case LookupResult::Found:
12645 case LookupResult::FoundUnresolvedValue:
12646 PrevDecl = Previous.getAsSingle<NamedDecl>();
12647 break;
12648
12649 case LookupResult::FoundOverloaded:
12650 PrevDecl = Previous.getRepresentativeDecl();
12651 break;
12652
12653 case LookupResult::NotFound:
12654 case LookupResult::NotFoundInCurrentInstantiation:
12655 case LookupResult::Ambiguous:
12656 break;
12657 }
12658
12659 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12660 // Maybe we will complain about the shadowed template parameter.
12661 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12662 // Just pretend that we didn't see the previous declaration.
12663 PrevDecl = 0;
12664 }
12665
12666 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12667 PrevDecl = 0;
12668
12669 SourceLocation TSSL = D.getLocStart();
12670 MSPropertyDecl *NewPD;
12671 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12672 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12673 II, T, TInfo, TSSL,
12674 Data.GetterId, Data.SetterId);
12675 ProcessDeclAttributes(TUScope, NewPD, D);
12676 NewPD->setAccess(AS);
12677
12678 if (NewPD->isInvalidDecl())
12679 Record->setInvalidDecl();
12680
12681 if (D.getDeclSpec().isModulePrivateSpecified())
12682 NewPD->setModulePrivate();
12683
12684 if (NewPD->isInvalidDecl() && PrevDecl) {
12685 // Don't introduce NewFD into scope; there's already something
12686 // with the same name in the same scope.
12687 } else if (II) {
12688 PushOnScopeChains(NewPD, S);
12689 } else
12690 Record->addDecl(NewPD);
12691
12692 return NewPD;
12693}