blob: f5bb3511f22561908d72445ac08b98a9e8ed3230 [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"
Faisal Valifad9e132013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000030#include "clang/Basic/TargetInfo.h"
Richard Smith4ac537b2013-07-23 08:14:48 +000031#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000033#include "clang/Sema/CXXFieldCollector.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000042#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000043#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner8123a952008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattner9e979552008-04-12 23:52:44 +000051namespace {
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000061
Chris Lattner9e979552008-04-12 23:52:44 +000062 public:
Mike Stump1eb44332009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000065
Chris Lattner9e979552008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000071 };
Chris Lattner8123a952008-04-10 02:22:51 +000072
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000079 }
80
Chris Lattner9e979552008-04-12 23:52:44 +000081 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000086 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107
Douglas Gregor3996f232008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattner9e979552008-04-12 23:52:44 +0000110
Douglas Gregor796da182008-11-04 14:32:21 +0000111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000119 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000120
John McCall045d2522013-04-09 01:56:28 +0000121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
Douglas Gregorf0459f82012-02-10 23:30:22 +0000138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
Chris Lattner8123a952008-04-10 02:22:51 +0000148}
149
Richard Smith0b0ca472013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith7a614d82011-06-11 17:19:42 +0000172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
174
Sean Hunt001cad92011-05-10 00:49:42 +0000175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
177 return;
178
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
181 return;
182
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
188 return;
189 }
190
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
200
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
209
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
215 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
216 EEnd = Proto->exception_end();
217 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000219 Exceptions.push_back(*E);
220}
221
Richard Smith7a614d82011-06-11 17:19:42 +0000222void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000223 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000224 return;
225
226 // FIXME:
227 //
228 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000229 // [An] implicit exception-specification specifies the type-id T if and
230 // only if T is allowed by the exception-specification of a function directly
231 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000232 // function it directly invokes allows all exceptions, and f shall allow no
233 // exceptions if every function it directly invokes allows no exceptions.
234 //
235 // Note in particular that if an implicit exception-specification is generated
236 // for a function containing a throw-expression, that specification can still
237 // be noexcept(true).
238 //
239 // Note also that 'directly invoked' is not defined in the standard, and there
240 // is no indication that we should only consider potentially-evaluated calls.
241 //
242 // Ultimately we should implement the intent of the standard: the exception
243 // specification should be the set of exceptions which can be thrown by the
244 // implicit definition. For now, we assume that any non-nothrow expression can
245 // throw any exception.
246
Richard Smithe6975e92012-04-17 00:58:00 +0000247 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000248 ComputedEST = EST_None;
249}
250
Anders Carlssoned961f92009-08-25 02:29:20 +0000251bool
John McCall9ae2f072010-08-23 23:25:46 +0000252Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000253 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000254 if (RequireCompleteType(Param->getLocation(), Param->getType(),
255 diag::err_typecheck_decl_incomplete_type)) {
256 Param->setInvalidDecl();
257 return true;
258 }
259
Anders Carlssoned961f92009-08-25 02:29:20 +0000260 // C++ [dcl.fct.default]p5
261 // A default argument expression is implicitly converted (clause
262 // 4) to the parameter type. The default argument expression has
263 // the same semantic constraints as the initializer expression in
264 // a declaration of a variable of the parameter type, using the
265 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000270 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000273 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000274 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000275
Richard Smith6c3af3d2013-01-17 01:17:56 +0000276 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000277 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Anders Carlssoned961f92009-08-25 02:29:20 +0000279 // Okay: add the default argument to the parameter
280 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000282 // We have already instantiated this parameter; provide each of the
283 // instantiations with the uninstantiated default argument.
284 UnparsedDefaultArgInstantiationsMap::iterator InstPos
285 = UnparsedDefaultArgInstantiations.find(Param);
286 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
289
290 // We're done tracking this parameter's instantiations.
291 UnparsedDefaultArgInstantiations.erase(InstPos);
292 }
293
Anders Carlsson9351c172009-08-25 03:18:48 +0000294 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000295}
296
Chris Lattner8123a952008-04-10 02:22:51 +0000297/// ActOnParamDefaultArgument - Check whether the default argument
298/// provided for a function parameter is well-formed. If so, attach it
299/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000300void
John McCalld226f652010-08-21 09:40:31 +0000301Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000302 Expr *DefaultArg) {
303 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000304 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000305
John McCalld226f652010-08-21 09:40:31 +0000306 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs.erase(Param);
308
Chris Lattner3d1cee32008-04-08 05:04:30 +0000309 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000310 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000311 Diag(EqualLoc, diag::err_param_default_argument)
312 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000313 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000314 return;
315 }
316
Douglas Gregor6f526752010-12-16 08:48:57 +0000317 // Check for unexpanded parameter packs.
318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319 Param->setInvalidDecl();
320 return;
321 }
322
Anders Carlsson66e30672009-08-25 01:02:06 +0000323 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000324 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
325 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000326 Param->setInvalidDecl();
327 return;
328 }
Mike Stump1eb44332009-09-09 15:08:12 +0000329
John McCall9ae2f072010-08-23 23:25:46 +0000330 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000331}
332
Douglas Gregor61366e92008-12-24 00:01:03 +0000333/// ActOnParamUnparsedDefaultArgument - We've seen a default
334/// argument for a function parameter, but we can't parse it yet
335/// because we're inside a class definition. Note that this default
336/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000337void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000338 SourceLocation EqualLoc,
339 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000340 if (!param)
341 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000342
John McCalld226f652010-08-21 09:40:31 +0000343 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +0000344 Param->setUnparsedDefaultArg();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000355 Param->setInvalidDecl();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000357}
358
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000359/// CheckExtraCXXDefaultArguments - Check for any extra default
360/// arguments in the declarator, which is not a function declaration
361/// or definition and therefore is not permitted to have default
362/// arguments. This routine should be invoked for every declarator
363/// that is not a function declaration or definition.
364void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365 // C++ [dcl.fct.default]p3
366 // A default argument expression shall be specified only in the
367 // parameter-declaration-clause of a function declaration or in a
368 // template-parameter (14.1). It shall not be specified for a
369 // parameter pack. If it is specified in a
370 // parameter-declaration-clause, it shall not occur within a
371 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000372 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000374 DeclaratorChunk &chunk = D.getTypeObject(i);
375 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000376 if (MightBeFunction) {
377 // This is a function declaration. It can have default arguments, but
378 // keep looking in case its return type is a function type with default
379 // arguments.
380 MightBeFunction = false;
381 continue;
382 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000383 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
384 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000385 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000386 if (Param->hasUnparsedDefaultArg()) {
387 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000389 << SourceRange((*Toks)[1].getLocation(),
390 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 delete Toks;
392 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000393 } else if (Param->getDefaultArg()) {
394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395 << Param->getDefaultArg()->getSourceRange();
396 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000397 }
398 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000399 } else if (chunk.Kind != DeclaratorChunk::Paren) {
400 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000401 }
402 }
403}
404
David Majnemerf6a144f2013-06-25 23:09:30 +0000405static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408 if (!PVD->hasDefaultArg())
409 return false;
410 if (!PVD->hasInheritedDefaultArg())
411 return true;
412 }
413 return false;
414}
415
Craig Topper1a6eac82012-09-21 04:33:26 +0000416/// MergeCXXFunctionDecl - Merge two declarations of the same C++
417/// function, once we already know that they have the same
418/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000422 bool Invalid = false;
423
Chris Lattner3d1cee32008-04-08 05:04:30 +0000424 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000425 // For non-template functions, default arguments can be added in
426 // later declarations of a function in the same
427 // scope. Declarations in different scopes have completely
428 // distinct sets of default arguments. That is, declarations in
429 // inner scopes do not acquire default arguments from
430 // declarations in outer scopes, and vice versa. In a given
431 // function declaration, all parameters subsequent to a
432 // parameter with a default argument shall have default
433 // arguments supplied in this or previous declarations. A
434 // default argument shall not be redefined by a later
435 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000436 //
437 // C++ [dcl.fct.default]p6:
Richard Smitha41c97a2013-09-20 01:15:31 +0000438 // Except for member functions of class templates, the default arguments
439 // in a member function definition that appears outside of the class
440 // definition are added to the set of default arguments provided by the
Douglas Gregor6cc15182009-09-11 18:44:32 +0000441 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443 ParmVarDecl *OldParam = Old->getParamDecl(p);
444 ParmVarDecl *NewParam = New->getParamDecl(p);
445
James Molloy9cda03f2012-03-13 08:55:35 +0000446 bool OldParamHasDfl = OldParam->hasDefaultArg();
447 bool NewParamHasDfl = NewParam->hasDefaultArg();
448
449 NamedDecl *ND = Old;
Richard Smitha41c97a2013-09-20 01:15:31 +0000450
451 // The declaration context corresponding to the scope is the semantic
452 // parent, unless this is a local function declaration, in which case
453 // it is that surrounding function.
454 DeclContext *ScopeDC = New->getLexicalDeclContext();
455 if (!ScopeDC->isFunctionOrMethod())
456 ScopeDC = New->getDeclContext();
457 if (S && !isDeclInScope(ND, ScopeDC, S) &&
458 !New->getDeclContext()->isRecord())
James Molloy9cda03f2012-03-13 08:55:35 +0000459 // Ignore default parameters of old decl if they are not in
Richard Smitha41c97a2013-09-20 01:15:31 +0000460 // the same scope and this is not an out-of-line definition of
461 // a member function.
James Molloy9cda03f2012-03-13 08:55:35 +0000462 OldParamHasDfl = false;
463
464 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000465
Francois Pichet8d051e02011-04-10 03:03:52 +0000466 unsigned DiagDefaultParamID =
467 diag::err_param_default_argument_redefinition;
468
469 // MSVC accepts that default parameters be redefined for member functions
470 // of template class. The new default parameter's value is ignored.
471 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000472 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000475 // Merge the old default argument into the new parameter.
476 NewParam->setHasInheritedDefaultArg();
477 if (OldParam->hasUninstantiatedDefaultArg())
478 NewParam->setUninstantiatedDefaultArg(
479 OldParam->getUninstantiatedDefaultArg());
480 else
481 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000482 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000483 Invalid = false;
484 }
485 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000486
Francois Pichet8cf90492011-04-10 04:58:30 +0000487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488 // hint here. Alternatively, we could walk the type-source information
489 // for NewParam to find the last source location in the type... but it
490 // isn't worth the effort right now. This is the kind of test case that
491 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000492 // int f(int);
493 // void g(int (*fp)(int) = f);
494 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000495 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000496 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000497
498 // Look for the function declaration where the default argument was
499 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000500 for (FunctionDecl *Older = Old->getPreviousDecl();
501 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000502 if (!Older->getParamDecl(p)->hasDefaultArg())
503 break;
504
505 OldParam = Older->getParamDecl(p);
506 }
507
508 Diag(OldParam->getLocation(), diag::note_previous_definition)
509 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000510 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000511 // Merge the old default argument into the new parameter.
512 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000513 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000514 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000515 if (OldParam->hasUninstantiatedDefaultArg())
516 NewParam->setUninstantiatedDefaultArg(
517 OldParam->getUninstantiatedDefaultArg());
518 else
John McCall3d6c1782010-05-04 01:53:42 +0000519 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000520 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000521 if (New->getDescribedFunctionTemplate()) {
522 // Paragraph 4, quoted above, only applies to non-template functions.
523 Diag(NewParam->getLocation(),
524 diag::err_param_default_argument_template_redecl)
525 << NewParam->getDefaultArgRange();
526 Diag(Old->getLocation(), diag::note_template_prev_declaration)
527 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000528 } else if (New->getTemplateSpecializationKind()
529 != TSK_ImplicitInstantiation &&
530 New->getTemplateSpecializationKind() != TSK_Undeclared) {
531 // C++ [temp.expr.spec]p21:
532 // Default function arguments shall not be specified in a declaration
533 // or a definition for one of the following explicit specializations:
534 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000535 // - the explicit specialization of a member function template;
536 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000537 // template where the class template specialization to which the
538 // member function specialization belongs is implicitly
539 // instantiated.
540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542 << New->getDeclName()
543 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000544 } else if (New->getDeclContext()->isDependentContext()) {
545 // C++ [dcl.fct.default]p6 (DR217):
546 // Default arguments for a member function of a class template shall
547 // be specified on the initial declaration of the member function
548 // within the class template.
549 //
550 // Reading the tea leaves a bit in DR217 and its reference to DR205
551 // leads me to the conclusion that one cannot add default function
552 // arguments for an out-of-line definition of a member function of a
553 // dependent type.
554 int WhichKind = 2;
555 if (CXXRecordDecl *Record
556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557 if (Record->getDescribedClassTemplate())
558 WhichKind = 0;
559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560 WhichKind = 1;
561 else
562 WhichKind = 2;
563 }
564
565 Diag(NewParam->getLocation(),
566 diag::err_param_default_argument_member_template_redecl)
567 << WhichKind
568 << NewParam->getDefaultArgRange();
569 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000570 }
571 }
572
Richard Smithb8abff62012-11-28 03:45:24 +0000573 // DR1344: If a default argument is added outside a class definition and that
574 // default argument makes the function a special member function, the program
575 // is ill-formed. This can only happen for constructors.
576 if (isa<CXXConstructorDecl>(New) &&
577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580 if (NewSM != OldSM) {
581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582 assert(NewParam->hasDefaultArg());
583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584 << NewParam->getDefaultArgRange() << NewSM;
585 Diag(Old->getLocation(), diag::note_previous_declaration);
586 }
587 }
588
Richard Smithff234882012-02-20 23:28:05 +0000589 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000590 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000591 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000592 if (New->isConstexpr() != Old->isConstexpr()) {
593 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
594 << New << New->isConstexpr();
595 Diag(Old->getLocation(), diag::note_previous_declaration);
596 Invalid = true;
597 }
598
David Majnemerf6a144f2013-06-25 23:09:30 +0000599 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000600 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000601 // the only declaration of the function or function template in the
602 // translation unit.
603 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
604 functionDeclHasDefaultArgument(Old)) {
605 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
606 Diag(Old->getLocation(), diag::note_previous_declaration);
607 Invalid = true;
608 }
609
Douglas Gregore13ad832010-02-12 07:32:17 +0000610 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000611 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000612
Douglas Gregorcda9c672009-02-16 17:45:42 +0000613 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000614}
615
Sebastian Redl60618fa2011-03-12 11:50:43 +0000616/// \brief Merge the exception specifications of two variable declarations.
617///
618/// This is called when there's a redeclaration of a VarDecl. The function
619/// checks if the redeclaration might have an exception specification and
620/// validates compatibility and merges the specs if necessary.
621void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
622 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000623 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000624 return;
625
626 assert(Context.hasSameType(New->getType(), Old->getType()) &&
627 "Should only be called if types are otherwise the same.");
628
629 QualType NewType = New->getType();
630 QualType OldType = Old->getType();
631
632 // We're only interested in pointers and references to functions, as well
633 // as pointers to member functions.
634 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
635 NewType = R->getPointeeType();
636 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
637 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
638 NewType = P->getPointeeType();
639 OldType = OldType->getAs<PointerType>()->getPointeeType();
640 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
641 NewType = M->getPointeeType();
642 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
643 }
644
645 if (!NewType->isFunctionProtoType())
646 return;
647
648 // There's lots of special cases for functions. For function pointers, system
649 // libraries are hopefully not as broken so that we don't need these
650 // workarounds.
651 if (CheckEquivalentExceptionSpec(
652 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
653 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
654 New->setInvalidDecl();
655 }
656}
657
Chris Lattner3d1cee32008-04-08 05:04:30 +0000658/// CheckCXXDefaultArguments - Verify that the default arguments for a
659/// function declaration are well-formed according to C++
660/// [dcl.fct.default].
661void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
662 unsigned NumParams = FD->getNumParams();
663 unsigned p;
664
665 // Find first parameter with a default argument
666 for (p = 0; p < NumParams; ++p) {
667 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000668 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000669 break;
670 }
671
672 // C++ [dcl.fct.default]p4:
673 // In a given function declaration, all parameters
674 // subsequent to a parameter with a default argument shall
675 // have default arguments supplied in this or previous
676 // declarations. A default argument shall not be redefined
677 // by a later declaration (not even to the same value).
678 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000679 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000680 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000681 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000682 if (Param->isInvalidDecl())
683 /* We already complained about this parameter. */;
684 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000685 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000686 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000687 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000688 else
Mike Stump1eb44332009-09-09 15:08:12 +0000689 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000690 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Chris Lattner3d1cee32008-04-08 05:04:30 +0000692 LastMissingDefaultArg = p;
693 }
694 }
695
696 if (LastMissingDefaultArg > 0) {
697 // Some default arguments were missing. Clear out all of the
698 // default arguments up to (and including) the last missing
699 // default argument, so that we leave the function parameters
700 // in a semantically valid state.
701 for (p = 0; p <= LastMissingDefaultArg; ++p) {
702 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000703 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000704 Param->setDefaultArg(0);
705 }
706 }
707 }
708}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000709
Richard Smith9f569cc2011-10-01 02:31:28 +0000710// CheckConstexprParameterTypes - Check whether a function's parameter types
711// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000712// diagnostic and return false.
713static bool CheckConstexprParameterTypes(Sema &SemaRef,
714 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000715 unsigned ArgIndex = 0;
716 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
717 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
718 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
719 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
720 SourceLocation ParamLoc = PD->getLocation();
721 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000722 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000723 diag::err_constexpr_non_literal_param,
724 ArgIndex+1, PD->getSourceRange(),
725 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000726 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000727 }
Joao Matos17d35c32012-08-31 22:18:20 +0000728 return true;
729}
730
731/// \brief Get diagnostic %select index for tag kind for
732/// record diagnostic message.
733/// WARNING: Indexes apply to particular diagnostics only!
734///
735/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000736static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000737 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000738 case TTK_Struct: return 0;
739 case TTK_Interface: return 1;
740 case TTK_Class: return 2;
741 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000742 }
Joao Matos17d35c32012-08-31 22:18:20 +0000743}
744
745// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
746// the requirements of a constexpr function definition or a constexpr
747// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000748// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000749//
Richard Smith86c3ae42012-02-13 03:54:03 +0000750// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
751bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000752 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
753 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000754 // C++11 [dcl.constexpr]p4:
755 // The definition of a constexpr constructor shall satisfy the following
756 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000757 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000758 const CXXRecordDecl *RD = MD->getParent();
759 if (RD->getNumVBases()) {
760 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
761 << isa<CXXConstructorDecl>(NewFD)
762 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
763 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
764 E = RD->vbases_end(); I != E; ++I)
765 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000766 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 return false;
768 }
Richard Smith35340502012-01-13 04:54:00 +0000769 }
770
771 if (!isa<CXXConstructorDecl>(NewFD)) {
772 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000773 // The definition of a constexpr function shall satisfy the following
774 // constraints:
775 // - it shall not be virtual;
776 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
777 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000778 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000779
Richard Smith86c3ae42012-02-13 03:54:03 +0000780 // If it's not obvious why this function is virtual, find an overridden
781 // function which uses the 'virtual' keyword.
782 const CXXMethodDecl *WrittenVirtual = Method;
783 while (!WrittenVirtual->isVirtualAsWritten())
784 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
785 if (WrittenVirtual != Method)
786 Diag(WrittenVirtual->getLocation(),
787 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000788 return false;
789 }
790
791 // - its return type shall be a literal type;
792 QualType RT = NewFD->getResultType();
793 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000794 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000795 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000797 }
798
Richard Smith35340502012-01-13 04:54:00 +0000799 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000800 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000801 return false;
802
Richard Smith9f569cc2011-10-01 02:31:28 +0000803 return true;
804}
805
806/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000807/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000808///
Richard Smitha10b9782013-04-22 15:31:51 +0000809/// \return true if the body is OK (maybe only as an extension), false if we
810/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000811static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000812 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
813 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000814 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
815 // contain only
816 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
817 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
818 switch ((*DclIt)->getKind()) {
819 case Decl::StaticAssert:
820 case Decl::Using:
821 case Decl::UsingShadow:
822 case Decl::UsingDirective:
823 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000824 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 // - static_assert-declarations
826 // - using-declarations,
827 // - using-directives,
828 continue;
829
830 case Decl::Typedef:
831 case Decl::TypeAlias: {
832 // - typedef declarations and alias-declarations that do not define
833 // classes or enumerations,
834 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
835 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
836 // Don't allow variably-modified types in constexpr functions.
837 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
838 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
839 << TL.getSourceRange() << TL.getType()
840 << isa<CXXConstructorDecl>(Dcl);
841 return false;
842 }
843 continue;
844 }
845
846 case Decl::Enum:
847 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000848 // C++1y allows types to be defined, not just declared.
849 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
850 SemaRef.Diag(DS->getLocStart(),
851 SemaRef.getLangOpts().CPlusPlus1y
852 ? diag::warn_cxx11_compat_constexpr_type_definition
853 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000854 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000855 continue;
856
Richard Smitha10b9782013-04-22 15:31:51 +0000857 case Decl::EnumConstant:
858 case Decl::IndirectField:
859 case Decl::ParmVar:
860 // These can only appear with other declarations which are banned in
861 // C++11 and permitted in C++1y, so ignore them.
862 continue;
863
864 case Decl::Var: {
865 // C++1y [dcl.constexpr]p3 allows anything except:
866 // a definition of a variable of non-literal type or of static or
867 // thread storage duration or for which no initialization is performed.
868 VarDecl *VD = cast<VarDecl>(*DclIt);
869 if (VD->isThisDeclarationADefinition()) {
870 if (VD->isStaticLocal()) {
871 SemaRef.Diag(VD->getLocation(),
872 diag::err_constexpr_local_var_static)
873 << isa<CXXConstructorDecl>(Dcl)
874 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
875 return false;
876 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000877 if (!VD->getType()->isDependentType() &&
878 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000879 VD->getLocation(), VD->getType(),
880 diag::err_constexpr_local_var_non_literal_type,
881 isa<CXXConstructorDecl>(Dcl)))
882 return false;
883 if (!VD->hasInit()) {
884 SemaRef.Diag(VD->getLocation(),
885 diag::err_constexpr_local_var_no_init)
886 << isa<CXXConstructorDecl>(Dcl);
887 return false;
888 }
889 }
890 SemaRef.Diag(VD->getLocation(),
891 SemaRef.getLangOpts().CPlusPlus1y
892 ? diag::warn_cxx11_compat_constexpr_local_var
893 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000894 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000895 continue;
896 }
897
898 case Decl::NamespaceAlias:
899 case Decl::Function:
900 // These are disallowed in C++11 and permitted in C++1y. Allow them
901 // everywhere as an extension.
902 if (!Cxx1yLoc.isValid())
903 Cxx1yLoc = DS->getLocStart();
904 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000905
906 default:
907 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
908 << isa<CXXConstructorDecl>(Dcl);
909 return false;
910 }
911 }
912
913 return true;
914}
915
916/// Check that the given field is initialized within a constexpr constructor.
917///
918/// \param Dcl The constexpr constructor being checked.
919/// \param Field The field being checked. This may be a member of an anonymous
920/// struct or union nested within the class being checked.
921/// \param Inits All declarations, including anonymous struct/union members and
922/// indirect members, for which any initialization was provided.
923/// \param Diagnosed Set to true if an error is produced.
924static void CheckConstexprCtorInitializer(Sema &SemaRef,
925 const FunctionDecl *Dcl,
926 FieldDecl *Field,
927 llvm::SmallSet<Decl*, 16> &Inits,
928 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000929 if (Field->isInvalidDecl())
930 return;
931
Douglas Gregord61db332011-10-10 17:22:13 +0000932 if (Field->isUnnamedBitfield())
933 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000934
935 if (Field->isAnonymousStructOrUnion() &&
936 Field->getType()->getAsCXXRecordDecl()->isEmpty())
937 return;
938
Richard Smith9f569cc2011-10-01 02:31:28 +0000939 if (!Inits.count(Field)) {
940 if (!Diagnosed) {
941 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
942 Diagnosed = true;
943 }
944 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
945 } else if (Field->isAnonymousStructOrUnion()) {
946 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
947 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
948 I != E; ++I)
949 // If an anonymous union contains an anonymous struct of which any member
950 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000951 if (!RD->isUnion() || Inits.count(*I))
952 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000953 }
954}
955
Richard Smitha10b9782013-04-22 15:31:51 +0000956/// Check the provided statement is allowed in a constexpr function
957/// definition.
958static bool
959CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000960 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000961 SourceLocation &Cxx1yLoc) {
962 // - its function-body shall be [...] a compound-statement that contains only
963 switch (S->getStmtClass()) {
964 case Stmt::NullStmtClass:
965 // - null statements,
966 return true;
967
968 case Stmt::DeclStmtClass:
969 // - static_assert-declarations
970 // - using-declarations,
971 // - using-directives,
972 // - typedef declarations and alias-declarations that do not define
973 // classes or enumerations,
974 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
975 return false;
976 return true;
977
978 case Stmt::ReturnStmtClass:
979 // - and exactly one return statement;
980 if (isa<CXXConstructorDecl>(Dcl)) {
981 // C++1y allows return statements in constexpr constructors.
982 if (!Cxx1yLoc.isValid())
983 Cxx1yLoc = S->getLocStart();
984 return true;
985 }
986
987 ReturnStmts.push_back(S->getLocStart());
988 return true;
989
990 case Stmt::CompoundStmtClass: {
991 // C++1y allows compound-statements.
992 if (!Cxx1yLoc.isValid())
993 Cxx1yLoc = S->getLocStart();
994
995 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
996 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
997 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
998 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
999 Cxx1yLoc))
1000 return false;
1001 }
1002 return true;
1003 }
1004
1005 case Stmt::AttributedStmtClass:
1006 if (!Cxx1yLoc.isValid())
1007 Cxx1yLoc = S->getLocStart();
1008 return true;
1009
1010 case Stmt::IfStmtClass: {
1011 // C++1y allows if-statements.
1012 if (!Cxx1yLoc.isValid())
1013 Cxx1yLoc = S->getLocStart();
1014
1015 IfStmt *If = cast<IfStmt>(S);
1016 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1017 Cxx1yLoc))
1018 return false;
1019 if (If->getElse() &&
1020 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1021 Cxx1yLoc))
1022 return false;
1023 return true;
1024 }
1025
1026 case Stmt::WhileStmtClass:
1027 case Stmt::DoStmtClass:
1028 case Stmt::ForStmtClass:
1029 case Stmt::CXXForRangeStmtClass:
1030 case Stmt::ContinueStmtClass:
1031 // C++1y allows all of these. We don't allow them as extensions in C++11,
1032 // because they don't make sense without variable mutation.
1033 if (!SemaRef.getLangOpts().CPlusPlus1y)
1034 break;
1035 if (!Cxx1yLoc.isValid())
1036 Cxx1yLoc = S->getLocStart();
1037 for (Stmt::child_range Children = S->children(); Children; ++Children)
1038 if (*Children &&
1039 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1040 Cxx1yLoc))
1041 return false;
1042 return true;
1043
1044 case Stmt::SwitchStmtClass:
1045 case Stmt::CaseStmtClass:
1046 case Stmt::DefaultStmtClass:
1047 case Stmt::BreakStmtClass:
1048 // C++1y allows switch-statements, and since they don't need variable
1049 // mutation, we can reasonably allow them in C++11 as an extension.
1050 if (!Cxx1yLoc.isValid())
1051 Cxx1yLoc = S->getLocStart();
1052 for (Stmt::child_range Children = S->children(); Children; ++Children)
1053 if (*Children &&
1054 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1055 Cxx1yLoc))
1056 return false;
1057 return true;
1058
1059 default:
1060 if (!isa<Expr>(S))
1061 break;
1062
1063 // C++1y allows expression-statements.
1064 if (!Cxx1yLoc.isValid())
1065 Cxx1yLoc = S->getLocStart();
1066 return true;
1067 }
1068
1069 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1070 << isa<CXXConstructorDecl>(Dcl);
1071 return false;
1072}
1073
Richard Smith9f569cc2011-10-01 02:31:28 +00001074/// Check the body for the given constexpr function declaration only contains
1075/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1076///
1077/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001078bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001079 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001080 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 // The definition of a constexpr function shall satisfy the following
1082 // constraints: [...]
1083 // - its function-body shall be = delete, = default, or a
1084 // compound-statement
1085 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001086 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001087 // In the definition of a constexpr constructor, [...]
1088 // - its function-body shall not be a function-try-block;
1089 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1090 << isa<CXXConstructorDecl>(Dcl);
1091 return false;
1092 }
1093
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001094 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001095
1096 // - its function-body shall be [...] a compound-statement that contains only
1097 // [... list of cases ...]
1098 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1099 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001100 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1101 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001102 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1103 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001104 }
1105
Richard Smitha10b9782013-04-22 15:31:51 +00001106 if (Cxx1yLoc.isValid())
1107 Diag(Cxx1yLoc,
1108 getLangOpts().CPlusPlus1y
1109 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1110 : diag::ext_constexpr_body_invalid_stmt)
1111 << isa<CXXConstructorDecl>(Dcl);
1112
Richard Smith9f569cc2011-10-01 02:31:28 +00001113 if (const CXXConstructorDecl *Constructor
1114 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1115 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001116 // DR1359:
1117 // - every non-variant non-static data member and base class sub-object
1118 // shall be initialized;
1119 // - if the class is a non-empty union, or for each non-empty anonymous
1120 // union member of a non-union class, exactly one non-static data member
1121 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001122 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001123 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001124 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1125 return false;
1126 }
Richard Smith6e433752011-10-10 16:38:04 +00001127 } else if (!Constructor->isDependentContext() &&
1128 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001129 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1130
1131 // Skip detailed checking if we have enough initializers, and we would
1132 // allow at most one initializer per member.
1133 bool AnyAnonStructUnionMembers = false;
1134 unsigned Fields = 0;
1135 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1136 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001137 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001138 AnyAnonStructUnionMembers = true;
1139 break;
1140 }
1141 }
1142 if (AnyAnonStructUnionMembers ||
1143 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1144 // Check initialization of non-static data members. Base classes are
1145 // always initialized so do not need to be checked. Dependent bases
1146 // might not have initializers in the member initializer list.
1147 llvm::SmallSet<Decl*, 16> Inits;
1148 for (CXXConstructorDecl::init_const_iterator
1149 I = Constructor->init_begin(), E = Constructor->init_end();
1150 I != E; ++I) {
1151 if (FieldDecl *FD = (*I)->getMember())
1152 Inits.insert(FD);
1153 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1154 Inits.insert(ID->chain_begin(), ID->chain_end());
1155 }
1156
1157 bool Diagnosed = false;
1158 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1159 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001160 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001161 if (Diagnosed)
1162 return false;
1163 }
1164 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001165 } else {
1166 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001167 // C++1y doesn't require constexpr functions to contain a 'return'
1168 // statement. We still do, unless the return type is void, because
1169 // otherwise if there's no return statement, the function cannot
1170 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001171 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001172 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001173 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1174 : diag::err_constexpr_body_no_return);
1175 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001176 }
1177 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001178 Diag(ReturnStmts.back(),
1179 getLangOpts().CPlusPlus1y
1180 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1181 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001182 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1183 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001184 }
1185 }
1186
Richard Smith5ba73e12012-02-04 00:33:54 +00001187 // C++11 [dcl.constexpr]p5:
1188 // if no function argument values exist such that the function invocation
1189 // substitution would produce a constant expression, the program is
1190 // ill-formed; no diagnostic required.
1191 // C++11 [dcl.constexpr]p3:
1192 // - every constructor call and implicit conversion used in initializing the
1193 // return value shall be one of those allowed in a constant expression.
1194 // C++11 [dcl.constexpr]p4:
1195 // - every constructor involved in initializing non-static data members and
1196 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001197 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001198 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001199 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001200 << isa<CXXConstructorDecl>(Dcl);
1201 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1202 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001203 // Don't return false here: we allow this for compatibility in
1204 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001205 }
1206
Richard Smith9f569cc2011-10-01 02:31:28 +00001207 return true;
1208}
1209
Douglas Gregorb48fe382008-10-31 09:07:45 +00001210/// isCurrentClassName - Determine whether the identifier II is the
1211/// name of the class type currently being defined. In the case of
1212/// nested classes, this will only return true if II is the name of
1213/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001214bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1215 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001216 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001217
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001218 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001219 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001220 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001221 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1222 } else
1223 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1224
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001225 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001226 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001227 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001228}
1229
Richard Smithb79b17b2013-10-15 00:00:26 +00001230/// \brief Determine whether the identifier II is a typo for the name of
1231/// the class type currently being defined. If so, update it to the identifier
1232/// that should have been used.
1233bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1234 assert(getLangOpts().CPlusPlus && "No class names in C!");
1235
1236 if (!getLangOpts().SpellChecking)
1237 return false;
1238
1239 CXXRecordDecl *CurDecl;
1240 if (SS && SS->isSet() && !SS->isInvalid()) {
1241 DeclContext *DC = computeDeclContext(*SS, true);
1242 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1243 } else
1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1245
1246 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1247 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1248 < II->getLength()) {
1249 II = CurDecl->getIdentifier();
1250 return true;
1251 }
1252
1253 return false;
1254}
1255
Douglas Gregor229d47a2012-11-10 07:24:09 +00001256/// \brief Determine whether the given class is a base class of the given
1257/// class, including looking at dependent bases.
1258static bool findCircularInheritance(const CXXRecordDecl *Class,
1259 const CXXRecordDecl *Current) {
1260 SmallVector<const CXXRecordDecl*, 8> Queue;
1261
1262 Class = Class->getCanonicalDecl();
1263 while (true) {
1264 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1265 E = Current->bases_end();
1266 I != E; ++I) {
1267 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1268 if (!Base)
1269 continue;
1270
1271 Base = Base->getDefinition();
1272 if (!Base)
1273 continue;
1274
1275 if (Base->getCanonicalDecl() == Class)
1276 return true;
1277
1278 Queue.push_back(Base);
1279 }
1280
1281 if (Queue.empty())
1282 return false;
1283
Robert Wilhelm344472e2013-08-23 16:11:15 +00001284 Current = Queue.pop_back_val();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001285 }
1286
1287 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001288}
1289
Mike Stump1eb44332009-09-09 15:08:12 +00001290/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001291///
1292/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1293/// and returns NULL otherwise.
1294CXXBaseSpecifier *
1295Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1296 SourceRange SpecifierRange,
1297 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001298 TypeSourceInfo *TInfo,
1299 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001300 QualType BaseType = TInfo->getType();
1301
Douglas Gregor2943aed2009-03-03 04:44:36 +00001302 // C++ [class.union]p1:
1303 // A union shall not have base classes.
1304 if (Class->isUnion()) {
1305 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1306 << SpecifierRange;
1307 return 0;
1308 }
1309
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001310 if (EllipsisLoc.isValid() &&
1311 !TInfo->getType()->containsUnexpandedParameterPack()) {
1312 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1313 << TInfo->getTypeLoc().getSourceRange();
1314 EllipsisLoc = SourceLocation();
1315 }
Douglas Gregord777e282012-11-10 01:18:17 +00001316
1317 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1318
1319 if (BaseType->isDependentType()) {
1320 // Make sure that we don't have circular inheritance among our dependent
1321 // bases. For non-dependent bases, the check for completeness below handles
1322 // this.
1323 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1324 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1325 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001326 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001327 Diag(BaseLoc, diag::err_circular_inheritance)
1328 << BaseType << Context.getTypeDeclType(Class);
1329
1330 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1331 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1332 << BaseType;
1333
1334 return 0;
1335 }
1336 }
1337
Mike Stump1eb44332009-09-09 15:08:12 +00001338 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001339 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001340 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001341 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001342
1343 // Base specifiers must be record types.
1344 if (!BaseType->isRecordType()) {
1345 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1346 return 0;
1347 }
1348
1349 // C++ [class.union]p1:
1350 // A union shall not be used as a base class.
1351 if (BaseType->isUnionType()) {
1352 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1353 return 0;
1354 }
1355
1356 // C++ [class.derived]p2:
1357 // The class-name in a base-specifier shall not be an incompletely
1358 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001359 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001360 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001361 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001362 return 0;
John McCall572fc622010-08-17 07:23:57 +00001363 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001364
Eli Friedman1d954f62009-08-15 21:55:26 +00001365 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001366 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001367 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001368 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001369 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001370 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001371 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001372
Anders Carlsson1d209272011-03-25 14:55:14 +00001373 // C++ [class]p3:
1374 // If a class is marked final and it appears as a base-type-specifier in
1375 // base-clause, the program is ill-formed.
David Majnemer7121bdb2013-10-18 00:33:31 +00001376 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001377 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemer7121bdb2013-10-18 00:33:31 +00001378 << CXXBaseDecl->getDeclName()
1379 << FA->isSpelledAsSealed();
Anders Carlssondfc2f102011-01-22 17:51:53 +00001380 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1381 << CXXBaseDecl->getDeclName();
1382 return 0;
1383 }
1384
John McCall572fc622010-08-17 07:23:57 +00001385 if (BaseDecl->isInvalidDecl())
1386 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001387
1388 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001389 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001390 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001391 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001392}
1393
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001394/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1395/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001396/// example:
1397/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001398/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001399BaseResult
John McCalld226f652010-08-21 09:40:31 +00001400Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001401 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001402 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001403 ParsedType basetype, SourceLocation BaseLoc,
1404 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001405 if (!classdecl)
1406 return true;
1407
Douglas Gregor40808ce2009-03-09 23:48:35 +00001408 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001409 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001410 if (!Class)
1411 return true;
1412
Richard Smith05321402013-02-19 23:47:15 +00001413 // We do not support any C++11 attributes on base-specifiers yet.
1414 // Diagnose any attributes we see.
1415 if (!Attributes.empty()) {
1416 for (AttributeList *Attr = Attributes.getList(); Attr;
1417 Attr = Attr->getNext()) {
1418 if (Attr->isInvalid() ||
1419 Attr->getKind() == AttributeList::IgnoredAttribute)
1420 continue;
1421 Diag(Attr->getLoc(),
1422 Attr->getKind() == AttributeList::UnknownAttribute
1423 ? diag::warn_unknown_attribute_ignored
1424 : diag::err_base_specifier_attribute)
1425 << Attr->getName();
1426 }
1427 }
1428
Nick Lewycky56062202010-07-26 16:56:01 +00001429 TypeSourceInfo *TInfo = 0;
1430 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001431
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001432 if (EllipsisLoc.isInvalid() &&
1433 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001434 UPPC_BaseType))
1435 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001436
Douglas Gregor2943aed2009-03-03 04:44:36 +00001437 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001438 Virtual, Access, TInfo,
1439 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001440 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001441 else
1442 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Douglas Gregor2943aed2009-03-03 04:44:36 +00001444 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001445}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001446
Douglas Gregor2943aed2009-03-03 04:44:36 +00001447/// \brief Performs the actual work of attaching the given base class
1448/// specifiers to a C++ class.
1449bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1450 unsigned NumBases) {
1451 if (NumBases == 0)
1452 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001453
1454 // Used to keep track of which base types we have already seen, so
1455 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001456 // that the key is always the unqualified canonical type of the base
1457 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001458 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1459
1460 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001461 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001462 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001463 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001464 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001465 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001466 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001467
1468 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1469 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001470 // C++ [class.mi]p3:
1471 // A class shall not be specified as a direct base class of a
1472 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001473 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001474 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001475 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001476 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001477
1478 // Delete the duplicate base class specifier; we're going to
1479 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001480 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001481
1482 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001483 } else {
1484 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001485 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001486 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001487 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1488 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1489 if (Class->isInterface() &&
1490 (!RD->isInterface() ||
1491 KnownBase->getAccessSpecifier() != AS_public)) {
1492 // The Microsoft extension __interface does not permit bases that
1493 // are not themselves public interfaces.
1494 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1495 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1496 << RD->getSourceRange();
1497 Invalid = true;
1498 }
1499 if (RD->hasAttr<WeakAttr>())
1500 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1501 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001502 }
1503 }
1504
1505 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001506 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001507
1508 // Delete the remaining (good) base class specifiers, since their
1509 // data has been copied into the CXXRecordDecl.
1510 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001511 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001512
1513 return Invalid;
1514}
1515
1516/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1517/// class, after checking whether there are any duplicate base
1518/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001519void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001520 unsigned NumBases) {
1521 if (!ClassDecl || !Bases || !NumBases)
1522 return;
1523
1524 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001525 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001526}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001527
Douglas Gregora8f32e02009-10-06 17:59:45 +00001528/// \brief Determine whether the type \p Derived is a C++ class that is
1529/// derived from the type \p Base.
1530bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001531 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001532 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001533
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001534 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001535 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001536 return false;
1537
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001538 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001539 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001540 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001541
1542 // If either the base or the derived type is invalid, don't try to
1543 // check whether one is derived from the other.
1544 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1545 return false;
1546
John McCall86ff3082010-02-04 22:26:26 +00001547 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1548 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001549}
1550
1551/// \brief Determine whether the type \p Derived is a C++ class that is
1552/// derived from the type \p Base.
1553bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001554 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001555 return false;
1556
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001557 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001558 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001559 return false;
1560
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001561 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001562 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001563 return false;
1564
Douglas Gregora8f32e02009-10-06 17:59:45 +00001565 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1566}
1567
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001568void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001569 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001570 assert(BasePathArray.empty() && "Base path array must be empty!");
1571 assert(Paths.isRecordingPaths() && "Must record paths!");
1572
1573 const CXXBasePath &Path = Paths.front();
1574
1575 // We first go backward and check if we have a virtual base.
1576 // FIXME: It would be better if CXXBasePath had the base specifier for
1577 // the nearest virtual base.
1578 unsigned Start = 0;
1579 for (unsigned I = Path.size(); I != 0; --I) {
1580 if (Path[I - 1].Base->isVirtual()) {
1581 Start = I - 1;
1582 break;
1583 }
1584 }
1585
1586 // Now add all bases.
1587 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001588 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001589}
1590
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001591/// \brief Determine whether the given base path includes a virtual
1592/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001593bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1594 for (CXXCastPath::const_iterator B = BasePath.begin(),
1595 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001596 B != BEnd; ++B)
1597 if ((*B)->isVirtual())
1598 return true;
1599
1600 return false;
1601}
1602
Douglas Gregora8f32e02009-10-06 17:59:45 +00001603/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1604/// conversion (where Derived and Base are class types) is
1605/// well-formed, meaning that the conversion is unambiguous (and
1606/// that all of the base classes are accessible). Returns true
1607/// and emits a diagnostic if the code is ill-formed, returns false
1608/// otherwise. Loc is the location where this routine should point to
1609/// if there is an error, and Range is the source range to highlight
1610/// if there is an error.
1611bool
1612Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001613 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001614 unsigned AmbigiousBaseConvID,
1615 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001616 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001617 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001618 // First, determine whether the path from Derived to Base is
1619 // ambiguous. This is slightly more expensive than checking whether
1620 // the Derived to Base conversion exists, because here we need to
1621 // explore multiple paths to determine if there is an ambiguity.
1622 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1623 /*DetectVirtual=*/false);
1624 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1625 assert(DerivationOkay &&
1626 "Can only be used with a derived-to-base conversion");
1627 (void)DerivationOkay;
1628
1629 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001630 if (InaccessibleBaseID) {
1631 // Check that the base class can be accessed.
1632 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1633 InaccessibleBaseID)) {
1634 case AR_inaccessible:
1635 return true;
1636 case AR_accessible:
1637 case AR_dependent:
1638 case AR_delayed:
1639 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001640 }
John McCall6b2accb2010-02-10 09:31:12 +00001641 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001642
1643 // Build a base path if necessary.
1644 if (BasePath)
1645 BuildBasePathArray(Paths, *BasePath);
1646 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001647 }
1648
David Majnemer2f686692013-06-22 06:43:58 +00001649 if (AmbigiousBaseConvID) {
1650 // We know that the derived-to-base conversion is ambiguous, and
1651 // we're going to produce a diagnostic. Perform the derived-to-base
1652 // search just one more time to compute all of the possible paths so
1653 // that we can print them out. This is more expensive than any of
1654 // the previous derived-to-base checks we've done, but at this point
1655 // performance isn't as much of an issue.
1656 Paths.clear();
1657 Paths.setRecordingPaths(true);
1658 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1659 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1660 (void)StillOkay;
1661
1662 // Build up a textual representation of the ambiguous paths, e.g.,
1663 // D -> B -> A, that will be used to illustrate the ambiguous
1664 // conversions in the diagnostic. We only print one of the paths
1665 // to each base class subobject.
1666 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1667
1668 Diag(Loc, AmbigiousBaseConvID)
1669 << Derived << Base << PathDisplayStr << Range << Name;
1670 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001671 return true;
1672}
1673
1674bool
1675Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001676 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001677 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001678 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001679 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001680 IgnoreAccess ? 0
1681 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001682 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001683 Loc, Range, DeclarationName(),
1684 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001685}
1686
1687
1688/// @brief Builds a string representing ambiguous paths from a
1689/// specific derived class to different subobjects of the same base
1690/// class.
1691///
1692/// This function builds a string that can be used in error messages
1693/// to show the different paths that one can take through the
1694/// inheritance hierarchy to go from the derived class to different
1695/// subobjects of a base class. The result looks something like this:
1696/// @code
1697/// struct D -> struct B -> struct A
1698/// struct D -> struct C -> struct A
1699/// @endcode
1700std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1701 std::string PathDisplayStr;
1702 std::set<unsigned> DisplayedPaths;
1703 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1704 Path != Paths.end(); ++Path) {
1705 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1706 // We haven't displayed a path to this particular base
1707 // class subobject yet.
1708 PathDisplayStr += "\n ";
1709 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1710 for (CXXBasePath::const_iterator Element = Path->begin();
1711 Element != Path->end(); ++Element)
1712 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1713 }
1714 }
1715
1716 return PathDisplayStr;
1717}
1718
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001719//===----------------------------------------------------------------------===//
1720// C++ class member Handling
1721//===----------------------------------------------------------------------===//
1722
Abramo Bagnara6206d532010-06-05 05:09:32 +00001723/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001724bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1725 SourceLocation ASLoc,
1726 SourceLocation ColonLoc,
1727 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001728 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001729 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001730 ASLoc, ColonLoc);
1731 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001732 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001733}
1734
Richard Smitha4b39652012-08-06 03:25:17 +00001735/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmandae92712013-09-05 23:51:03 +00001736void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001737 if (D->isInvalidDecl())
1738 return;
1739
Eli Friedmandae92712013-09-05 23:51:03 +00001740 // We only care about "override" and "final" declarations.
1741 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1742 return;
Anders Carlsson9e682d92011-01-20 05:57:14 +00001743
Eli Friedmandae92712013-09-05 23:51:03 +00001744 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001745
Eli Friedmandae92712013-09-05 23:51:03 +00001746 // We can't check dependent instance methods.
1747 if (MD && MD->isInstance() &&
1748 (MD->getParent()->hasAnyDependentBases() ||
1749 MD->getType()->isDependentType()))
1750 return;
1751
1752 if (MD && !MD->isVirtual()) {
1753 // If we have a non-virtual method, check if if hides a virtual method.
1754 // (In that case, it's most likely the method has the wrong type.)
1755 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1756 FindHiddenVirtualMethods(MD, OverloadedMethods);
1757
1758 if (!OverloadedMethods.empty()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001759 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1760 Diag(OA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001761 diag::override_keyword_hides_virtual_member_function)
1762 << "override" << (OverloadedMethods.size() > 1);
1763 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001764 Diag(FA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001765 diag::override_keyword_hides_virtual_member_function)
David Majnemer7121bdb2013-10-18 00:33:31 +00001766 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1767 << (OverloadedMethods.size() > 1);
Richard Smitha4b39652012-08-06 03:25:17 +00001768 }
Eli Friedmandae92712013-09-05 23:51:03 +00001769 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1770 MD->setInvalidDecl();
1771 return;
1772 }
1773 // Fall through into the general case diagnostic.
1774 // FIXME: We might want to attempt typo correction here.
1775 }
1776
1777 if (!MD || !MD->isVirtual()) {
1778 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1779 Diag(OA->getLocation(),
1780 diag::override_keyword_only_allowed_on_virtual_member_functions)
1781 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1782 D->dropAttr<OverrideAttr>();
1783 }
1784 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1785 Diag(FA->getLocation(),
1786 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemer7121bdb2013-10-18 00:33:31 +00001787 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1788 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmandae92712013-09-05 23:51:03 +00001789 D->dropAttr<FinalAttr>();
Richard Smitha4b39652012-08-06 03:25:17 +00001790 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001791 return;
1792 }
Richard Smitha4b39652012-08-06 03:25:17 +00001793
Richard Smitha4b39652012-08-06 03:25:17 +00001794 // C++11 [class.virtual]p5:
1795 // If a virtual function is marked with the virt-specifier override and
1796 // does not override a member function of a base class, the program is
1797 // ill-formed.
1798 bool HasOverriddenMethods =
1799 MD->begin_overridden_methods() != MD->end_overridden_methods();
1800 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1801 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1802 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001803}
1804
Richard Smitha4b39652012-08-06 03:25:17 +00001805/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001806/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001807/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001808bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1809 const CXXMethodDecl *Old) {
David Majnemer7121bdb2013-10-18 00:33:31 +00001810 FinalAttr *FA = Old->getAttr<FinalAttr>();
1811 if (!FA)
Anders Carlssonf89e0422011-01-23 21:07:30 +00001812 return false;
1813
1814 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemer7121bdb2013-10-18 00:33:31 +00001815 << New->getDeclName()
1816 << FA->isSpelledAsSealed();
Anders Carlssonf89e0422011-01-23 21:07:30 +00001817 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1818 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001819}
1820
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001821static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001822 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1823 // FIXME: Destruction of ObjC lifetime types has side-effects.
1824 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1825 return !RD->isCompleteDefinition() ||
1826 !RD->hasTrivialDefaultConstructor() ||
1827 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001828 return false;
1829}
1830
John McCall76da55d2013-04-16 07:28:30 +00001831static AttributeList *getMSPropertyAttr(AttributeList *list) {
1832 for (AttributeList* it = list; it != 0; it = it->getNext())
1833 if (it->isDeclspecPropertyAttribute())
1834 return it;
1835 return 0;
1836}
1837
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001838/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1839/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001840/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001841/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1842/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001843NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001844Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001845 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001846 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001847 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001848 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001849 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1850 DeclarationName Name = NameInfo.getName();
1851 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001852
1853 // For anonymous bitfields, the location should point to the type.
1854 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001855 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001856
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001857 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001858
John McCall4bde1e12010-06-04 08:34:12 +00001859 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001860 assert(!DS.isFriendSpecified());
1861
Richard Smith1ab0d902011-06-25 02:28:38 +00001862 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001863
John McCalle402e722012-09-25 07:32:39 +00001864 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1865 // The Microsoft extension __interface only permits public member functions
1866 // and prohibits constructors, destructors, operators, non-public member
1867 // functions, static methods and data members.
1868 unsigned InvalidDecl;
1869 bool ShowDeclName = true;
1870 if (!isFunc)
1871 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1872 else if (AS != AS_public)
1873 InvalidDecl = 2;
1874 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1875 InvalidDecl = 3;
1876 else switch (Name.getNameKind()) {
1877 case DeclarationName::CXXConstructorName:
1878 InvalidDecl = 4;
1879 ShowDeclName = false;
1880 break;
1881
1882 case DeclarationName::CXXDestructorName:
1883 InvalidDecl = 5;
1884 ShowDeclName = false;
1885 break;
1886
1887 case DeclarationName::CXXOperatorName:
1888 case DeclarationName::CXXConversionFunctionName:
1889 InvalidDecl = 6;
1890 break;
1891
1892 default:
1893 InvalidDecl = 0;
1894 break;
1895 }
1896
1897 if (InvalidDecl) {
1898 if (ShowDeclName)
1899 Diag(Loc, diag::err_invalid_member_in_interface)
1900 << (InvalidDecl-1) << Name;
1901 else
1902 Diag(Loc, diag::err_invalid_member_in_interface)
1903 << (InvalidDecl-1) << "";
1904 return 0;
1905 }
1906 }
1907
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001908 // C++ 9.2p6: A member shall not be declared to have automatic storage
1909 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001910 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1911 // data members and cannot be applied to names declared const or static,
1912 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001913 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001914 case DeclSpec::SCS_unspecified:
1915 case DeclSpec::SCS_typedef:
1916 case DeclSpec::SCS_static:
1917 break;
1918 case DeclSpec::SCS_mutable:
1919 if (isFunc) {
1920 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Richard Smithec642442013-04-12 22:46:28 +00001922 // FIXME: It would be nicer if the keyword was ignored only for this
1923 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001924 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001925 }
1926 break;
1927 default:
1928 Diag(DS.getStorageClassSpecLoc(),
1929 diag::err_storageclass_invalid_for_member);
1930 D.getMutableDeclSpec().ClearStorageClassSpecs();
1931 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001932 }
1933
Sebastian Redl669d5d72008-11-14 23:42:31 +00001934 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1935 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001936 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001937
David Blaikie1d87fba2013-01-30 01:22:18 +00001938 if (DS.isConstexprSpecified() && isInstField) {
1939 SemaDiagnosticBuilder B =
1940 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1941 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1942 if (InitStyle == ICIS_NoInit) {
1943 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1944 D.getMutableDeclSpec().ClearConstexprSpec();
1945 const char *PrevSpec;
1946 unsigned DiagID;
1947 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1948 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001949 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001950 assert(!Failed && "Making a constexpr member const shouldn't fail");
1951 } else {
1952 B << 1;
1953 const char *PrevSpec;
1954 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001955 if (D.getMutableDeclSpec().SetStorageClassSpec(
1956 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001957 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001958 "This is the only DeclSpec that should fail to be applied");
1959 B << 1;
1960 } else {
1961 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1962 isInstField = false;
1963 }
1964 }
1965 }
1966
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001967 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001968 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001969 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001970
1971 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001972 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001973 Diag(Loc, diag::err_bad_variable_name)
1974 << Name;
1975 return 0;
1976 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001977
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001978 IdentifierInfo *II = Name.getAsIdentifierInfo();
1979
Douglas Gregorf2503652011-09-21 14:40:46 +00001980 // Member field could not be with "template" keyword.
1981 // So TemplateParameterLists should be empty in this case.
1982 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001983 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001984 if (TemplateParams->size()) {
1985 // There is no such thing as a member field template.
1986 Diag(D.getIdentifierLoc(), diag::err_template_member)
1987 << II
1988 << SourceRange(TemplateParams->getTemplateLoc(),
1989 TemplateParams->getRAngleLoc());
1990 } else {
1991 // There is an extraneous 'template<>' for this member.
1992 Diag(TemplateParams->getTemplateLoc(),
1993 diag::err_template_member_noparams)
1994 << II
1995 << SourceRange(TemplateParams->getTemplateLoc(),
1996 TemplateParams->getRAngleLoc());
1997 }
1998 return 0;
1999 }
2000
Douglas Gregor922fff22010-10-13 22:19:53 +00002001 if (SS.isSet() && !SS.isInvalid()) {
2002 // The user provided a superfluous scope specifier inside a class
2003 // definition:
2004 //
2005 // class X {
2006 // int X::member;
2007 // };
Douglas Gregor69605872012-03-28 16:01:27 +00002008 if (DeclContext *DC = computeDeclContext(SS, false))
2009 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00002010 else
2011 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2012 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00002013
Douglas Gregor922fff22010-10-13 22:19:53 +00002014 SS.clear();
2015 }
Douglas Gregorf2503652011-09-21 14:40:46 +00002016
John McCall76da55d2013-04-16 07:28:30 +00002017 AttributeList *MSPropertyAttr =
2018 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00002019 if (MSPropertyAttr) {
2020 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2021 BitWidth, InitStyle, AS, MSPropertyAttr);
2022 if (!Member)
2023 return 0;
2024 isInstField = false;
2025 } else {
2026 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2027 BitWidth, InitStyle, AS);
2028 assert(Member && "HandleField never returns null");
2029 }
2030 } else {
2031 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2032
2033 Member = HandleDeclarator(S, D, TemplateParameterLists);
2034 if (!Member)
2035 return 0;
2036
2037 // Non-instance-fields can't have a bitfield.
2038 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002039 if (Member->isInvalidDecl()) {
2040 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002041 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002042 // C++ 9.6p3: A bit-field shall not be a static member.
2043 // "static member 'A' cannot be a bit-field"
2044 Diag(Loc, diag::err_static_not_bitfield)
2045 << Name << BitWidth->getSourceRange();
2046 } else if (isa<TypedefDecl>(Member)) {
2047 // "typedef member 'x' cannot be a bit-field"
2048 Diag(Loc, diag::err_typedef_not_bitfield)
2049 << Name << BitWidth->getSourceRange();
2050 } else {
2051 // A function typedef ("typedef int f(); f a;").
2052 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2053 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00002054 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00002055 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00002056 }
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Chris Lattner8b963ef2009-03-05 23:01:03 +00002058 BitWidth = 0;
2059 Member->setInvalidDecl();
2060 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002061
2062 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Larisse Voufoef4579c2013-08-06 01:03:05 +00002064 // If we have declared a member function template or static data member
2065 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002066 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2067 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002068 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2069 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002070 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002071
Richard Smitha4b39652012-08-06 03:25:17 +00002072 if (VS.isOverrideSpecified())
2073 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2074 if (VS.isFinalSpecified())
David Majnemer7121bdb2013-10-18 00:33:31 +00002075 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2076 VS.isFinalSpelledSealed()));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002077
Douglas Gregorf5251602011-03-08 17:10:18 +00002078 if (VS.getLastLocation().isValid()) {
2079 // Update the end location of a method that has a virt-specifiers.
2080 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2081 MD->setRangeEnd(VS.getLastLocation());
2082 }
Richard Smitha4b39652012-08-06 03:25:17 +00002083
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002084 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002085
Douglas Gregor10bd3682008-11-17 22:58:34 +00002086 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002087
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002088 if (isInstField) {
2089 FieldDecl *FD = cast<FieldDecl>(Member);
2090 FieldCollector->Add(FD);
2091
2092 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2093 FD->getLocation())
2094 != DiagnosticsEngine::Ignored) {
2095 // Remember all explicit private FieldDecls that have a name, no side
2096 // effects and are not part of a dependent type declaration.
2097 if (!FD->isImplicit() && FD->getDeclName() &&
2098 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002099 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002100 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002101 !InitializationHasSideEffects(*FD))
2102 UnusedPrivateFields.insert(FD);
2103 }
2104 }
2105
John McCalld226f652010-08-21 09:40:31 +00002106 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002107}
2108
Hans Wennborg471f9852012-09-18 15:58:06 +00002109namespace {
2110 class UninitializedFieldVisitor
2111 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2112 Sema &S;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002113 // If VD is null, this visitor will only update the Decls set.
Hans Wennborg471f9852012-09-18 15:58:06 +00002114 ValueDecl *VD;
Richard Trieufbb08b52013-09-13 03:20:53 +00002115 bool isReferenceType;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002116 // List of Decls to generate a warning on.
2117 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
2118 bool WarnOnSelfReference;
2119 // If non-null, add a note to the warning pointing back to the constructor.
2120 const CXXConstructorDecl *Constructor;
Hans Wennborg471f9852012-09-18 15:58:06 +00002121 public:
2122 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002123 UninitializedFieldVisitor(Sema &S, ValueDecl *VD,
2124 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2125 bool WarnOnSelfReference,
2126 const CXXConstructorDecl *Constructor)
2127 : Inherited(S.Context), S(S), VD(VD), isReferenceType(false), Decls(Decls),
2128 WarnOnSelfReference(WarnOnSelfReference), Constructor(Constructor) {
2129 // When VD is null, this visitor is used to detect initialization of other
2130 // fields.
2131 if (VD) {
2132 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2133 this->VD = IFD->getAnonField();
2134 else
2135 this->VD = VD;
2136 isReferenceType = this->VD->getType()->isReferenceType();
2137 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002138 }
2139
Richard Trieu3ddec882013-09-16 20:46:50 +00002140 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002141 if (!VD)
2142 return;
2143
Richard Trieu3ddec882013-09-16 20:46:50 +00002144 if (CheckReferenceOnly && !isReferenceType)
2145 return;
2146
Richard Trieufbb08b52013-09-13 03:20:53 +00002147 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2148 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002149
Richard Trieufbb08b52013-09-13 03:20:53 +00002150 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2151 // or union.
2152 MemberExpr *FieldME = ME;
2153
2154 Expr *Base = ME;
2155 while (isa<MemberExpr>(Base)) {
2156 ME = cast<MemberExpr>(Base);
2157
2158 if (isa<VarDecl>(ME->getMemberDecl()))
2159 return;
2160
2161 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2162 if (!FD->isAnonymousStructOrUnion())
2163 FieldME = ME;
2164
2165 Base = ME->getBase();
2166 }
2167
Richard Trieu3ddec882013-09-16 20:46:50 +00002168 if (!isa<CXXThisExpr>(Base))
2169 return;
2170
Richard Trieuef8f90c2013-09-20 03:03:06 +00002171 ValueDecl* FoundVD = FieldME->getMemberDecl();
2172
2173 if (VD == FoundVD) {
2174 if (!WarnOnSelfReference)
2175 return;
2176
Richard Trieu3ddec882013-09-16 20:46:50 +00002177 unsigned diag = isReferenceType
Richard Trieufbb08b52013-09-13 03:20:53 +00002178 ? diag::warn_reference_field_is_uninit
2179 : diag::warn_field_is_uninit;
2180 S.Diag(FieldME->getExprLoc(), diag) << VD;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002181 if (Constructor)
2182 S.Diag(Constructor->getLocation(),
2183 diag::note_uninit_in_this_constructor);
2184 return;
2185 }
2186
2187 if (CheckReferenceOnly)
2188 return;
2189
2190 if (Decls.count(FoundVD)) {
2191 S.Diag(FieldME->getExprLoc(), diag::warn_field_is_uninit) << FoundVD;
2192 if (Constructor)
2193 S.Diag(Constructor->getLocation(),
2194 diag::note_uninit_in_this_constructor);
2195
Richard Trieufbb08b52013-09-13 03:20:53 +00002196 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002197 }
2198
2199 void HandleValue(Expr *E) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002200 if (!VD)
2201 return;
2202
Hans Wennborg471f9852012-09-18 15:58:06 +00002203 E = E->IgnoreParens();
2204
2205 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002206 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002207 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002208 }
2209
2210 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2211 HandleValue(CO->getTrueExpr());
2212 HandleValue(CO->getFalseExpr());
2213 return;
2214 }
2215
2216 if (BinaryConditionalOperator *BCO =
2217 dyn_cast<BinaryConditionalOperator>(E)) {
2218 HandleValue(BCO->getCommon());
2219 HandleValue(BCO->getFalseExpr());
2220 return;
2221 }
2222
2223 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2224 switch (BO->getOpcode()) {
2225 default:
2226 return;
2227 case(BO_PtrMemD):
2228 case(BO_PtrMemI):
2229 HandleValue(BO->getLHS());
2230 return;
2231 case(BO_Comma):
2232 HandleValue(BO->getRHS());
2233 return;
2234 }
2235 }
2236 }
2237
Richard Trieufbb08b52013-09-13 03:20:53 +00002238 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002239 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002240
2241 Inherited::VisitMemberExpr(ME);
2242 }
2243
Hans Wennborg471f9852012-09-18 15:58:06 +00002244 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2245 if (E->getCastKind() == CK_LValueToRValue)
2246 HandleValue(E->getSubExpr());
2247
2248 Inherited::VisitImplicitCastExpr(E);
2249 }
2250
Richard Trieufbb08b52013-09-13 03:20:53 +00002251 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002252 if (E->getConstructor()->isCopyConstructor())
Richard Trieufbb08b52013-09-13 03:20:53 +00002253 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2254 if (ICE->getCastKind() == CK_NoOp)
2255 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieu3ddec882013-09-16 20:46:50 +00002256 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002257
2258 Inherited::VisitCXXConstructExpr(E);
2259 }
2260
Hans Wennborg471f9852012-09-18 15:58:06 +00002261 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2262 Expr *Callee = E->getCallee();
2263 if (isa<MemberExpr>(Callee))
2264 HandleValue(Callee);
2265
2266 Inherited::VisitCXXMemberCallExpr(E);
2267 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002268
2269 void VisitBinaryOperator(BinaryOperator *E) {
2270 // If a field assignment is detected, remove the field from the
2271 // uninitiailized field set.
2272 if (E->getOpcode() == BO_Assign)
2273 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2274 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2275 Decls.erase(FD);
2276
2277 Inherited::VisitBinaryOperator(E);
2278 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002279 };
Richard Trieuef8f90c2013-09-20 03:03:06 +00002280 static void CheckInitExprContainsUninitializedFields(
2281 Sema &S, Expr *E, ValueDecl *VD, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2282 bool WarnOnSelfReference, const CXXConstructorDecl *Constructor = 0) {
2283 if (Decls.size() == 0 && !WarnOnSelfReference)
2284 return;
2285
Richard Trieufbb08b52013-09-13 03:20:53 +00002286 if (E)
Richard Trieuef8f90c2013-09-20 03:03:06 +00002287 UninitializedFieldVisitor(S, VD, Decls, WarnOnSelfReference, Constructor)
2288 .Visit(E);
Hans Wennborg471f9852012-09-18 15:58:06 +00002289 }
2290} // namespace
2291
Richard Smith7a614d82011-06-11 17:19:42 +00002292/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002293/// in-class initializer for a non-static C++ class member, and after
2294/// instantiating an in-class initializer in a class template. Such actions
2295/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002296void
Richard Smithca523302012-06-10 03:12:00 +00002297Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002298 Expr *InitExpr) {
2299 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002300 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2301 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002302
2303 if (!InitExpr) {
2304 FD->setInvalidDecl();
2305 FD->removeInClassInitializer();
2306 return;
2307 }
2308
Peter Collingbournefef21892011-10-23 18:59:44 +00002309 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2310 FD->setInvalidDecl();
2311 FD->removeInClassInitializer();
2312 return;
2313 }
2314
Richard Smith7a614d82011-06-11 17:19:42 +00002315 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002316 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002317 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002318 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002319 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002320 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002321 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2322 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002323 if (Init.isInvalid()) {
2324 FD->setInvalidDecl();
2325 return;
2326 }
Richard Smith7a614d82011-06-11 17:19:42 +00002327 }
2328
Richard Smith41956372013-01-14 22:39:08 +00002329 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002330 // The initialization of each base and member constitutes a
2331 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002332 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002333 if (Init.isInvalid()) {
2334 FD->setInvalidDecl();
2335 return;
2336 }
2337
2338 InitExpr = Init.release();
2339
2340 FD->setInClassInitializer(InitExpr);
2341}
2342
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002343/// \brief Find the direct and/or virtual base specifiers that
2344/// correspond to the given base type, for use in base initialization
2345/// within a constructor.
2346static bool FindBaseInitializer(Sema &SemaRef,
2347 CXXRecordDecl *ClassDecl,
2348 QualType BaseType,
2349 const CXXBaseSpecifier *&DirectBaseSpec,
2350 const CXXBaseSpecifier *&VirtualBaseSpec) {
2351 // First, check for a direct base class.
2352 DirectBaseSpec = 0;
2353 for (CXXRecordDecl::base_class_const_iterator Base
2354 = ClassDecl->bases_begin();
2355 Base != ClassDecl->bases_end(); ++Base) {
2356 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2357 // We found a direct base of this type. That's what we're
2358 // initializing.
2359 DirectBaseSpec = &*Base;
2360 break;
2361 }
2362 }
2363
2364 // Check for a virtual base class.
2365 // FIXME: We might be able to short-circuit this if we know in advance that
2366 // there are no virtual bases.
2367 VirtualBaseSpec = 0;
2368 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2369 // We haven't found a base yet; search the class hierarchy for a
2370 // virtual base class.
2371 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2372 /*DetectVirtual=*/false);
2373 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2374 BaseType, Paths)) {
2375 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2376 Path != Paths.end(); ++Path) {
2377 if (Path->back().Base->isVirtual()) {
2378 VirtualBaseSpec = Path->back().Base;
2379 break;
2380 }
2381 }
2382 }
2383 }
2384
2385 return DirectBaseSpec || VirtualBaseSpec;
2386}
2387
Sebastian Redl6df65482011-09-24 17:48:25 +00002388/// \brief Handle a C++ member initializer using braced-init-list syntax.
2389MemInitResult
2390Sema::ActOnMemInitializer(Decl *ConstructorD,
2391 Scope *S,
2392 CXXScopeSpec &SS,
2393 IdentifierInfo *MemberOrBase,
2394 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002395 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002396 SourceLocation IdLoc,
2397 Expr *InitList,
2398 SourceLocation EllipsisLoc) {
2399 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002400 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002401 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002402}
2403
2404/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002405MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002406Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002407 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002408 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002409 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002410 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002411 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002412 SourceLocation IdLoc,
2413 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002414 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002415 SourceLocation RParenLoc,
2416 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002417 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002418 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002419 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002420 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002421}
2422
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002423namespace {
2424
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002425// Callback to only accept typo corrections that can be a valid C++ member
2426// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002427class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002428public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002429 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2430 : ClassDecl(ClassDecl) {}
2431
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002432 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002433 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2434 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2435 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002436 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002437 }
2438 return false;
2439 }
2440
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002441private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002442 CXXRecordDecl *ClassDecl;
2443};
2444
2445}
2446
Sebastian Redl6df65482011-09-24 17:48:25 +00002447/// \brief Handle a C++ member initializer.
2448MemInitResult
2449Sema::BuildMemInitializer(Decl *ConstructorD,
2450 Scope *S,
2451 CXXScopeSpec &SS,
2452 IdentifierInfo *MemberOrBase,
2453 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002454 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002455 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002456 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002457 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002458 if (!ConstructorD)
2459 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002460
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002461 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002462
2463 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002464 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002465 if (!Constructor) {
2466 // The user wrote a constructor initializer on a function that is
2467 // not a C++ constructor. Ignore the error for now, because we may
2468 // have more member initializers coming; we'll diagnose it just
2469 // once in ActOnMemInitializers.
2470 return true;
2471 }
2472
2473 CXXRecordDecl *ClassDecl = Constructor->getParent();
2474
2475 // C++ [class.base.init]p2:
2476 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002477 // constructor's class and, if not found in that scope, are looked
2478 // up in the scope containing the constructor's definition.
2479 // [Note: if the constructor's class contains a member with the
2480 // same name as a direct or virtual base class of the class, a
2481 // mem-initializer-id naming the member or base class and composed
2482 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002483 // mem-initializer-id for the hidden base class may be specified
2484 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002485 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002486 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002487 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002488 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002489 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002490 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002491 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2492 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002493 if (EllipsisLoc.isValid())
2494 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002495 << MemberOrBase
2496 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002497
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002498 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002499 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002500 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002501 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002502 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002503 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002504 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002505
2506 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002507 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002508 } else if (DS.getTypeSpecType() == TST_decltype) {
2509 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002510 } else {
2511 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2512 LookupParsedName(R, S, &SS);
2513
2514 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2515 if (!TyD) {
2516 if (R.isAmbiguous()) return true;
2517
John McCallfd225442010-04-09 19:01:14 +00002518 // We don't want access-control diagnostics here.
2519 R.suppressDiagnostics();
2520
Douglas Gregor7a886e12010-01-19 06:46:48 +00002521 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2522 bool NotUnknownSpecialization = false;
2523 DeclContext *DC = computeDeclContext(SS, false);
2524 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2525 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2526
2527 if (!NotUnknownSpecialization) {
2528 // When the scope specifier can refer to a member of an unknown
2529 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002530 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2531 SS.getWithLocInContext(Context),
2532 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002533 if (BaseType.isNull())
2534 return true;
2535
Douglas Gregor7a886e12010-01-19 06:46:48 +00002536 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002537 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002538 }
2539 }
2540
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002541 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002542 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002543 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002544 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002545 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002546 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002547 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002548 // We have found a non-static data member with a similar
2549 // name to what was typed; complain and initialize that
2550 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002551 diagnoseTypo(Corr,
2552 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2553 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002554 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002555 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002556 const CXXBaseSpecifier *DirectBaseSpec;
2557 const CXXBaseSpecifier *VirtualBaseSpec;
2558 if (FindBaseInitializer(*this, ClassDecl,
2559 Context.getTypeDeclType(Type),
2560 DirectBaseSpec, VirtualBaseSpec)) {
2561 // We have found a direct or virtual base class with a
2562 // similar name to what was typed; complain and initialize
2563 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002564 diagnoseTypo(Corr,
2565 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2566 << MemberOrBase << false,
2567 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002568
Richard Smith2d670972013-08-17 00:46:16 +00002569 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2570 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002571 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002572 diag::note_base_class_specified_here)
2573 << BaseSpec->getType()
2574 << BaseSpec->getSourceRange();
2575
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002576 TyD = Type;
2577 }
2578 }
2579 }
2580
Douglas Gregor7a886e12010-01-19 06:46:48 +00002581 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002582 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002583 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002584 return true;
2585 }
John McCall2b194412009-12-21 10:41:20 +00002586 }
2587
Douglas Gregor7a886e12010-01-19 06:46:48 +00002588 if (BaseType.isNull()) {
2589 BaseType = Context.getTypeDeclType(TyD);
2590 if (SS.isSet()) {
2591 NestedNameSpecifier *Qualifier =
2592 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002593
Douglas Gregor7a886e12010-01-19 06:46:48 +00002594 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002595 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002596 }
John McCall2b194412009-12-21 10:41:20 +00002597 }
2598 }
Mike Stump1eb44332009-09-09 15:08:12 +00002599
John McCalla93c9342009-12-07 02:54:59 +00002600 if (!TInfo)
2601 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002602
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002603 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002604}
2605
Chandler Carruth81c64772011-09-03 01:14:15 +00002606/// Checks a member initializer expression for cases where reference (or
2607/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002608static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2609 Expr *Init,
2610 SourceLocation IdLoc) {
2611 QualType MemberTy = Member->getType();
2612
2613 // We only handle pointers and references currently.
2614 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2615 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2616 return;
2617
2618 const bool IsPointer = MemberTy->isPointerType();
2619 if (IsPointer) {
2620 if (const UnaryOperator *Op
2621 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2622 // The only case we're worried about with pointers requires taking the
2623 // address.
2624 if (Op->getOpcode() != UO_AddrOf)
2625 return;
2626
2627 Init = Op->getSubExpr();
2628 } else {
2629 // We only handle address-of expression initializers for pointers.
2630 return;
2631 }
2632 }
2633
Richard Smitha4bb99c2013-06-12 21:51:50 +00002634 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002635 // We only warn when referring to a non-reference parameter declaration.
2636 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2637 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002638 return;
2639
2640 S.Diag(Init->getExprLoc(),
2641 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2642 : diag::warn_bind_ref_member_to_parameter)
2643 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002644 } else {
2645 // Other initializers are fine.
2646 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002647 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002648
2649 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2650 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002651}
2652
John McCallf312b1e2010-08-26 23:41:50 +00002653MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002654Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002655 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002656 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2657 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2658 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002659 "Member must be a FieldDecl or IndirectFieldDecl");
2660
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002661 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002662 return true;
2663
Douglas Gregor464b2f02010-11-05 22:21:31 +00002664 if (Member->isInvalidDecl())
2665 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002666
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002667 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002668 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002669 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002670 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002671 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002672 } else {
2673 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002674 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002675 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002676
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002677 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002678
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002679 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002680 // Can't check initialization for a member of dependent type or when
2681 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002682 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002683 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002684 bool InitList = false;
2685 if (isa<InitListExpr>(Init)) {
2686 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002687 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002688 }
2689
Chandler Carruth894aed92010-12-06 09:23:57 +00002690 // Initialize the member.
2691 InitializedEntity MemberEntity =
2692 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2693 : InitializedEntity::InitializeMember(IndirectMember, 0);
2694 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002695 InitList ? InitializationKind::CreateDirectList(IdLoc)
2696 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2697 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002698
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002699 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2700 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002701 if (MemberInit.isInvalid())
2702 return true;
2703
Richard Smith8a07cd32013-06-12 20:42:33 +00002704 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2705
Richard Smith41956372013-01-14 22:39:08 +00002706 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002707 // The initialization of each base and member constitutes a
2708 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002709 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002710 if (MemberInit.isInvalid())
2711 return true;
2712
Richard Smithc83c2302012-12-19 01:39:02 +00002713 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002714 }
2715
Chandler Carruth894aed92010-12-06 09:23:57 +00002716 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002717 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2718 InitRange.getBegin(), Init,
2719 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002720 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002721 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2722 InitRange.getBegin(), Init,
2723 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002724 }
Eli Friedman59c04372009-07-29 19:44:27 +00002725}
2726
John McCallf312b1e2010-08-26 23:41:50 +00002727MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002728Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002729 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002730 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002731 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002732 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002733 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002734 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002735
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002736 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002737 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002738 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2739 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002740 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002741 }
2742
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002743 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002744 // Initialize the object.
2745 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2746 QualType(ClassDecl->getTypeForDecl(), 0));
2747 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002748 InitList ? InitializationKind::CreateDirectList(NameLoc)
2749 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2750 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002751 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002752 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002753 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002754 if (DelegationInit.isInvalid())
2755 return true;
2756
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002757 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2758 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002759
Richard Smith41956372013-01-14 22:39:08 +00002760 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002761 // The initialization of each base and member constitutes a
2762 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002763 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2764 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002765 if (DelegationInit.isInvalid())
2766 return true;
2767
Eli Friedmand21016f2012-05-19 23:35:23 +00002768 // If we are in a dependent context, template instantiation will
2769 // perform this type-checking again. Just save the arguments that we
2770 // received in a ParenListExpr.
2771 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2772 // of the information that we have about the base
2773 // initializer. However, deconstructing the ASTs is a dicey process,
2774 // and this approach is far more likely to get the corner cases right.
2775 if (CurContext->isDependentContext())
2776 DelegationInit = Owned(Init);
2777
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002778 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002779 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002780 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002781}
2782
2783MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002784Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002785 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002786 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002787 SourceLocation BaseLoc
2788 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002789
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002790 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2791 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2792 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2793
2794 // C++ [class.base.init]p2:
2795 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002796 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002797 // of that class, the mem-initializer is ill-formed. A
2798 // mem-initializer-list can initialize a base class using any
2799 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002800 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002801
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002802 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002803 if (EllipsisLoc.isValid()) {
2804 // This is a pack expansion.
2805 if (!BaseType->containsUnexpandedParameterPack()) {
2806 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002807 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002808
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002809 EllipsisLoc = SourceLocation();
2810 }
2811 } else {
2812 // Check for any unexpanded parameter packs.
2813 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2814 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002815
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002816 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002817 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002818 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002819
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002820 // Check for direct and virtual base classes.
2821 const CXXBaseSpecifier *DirectBaseSpec = 0;
2822 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2823 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002824 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2825 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002826 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002827
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002828 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2829 VirtualBaseSpec);
2830
2831 // C++ [base.class.init]p2:
2832 // Unless the mem-initializer-id names a nonstatic data member of the
2833 // constructor's class or a direct or virtual base of that class, the
2834 // mem-initializer is ill-formed.
2835 if (!DirectBaseSpec && !VirtualBaseSpec) {
2836 // If the class has any dependent bases, then it's possible that
2837 // one of those types will resolve to the same type as
2838 // BaseType. Therefore, just treat this as a dependent base
2839 // class initialization. FIXME: Should we try to check the
2840 // initialization anyway? It seems odd.
2841 if (ClassDecl->hasAnyDependentBases())
2842 Dependent = true;
2843 else
2844 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2845 << BaseType << Context.getTypeDeclType(ClassDecl)
2846 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2847 }
2848 }
2849
2850 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002851 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002852
Sebastian Redl6df65482011-09-24 17:48:25 +00002853 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2854 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002855 InitRange.getBegin(), Init,
2856 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002857 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002858
2859 // C++ [base.class.init]p2:
2860 // If a mem-initializer-id is ambiguous because it designates both
2861 // a direct non-virtual base class and an inherited virtual base
2862 // class, the mem-initializer is ill-formed.
2863 if (DirectBaseSpec && VirtualBaseSpec)
2864 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002865 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002866
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002867 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002868 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002869 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002870
2871 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002872 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002873 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002874 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002875 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002876 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002877 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002878
2879 InitializedEntity BaseEntity =
2880 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2881 InitializationKind Kind =
2882 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2883 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2884 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002885 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2886 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002887 if (BaseInit.isInvalid())
2888 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002889
Richard Smith41956372013-01-14 22:39:08 +00002890 // C++11 [class.base.init]p7:
2891 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002892 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002893 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002894 if (BaseInit.isInvalid())
2895 return true;
2896
2897 // If we are in a dependent context, template instantiation will
2898 // perform this type-checking again. Just save the arguments that we
2899 // received in a ParenListExpr.
2900 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2901 // of the information that we have about the base
2902 // initializer. However, deconstructing the ASTs is a dicey process,
2903 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002904 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002905 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002906
Sean Huntcbb67482011-01-08 20:30:50 +00002907 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002908 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002909 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002910 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002911 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002912}
2913
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002914// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002915static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2916 if (T.isNull()) T = E->getType();
2917 QualType TargetType = SemaRef.BuildReferenceType(
2918 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002919 SourceLocation ExprLoc = E->getLocStart();
2920 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2921 TargetType, ExprLoc);
2922
2923 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2924 SourceRange(ExprLoc, ExprLoc),
2925 E->getSourceRange()).take();
2926}
2927
Anders Carlssone5ef7402010-04-23 03:10:23 +00002928/// ImplicitInitializerKind - How an implicit base or member initializer should
2929/// initialize its base or member.
2930enum ImplicitInitializerKind {
2931 IIK_Default,
2932 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002933 IIK_Move,
2934 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002935};
2936
Anders Carlssondefefd22010-04-23 02:00:02 +00002937static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002938BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002939 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002940 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002941 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002942 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002943 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002944 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2945 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002946
John McCall60d7b3a2010-08-24 06:29:42 +00002947 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002948
2949 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002950 case IIK_Inherit: {
2951 const CXXRecordDecl *Inherited =
2952 Constructor->getInheritedConstructor()->getParent();
2953 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2954 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2955 // C++11 [class.inhctor]p8:
2956 // Each expression in the expression-list is of the form
2957 // static_cast<T&&>(p), where p is the name of the corresponding
2958 // constructor parameter and T is the declared type of p.
2959 SmallVector<Expr*, 16> Args;
2960 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2961 ParmVarDecl *PD = Constructor->getParamDecl(I);
2962 ExprResult ArgExpr =
2963 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2964 VK_LValue, SourceLocation());
2965 if (ArgExpr.isInvalid())
2966 return true;
2967 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2968 }
2969
2970 InitializationKind InitKind = InitializationKind::CreateDirect(
2971 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002972 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002973 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2974 break;
2975 }
2976 }
2977 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002978 case IIK_Default: {
2979 InitializationKind InitKind
2980 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002981 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2982 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002983 break;
2984 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002985
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002986 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002987 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002988 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002989 ParmVarDecl *Param = Constructor->getParamDecl(0);
2990 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002991
Anders Carlssone5ef7402010-04-23 03:10:23 +00002992 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002993 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002994 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002995 Constructor->getLocation(), ParamType,
2996 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002997
Eli Friedman5f2987c2012-02-02 03:46:19 +00002998 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2999
Anders Carlssonc7957502010-04-24 22:02:54 +00003000 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00003001 QualType ArgTy =
3002 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3003 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00003004
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003005 if (Moving) {
3006 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3007 }
3008
John McCallf871d0c2010-08-07 06:22:56 +00003009 CXXCastPath BasePath;
3010 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00003011 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3012 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003013 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003014 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00003015
Anders Carlssone5ef7402010-04-23 03:10:23 +00003016 InitializationKind InitKind
3017 = InitializationKind::CreateDirect(Constructor->getLocation(),
3018 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003019 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3020 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003021 break;
3022 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00003023 }
John McCall9ae2f072010-08-23 23:25:46 +00003024
Douglas Gregor53c374f2010-12-07 00:41:46 +00003025 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00003026 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00003027 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00003028
Anders Carlssondefefd22010-04-23 02:00:02 +00003029 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00003030 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00003031 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3032 SourceLocation()),
3033 BaseSpec->isVirtual(),
3034 SourceLocation(),
3035 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003036 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00003037 SourceLocation());
3038
Anders Carlssondefefd22010-04-23 02:00:02 +00003039 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00003040}
3041
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003042static bool RefersToRValueRef(Expr *MemRef) {
3043 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3044 return Referenced->getType()->isRValueReferenceType();
3045}
3046
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003047static bool
3048BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003049 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003050 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00003051 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003052 if (Field->isInvalidDecl())
3053 return true;
3054
Chandler Carruthf186b542010-06-29 23:50:44 +00003055 SourceLocation Loc = Constructor->getLocation();
3056
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003057 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3058 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003059 ParmVarDecl *Param = Constructor->getParamDecl(0);
3060 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00003061
3062 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003063 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3064 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00003065
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003066 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003067 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003068 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00003069 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003070
Eli Friedman5f2987c2012-02-02 03:46:19 +00003071 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3072
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003073 if (Moving) {
3074 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3075 }
3076
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003077 // Build a reference to this field within the parameter.
3078 CXXScopeSpec SS;
3079 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3080 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003081 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3082 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003083 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00003084 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00003085 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003086 ParamType, Loc,
3087 /*IsArrow=*/false,
3088 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003089 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003090 /*FirstQualifierInScope=*/0,
3091 MemberLookup,
3092 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003093 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003094 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003095
3096 // C++11 [class.copy]p15:
3097 // - if a member m has rvalue reference type T&&, it is direct-initialized
3098 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003099 if (RefersToRValueRef(CtorArg.get())) {
3100 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003101 }
3102
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003103 // When the field we are copying is an array, create index variables for
3104 // each dimension of the array. We use these index variables to subscript
3105 // the source array, and other clients (e.g., CodeGen) will perform the
3106 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003107 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003108 QualType BaseType = Field->getType();
3109 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003110 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003111 while (const ConstantArrayType *Array
3112 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003113 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003114 // Create the iteration variable for this array index.
3115 IdentifierInfo *IterationVarName = 0;
3116 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003117 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003118 llvm::raw_svector_ostream OS(Str);
3119 OS << "__i" << IndexVariables.size();
3120 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3121 }
3122 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003123 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003124 IterationVarName, SizeType,
3125 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003126 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003127 IndexVariables.push_back(IterationVar);
3128
3129 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003130 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003131 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003132 assert(!IterationVarRef.isInvalid() &&
3133 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003134 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3135 assert(!IterationVarRef.isInvalid() &&
3136 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003137
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003138 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003139 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003140 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003141 Loc);
3142 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003143 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003144
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003145 BaseType = Array->getElementType();
3146 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003147
3148 // The array subscript expression is an lvalue, which is wrong for moving.
3149 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003150 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003151
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003152 // Construct the entity that we will be initializing. For an array, this
3153 // will be first element in the array, which may require several levels
3154 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003155 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003156 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003157 if (Indirect)
3158 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3159 else
3160 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003161 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3162 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3163 0,
3164 Entities.back()));
3165
3166 // Direct-initialize to use the copy constructor.
3167 InitializationKind InitKind =
3168 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3169
Sebastian Redl74e611a2011-09-04 18:14:28 +00003170 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003171 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003172
John McCall60d7b3a2010-08-24 06:29:42 +00003173 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003174 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003175 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003176 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003177 if (MemberInit.isInvalid())
3178 return true;
3179
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003180 if (Indirect) {
3181 assert(IndexVariables.size() == 0 &&
3182 "Indirect field improperly initialized");
3183 CXXMemberInit
3184 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3185 Loc, Loc,
3186 MemberInit.takeAs<Expr>(),
3187 Loc);
3188 } else
3189 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3190 Loc, MemberInit.takeAs<Expr>(),
3191 Loc,
3192 IndexVariables.data(),
3193 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003194 return false;
3195 }
3196
Richard Smith07b0fdc2013-03-18 21:12:30 +00003197 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3198 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003199
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003200 QualType FieldBaseElementType =
3201 SemaRef.Context.getBaseElementType(Field->getType());
3202
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003203 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003204 InitializedEntity InitEntity
3205 = Indirect? InitializedEntity::InitializeMember(Indirect)
3206 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003207 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003208 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003209
3210 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3211 ExprResult MemberInit =
3212 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003213
Douglas Gregor53c374f2010-12-07 00:41:46 +00003214 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003215 if (MemberInit.isInvalid())
3216 return true;
3217
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003218 if (Indirect)
3219 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3220 Indirect, Loc,
3221 Loc,
3222 MemberInit.get(),
3223 Loc);
3224 else
3225 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3226 Field, Loc, Loc,
3227 MemberInit.get(),
3228 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003229 return false;
3230 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003231
Sean Hunt1f2f3842011-05-17 00:19:05 +00003232 if (!Field->getParent()->isUnion()) {
3233 if (FieldBaseElementType->isReferenceType()) {
3234 SemaRef.Diag(Constructor->getLocation(),
3235 diag::err_uninitialized_member_in_ctor)
3236 << (int)Constructor->isImplicit()
3237 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3238 << 0 << Field->getDeclName();
3239 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3240 return true;
3241 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003242
Sean Hunt1f2f3842011-05-17 00:19:05 +00003243 if (FieldBaseElementType.isConstQualified()) {
3244 SemaRef.Diag(Constructor->getLocation(),
3245 diag::err_uninitialized_member_in_ctor)
3246 << (int)Constructor->isImplicit()
3247 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3248 << 1 << Field->getDeclName();
3249 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3250 return true;
3251 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003252 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003253
David Blaikie4e4d0842012-03-11 07:00:24 +00003254 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003255 FieldBaseElementType->isObjCRetainableType() &&
3256 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3257 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003258 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003259 // Default-initialize Objective-C pointers to NULL.
3260 CXXMemberInit
3261 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3262 Loc, Loc,
3263 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3264 Loc);
3265 return false;
3266 }
3267
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003268 // Nothing to initialize.
3269 CXXMemberInit = 0;
3270 return false;
3271}
John McCallf1860e52010-05-20 23:23:51 +00003272
3273namespace {
3274struct BaseAndFieldInfo {
3275 Sema &S;
3276 CXXConstructorDecl *Ctor;
3277 bool AnyErrorsInInits;
3278 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003279 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003280 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003281
3282 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3283 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003284 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3285 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003286 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003287 else if (Generated && Ctor->isMoveConstructor())
3288 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003289 else if (Ctor->getInheritedConstructor())
3290 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003291 else
3292 IIK = IIK_Default;
3293 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003294
3295 bool isImplicitCopyOrMove() const {
3296 switch (IIK) {
3297 case IIK_Copy:
3298 case IIK_Move:
3299 return true;
3300
3301 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003302 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003303 return false;
3304 }
David Blaikie30263482012-01-20 21:50:17 +00003305
3306 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003307 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003308
3309 bool addFieldInitializer(CXXCtorInitializer *Init) {
3310 AllToInit.push_back(Init);
3311
3312 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003313 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003314 S.UnusedPrivateFields.remove(Init->getAnyMember());
3315
3316 return false;
3317 }
John McCallf1860e52010-05-20 23:23:51 +00003318};
3319}
3320
Richard Smitha4950662011-09-19 13:34:43 +00003321/// \brief Determine whether the given indirect field declaration is somewhere
3322/// within an anonymous union.
3323static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3324 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3325 CEnd = F->chain_end();
3326 C != CEnd; ++C)
3327 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3328 if (Record->isUnion())
3329 return true;
3330
3331 return false;
3332}
3333
Douglas Gregorddb21472011-11-02 23:04:16 +00003334/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3335/// array type.
3336static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3337 if (T->isIncompleteArrayType())
3338 return true;
3339
3340 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3341 if (!ArrayT->getSize())
3342 return true;
3343
3344 T = ArrayT->getElementType();
3345 }
3346
3347 return false;
3348}
3349
Richard Smith7a614d82011-06-11 17:19:42 +00003350static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003351 FieldDecl *Field,
3352 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003353 if (Field->isInvalidDecl())
3354 return false;
John McCallf1860e52010-05-20 23:23:51 +00003355
Chandler Carruthe861c602010-06-30 02:59:29 +00003356 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003357 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3358 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003359
Richard Smith0b8220a2012-08-07 21:30:42 +00003360 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003361 // has a brace-or-equal-initializer, the entity is initialized as specified
3362 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003363 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003364 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3365 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003366 CXXCtorInitializer *Init;
3367 if (Indirect)
3368 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3369 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003370 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003371 SourceLocation());
3372 else
3373 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3374 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003375 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003376 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003377 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003378 }
3379
Richard Smithc115f632011-09-18 11:14:50 +00003380 // Don't build an implicit initializer for union members if none was
3381 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003382 if (Field->getParent()->isUnion() ||
3383 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003384 return false;
3385
Douglas Gregorddb21472011-11-02 23:04:16 +00003386 // Don't initialize incomplete or zero-length arrays.
3387 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3388 return false;
3389
John McCallf1860e52010-05-20 23:23:51 +00003390 // Don't try to build an implicit initializer if there were semantic
3391 // errors in any of the initializers (and therefore we might be
3392 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003393 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003394 return false;
3395
Sean Huntcbb67482011-01-08 20:30:50 +00003396 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003397 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3398 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003399 return true;
John McCallf1860e52010-05-20 23:23:51 +00003400
Richard Smith0b8220a2012-08-07 21:30:42 +00003401 if (!Init)
3402 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003403
Richard Smith0b8220a2012-08-07 21:30:42 +00003404 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003405}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003406
3407bool
3408Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3409 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003410 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003411 Constructor->setNumCtorInitializers(1);
3412 CXXCtorInitializer **initializer =
3413 new (Context) CXXCtorInitializer*[1];
3414 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3415 Constructor->setCtorInitializers(initializer);
3416
Sean Huntb76af9c2011-05-03 23:05:34 +00003417 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003418 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003419 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3420 }
3421
Sean Huntc1598702011-05-05 00:05:47 +00003422 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003423
Sean Hunt059ce0d2011-05-01 07:04:31 +00003424 return false;
3425}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003426
David Blaikie93c86172013-01-17 05:26:25 +00003427bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3428 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003429 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003430 // Just store the initializers as written, they will be checked during
3431 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003432 if (!Initializers.empty()) {
3433 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003434 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003435 new (Context) CXXCtorInitializer*[Initializers.size()];
3436 memcpy(baseOrMemberInitializers, Initializers.data(),
3437 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003438 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003439 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003440
3441 // Let template instantiation know whether we had errors.
3442 if (AnyErrors)
3443 Constructor->setInvalidDecl();
3444
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003445 return false;
3446 }
3447
John McCallf1860e52010-05-20 23:23:51 +00003448 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003449
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003450 // We need to build the initializer AST according to order of construction
3451 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003452 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003453 if (!ClassDecl)
3454 return true;
3455
Eli Friedman80c30da2009-11-09 19:20:36 +00003456 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003457
David Blaikie93c86172013-01-17 05:26:25 +00003458 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003459 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003460
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003461 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003462 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003463 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003464 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003465 }
3466
Anders Carlsson711f34a2010-04-21 19:52:01 +00003467 // Keep track of the direct virtual bases.
3468 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3469 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3470 E = ClassDecl->bases_end(); I != E; ++I) {
3471 if (I->isVirtual())
3472 DirectVBases.insert(I);
3473 }
3474
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003475 // Push virtual bases before others.
3476 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3477 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3478
Sean Huntcbb67482011-01-08 20:30:50 +00003479 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003480 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003481 // [class.base.init]p7, per DR257:
3482 // A mem-initializer where the mem-initializer-id names a virtual base
3483 // class is ignored during execution of a constructor of any class that
3484 // is not the most derived class.
3485 if (ClassDecl->isAbstract()) {
3486 // FIXME: Provide a fixit to remove the base specifier. This requires
3487 // tracking the location of the associated comma for a base specifier.
3488 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3489 << VBase->getType() << ClassDecl;
3490 DiagnoseAbstractType(ClassDecl);
3491 }
3492
John McCallf1860e52010-05-20 23:23:51 +00003493 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003494 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3495 // [class.base.init]p8, per DR257:
3496 // If a given [...] base class is not named by a mem-initializer-id
3497 // [...] and the entity is not a virtual base class of an abstract
3498 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003499 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003500 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003501 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003502 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003503 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003504 HadError = true;
3505 continue;
3506 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003507
John McCallf1860e52010-05-20 23:23:51 +00003508 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003509 }
3510 }
Mike Stump1eb44332009-09-09 15:08:12 +00003511
John McCallf1860e52010-05-20 23:23:51 +00003512 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003513 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3514 E = ClassDecl->bases_end(); Base != E; ++Base) {
3515 // Virtuals are in the virtual base list and already constructed.
3516 if (Base->isVirtual())
3517 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003518
Sean Huntcbb67482011-01-08 20:30:50 +00003519 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003520 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3521 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003522 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003523 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003524 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003525 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003526 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003527 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003528 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003529 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003530
John McCallf1860e52010-05-20 23:23:51 +00003531 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003532 }
3533 }
Mike Stump1eb44332009-09-09 15:08:12 +00003534
John McCallf1860e52010-05-20 23:23:51 +00003535 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003536 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3537 MemEnd = ClassDecl->decls_end();
3538 Mem != MemEnd; ++Mem) {
3539 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003540 // C++ [class.bit]p2:
3541 // A declaration for a bit-field that omits the identifier declares an
3542 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3543 // initialized.
3544 if (F->isUnnamedBitfield())
3545 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003546
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003547 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003548 // handle anonymous struct/union fields based on their individual
3549 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003550 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003551 continue;
3552
3553 if (CollectFieldInitializer(*this, Info, F))
3554 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003555 continue;
3556 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003557
3558 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003559 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003560 continue;
3561
3562 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3563 if (F->getType()->isIncompleteArrayType()) {
3564 assert(ClassDecl->hasFlexibleArrayMember() &&
3565 "Incomplete array type is not valid");
3566 continue;
3567 }
3568
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003569 // Initialize each field of an anonymous struct individually.
3570 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3571 HadError = true;
3572
3573 continue;
3574 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003575 }
Mike Stump1eb44332009-09-09 15:08:12 +00003576
David Blaikie93c86172013-01-17 05:26:25 +00003577 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003578 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003579 Constructor->setNumCtorInitializers(NumInitializers);
3580 CXXCtorInitializer **baseOrMemberInitializers =
3581 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003582 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003583 NumInitializers * sizeof(CXXCtorInitializer*));
3584 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003585
John McCallef027fe2010-03-16 21:39:52 +00003586 // Constructors implicitly reference the base and member
3587 // destructors.
3588 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3589 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003590 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003591
3592 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003593}
3594
David Blaikieee000bb2013-01-17 08:49:22 +00003595static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003596 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003597 const RecordDecl *RD = RT->getDecl();
3598 if (RD->isAnonymousStructOrUnion()) {
3599 for (RecordDecl::field_iterator Field = RD->field_begin(),
3600 E = RD->field_end(); Field != E; ++Field)
3601 PopulateKeysForFields(*Field, IdealInits);
3602 return;
3603 }
Eli Friedman6347f422009-07-21 19:28:10 +00003604 }
David Blaikieee000bb2013-01-17 08:49:22 +00003605 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003606}
3607
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003608static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3609 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003610}
3611
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003612static const void *GetKeyForMember(ASTContext &Context,
3613 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003614 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003615 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003616
David Blaikieee000bb2013-01-17 08:49:22 +00003617 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003618}
3619
David Blaikie93c86172013-01-17 05:26:25 +00003620static void DiagnoseBaseOrMemInitializerOrder(
3621 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3622 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003623 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003624 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003625
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003626 // Don't check initializers order unless the warning is enabled at the
3627 // location of at least one initializer.
3628 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003629 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003630 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003631 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3632 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003633 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003634 ShouldCheckOrder = true;
3635 break;
3636 }
3637 }
3638 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003639 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003640
John McCalld6ca8da2010-04-10 07:37:23 +00003641 // Build the list of bases and members in the order that they'll
3642 // actually be initialized. The explicit initializers should be in
3643 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003644 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003645
Anders Carlsson071d6102010-04-02 03:38:04 +00003646 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3647
John McCalld6ca8da2010-04-10 07:37:23 +00003648 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003649 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003650 ClassDecl->vbases_begin(),
3651 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003652 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003653
John McCalld6ca8da2010-04-10 07:37:23 +00003654 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003655 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003656 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003657 if (Base->isVirtual())
3658 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003659 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003660 }
Mike Stump1eb44332009-09-09 15:08:12 +00003661
John McCalld6ca8da2010-04-10 07:37:23 +00003662 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003663 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003664 E = ClassDecl->field_end(); Field != E; ++Field) {
3665 if (Field->isUnnamedBitfield())
3666 continue;
3667
David Blaikieee000bb2013-01-17 08:49:22 +00003668 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003669 }
3670
John McCalld6ca8da2010-04-10 07:37:23 +00003671 unsigned NumIdealInits = IdealInitKeys.size();
3672 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003673
Sean Huntcbb67482011-01-08 20:30:50 +00003674 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003675 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003676 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003677 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003678
3679 // Scan forward to try to find this initializer in the idealized
3680 // initializers list.
3681 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3682 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003683 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003684
3685 // If we didn't find this initializer, it must be because we
3686 // scanned past it on a previous iteration. That can only
3687 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003688 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003689 Sema::SemaDiagnosticBuilder D =
3690 SemaRef.Diag(PrevInit->getSourceLocation(),
3691 diag::warn_initializer_out_of_order);
3692
Francois Pichet00eb3f92010-12-04 09:14:42 +00003693 if (PrevInit->isAnyMemberInitializer())
3694 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003695 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003696 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003697
Francois Pichet00eb3f92010-12-04 09:14:42 +00003698 if (Init->isAnyMemberInitializer())
3699 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003700 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003701 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003702
3703 // Move back to the initializer's location in the ideal list.
3704 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3705 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003706 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003707
3708 assert(IdealIndex != NumIdealInits &&
3709 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003710 }
John McCalld6ca8da2010-04-10 07:37:23 +00003711
3712 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003713 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003714}
3715
John McCall3c3ccdb2010-04-10 09:28:51 +00003716namespace {
3717bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003718 CXXCtorInitializer *Init,
3719 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003720 if (!PrevInit) {
3721 PrevInit = Init;
3722 return false;
3723 }
3724
Douglas Gregordc392c12013-03-25 23:28:23 +00003725 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003726 S.Diag(Init->getSourceLocation(),
3727 diag::err_multiple_mem_initialization)
3728 << Field->getDeclName()
3729 << Init->getSourceRange();
3730 else {
John McCallf4c73712011-01-19 06:33:43 +00003731 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003732 assert(BaseClass && "neither field nor base");
3733 S.Diag(Init->getSourceLocation(),
3734 diag::err_multiple_base_initialization)
3735 << QualType(BaseClass, 0)
3736 << Init->getSourceRange();
3737 }
3738 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3739 << 0 << PrevInit->getSourceRange();
3740
3741 return true;
3742}
3743
Sean Huntcbb67482011-01-08 20:30:50 +00003744typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003745typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3746
3747bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003748 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003749 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003750 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003751 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003752 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003753
3754 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003755 if (Parent->isUnion()) {
3756 UnionEntry &En = Unions[Parent];
3757 if (En.first && En.first != Child) {
3758 S.Diag(Init->getSourceLocation(),
3759 diag::err_multiple_mem_union_initialization)
3760 << Field->getDeclName()
3761 << Init->getSourceRange();
3762 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3763 << 0 << En.second->getSourceRange();
3764 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003765 }
3766 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003767 En.first = Child;
3768 En.second = Init;
3769 }
David Blaikie6fe29652011-11-17 06:01:57 +00003770 if (!Parent->isAnonymousStructOrUnion())
3771 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003772 }
3773
3774 Child = Parent;
3775 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003776 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003777
3778 return false;
3779}
3780}
3781
Richard Trieu225e9822013-09-16 21:54:53 +00003782// Diagnose value-uses of fields to initialize themselves, e.g.
3783// foo(foo)
3784// where foo is not also a parameter to the constructor.
Richard Trieuef8f90c2013-09-20 03:03:06 +00003785// Also diagnose across field uninitialized use such as
3786// x(y), y(x)
Richard Trieu225e9822013-09-16 21:54:53 +00003787// TODO: implement -Wuninitialized and fold this into that framework.
Richard Trieu225e9822013-09-16 21:54:53 +00003788static void DiagnoseUnitializedFields(
3789 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3790
3791 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
3792 Constructor->getLocation())
3793 == DiagnosticsEngine::Ignored) {
3794 return;
3795 }
3796
Richard Trieuef8f90c2013-09-20 03:03:06 +00003797 const CXXRecordDecl *RD = Constructor->getParent();
3798
3799 // Holds fields that are uninitialized.
3800 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3801
3802 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
3803 I != E; ++I) {
3804 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
3805 UninitializedFields.insert(FD);
3806 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
3807 UninitializedFields.insert(IFD->getAnonField());
3808 }
3809 }
3810
3811 // Fields already checked when processing the in class initializers.
3812 llvm::SmallPtrSet<ValueDecl*, 4>
3813 InClassUninitializedFields = UninitializedFields;
3814
3815 for (CXXConstructorDecl::init_const_iterator FieldInit =
3816 Constructor->init_begin(),
Richard Trieu225e9822013-09-16 21:54:53 +00003817 FieldInitEnd = Constructor->init_end();
3818 FieldInit != FieldInitEnd; ++FieldInit) {
3819
Richard Trieuef8f90c2013-09-20 03:03:06 +00003820 FieldDecl *Field = (*FieldInit)->getAnyMember();
Richard Trieu225e9822013-09-16 21:54:53 +00003821 Expr *InitExpr = (*FieldInit)->getInit();
3822
Richard Trieuef8f90c2013-09-20 03:03:06 +00003823 if (!Field) {
3824 CheckInitExprContainsUninitializedFields(
3825 SemaRef, InitExpr, 0, UninitializedFields,
3826 false/*WarnOnSelfReference*/);
3827 continue;
Richard Trieu225e9822013-09-16 21:54:53 +00003828 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00003829
3830 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3831 // This field is initialized with an in-class initailzer. Remove the
3832 // fields already checked to prevent duplicate warnings.
3833 llvm::SmallPtrSet<ValueDecl*, 4> DiffSet = UninitializedFields;
3834 for (llvm::SmallPtrSet<ValueDecl*, 4>::iterator
3835 I = InClassUninitializedFields.begin(),
3836 E = InClassUninitializedFields.end();
3837 I != E; ++I) {
3838 DiffSet.erase(*I);
3839 }
3840 CheckInitExprContainsUninitializedFields(
3841 SemaRef, Default->getExpr(), Field, DiffSet,
3842 DiffSet.count(Field), Constructor);
3843
3844 // Update the unitialized field sets.
3845 CheckInitExprContainsUninitializedFields(
3846 SemaRef, Default->getExpr(), 0, UninitializedFields,
3847 false);
3848 CheckInitExprContainsUninitializedFields(
3849 SemaRef, Default->getExpr(), 0, InClassUninitializedFields,
3850 false);
3851 } else {
3852 CheckInitExprContainsUninitializedFields(
3853 SemaRef, InitExpr, Field, UninitializedFields,
3854 UninitializedFields.count(Field));
3855 if (Expr* InClassInit = Field->getInClassInitializer()) {
3856 CheckInitExprContainsUninitializedFields(
3857 SemaRef, InClassInit, 0, InClassUninitializedFields,
3858 false);
3859 }
3860 }
3861 UninitializedFields.erase(Field);
3862 InClassUninitializedFields.erase(Field);
Richard Trieu225e9822013-09-16 21:54:53 +00003863 }
3864}
3865
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003866/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003867void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003868 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003869 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003870 bool AnyErrors) {
3871 if (!ConstructorDecl)
3872 return;
3873
3874 AdjustDeclIfTemplate(ConstructorDecl);
3875
3876 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003877 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003878
3879 if (!Constructor) {
3880 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3881 return;
3882 }
3883
John McCall3c3ccdb2010-04-10 09:28:51 +00003884 // Mapping for the duplicate initializers check.
3885 // For member initializers, this is keyed with a FieldDecl*.
3886 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003887 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003888
3889 // Mapping for the inconsistent anonymous-union initializers check.
3890 RedundantUnionMap MemberUnions;
3891
Anders Carlssonea356fb2010-04-02 05:42:15 +00003892 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003893 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003894 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003895
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003896 // Set the source order index.
3897 Init->setSourceOrder(i);
3898
Francois Pichet00eb3f92010-12-04 09:14:42 +00003899 if (Init->isAnyMemberInitializer()) {
3900 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003901 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3902 CheckRedundantUnionInit(*this, Init, MemberUnions))
3903 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003904 } else if (Init->isBaseInitializer()) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003905 const void *Key =
3906 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall3c3ccdb2010-04-10 09:28:51 +00003907 if (CheckRedundantInit(*this, Init, Members[Key]))
3908 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003909 } else {
3910 assert(Init->isDelegatingInitializer());
3911 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003912 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003913 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003914 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003915 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003916 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003917 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003918 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003919 // Return immediately as the initializer is set.
3920 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003921 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003922 }
3923
Anders Carlssonea356fb2010-04-02 05:42:15 +00003924 if (HadError)
3925 return;
3926
David Blaikie93c86172013-01-17 05:26:25 +00003927 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003928
David Blaikie93c86172013-01-17 05:26:25 +00003929 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu225e9822013-09-16 21:54:53 +00003930
3931 DiagnoseUnitializedFields(*this, Constructor);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003932}
3933
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003934void
John McCallef027fe2010-03-16 21:39:52 +00003935Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3936 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003937 // Ignore dependent contexts. Also ignore unions, since their members never
3938 // have destructors implicitly called.
3939 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003940 return;
John McCall58e6f342010-03-16 05:22:47 +00003941
3942 // FIXME: all the access-control diagnostics are positioned on the
3943 // field/base declaration. That's probably good; that said, the
3944 // user might reasonably want to know why the destructor is being
3945 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003946
Anders Carlsson9f853df2009-11-17 04:44:12 +00003947 // Non-static data members.
3948 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3949 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003950 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003951 if (Field->isInvalidDecl())
3952 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003953
3954 // Don't destroy incomplete or zero-length arrays.
3955 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3956 continue;
3957
Anders Carlsson9f853df2009-11-17 04:44:12 +00003958 QualType FieldType = Context.getBaseElementType(Field->getType());
3959
3960 const RecordType* RT = FieldType->getAs<RecordType>();
3961 if (!RT)
3962 continue;
3963
3964 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003965 if (FieldClassDecl->isInvalidDecl())
3966 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003967 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003968 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003969 // The destructor for an implicit anonymous union member is never invoked.
3970 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3971 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003972
Douglas Gregordb89f282010-07-01 22:47:18 +00003973 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003974 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003975 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003976 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003977 << Field->getDeclName()
3978 << FieldType);
3979
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003980 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003981 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003982 }
3983
John McCall58e6f342010-03-16 05:22:47 +00003984 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3985
Anders Carlsson9f853df2009-11-17 04:44:12 +00003986 // Bases.
3987 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3988 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003989 // Bases are always records in a well-formed non-dependent class.
3990 const RecordType *RT = Base->getType()->getAs<RecordType>();
3991
3992 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003993 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003994 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003995
John McCall58e6f342010-03-16 05:22:47 +00003996 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003997 // If our base class is invalid, we probably can't get its dtor anyway.
3998 if (BaseClassDecl->isInvalidDecl())
3999 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004000 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00004001 continue;
John McCall58e6f342010-03-16 05:22:47 +00004002
Douglas Gregordb89f282010-07-01 22:47:18 +00004003 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004004 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00004005
4006 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00004007 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004008 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00004009 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00004010 << Base->getSourceRange(),
4011 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00004012
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004013 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004014 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00004015 }
4016
4017 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004018 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
4019 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00004020
4021 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00004022 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00004023
4024 // Ignore direct virtual bases.
4025 if (DirectVirtualBases.count(RT))
4026 continue;
4027
John McCall58e6f342010-03-16 05:22:47 +00004028 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004029 // If our base class is invalid, we probably can't get its dtor anyway.
4030 if (BaseClassDecl->isInvalidDecl())
4031 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004032 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004033 continue;
John McCall58e6f342010-03-16 05:22:47 +00004034
Douglas Gregordb89f282010-07-01 22:47:18 +00004035 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004036 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00004037 if (CheckDestructorAccess(
4038 ClassDecl->getLocation(), Dtor,
4039 PDiag(diag::err_access_dtor_vbase)
4040 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
4041 Context.getTypeDeclType(ClassDecl)) ==
4042 AR_accessible) {
4043 CheckDerivedToBaseConversion(
4044 Context.getTypeDeclType(ClassDecl), VBase->getType(),
4045 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4046 SourceRange(), DeclarationName(), 0);
4047 }
John McCall58e6f342010-03-16 05:22:47 +00004048
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004049 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004050 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004051 }
4052}
4053
John McCalld226f652010-08-21 09:40:31 +00004054void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00004055 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004056 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004057
Mike Stump1eb44332009-09-09 15:08:12 +00004058 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00004059 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00004060 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004061}
4062
Mike Stump1eb44332009-09-09 15:08:12 +00004063bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00004064 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004065 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4066 unsigned DiagID;
4067 AbstractDiagSelID SelID;
4068
4069 public:
4070 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4071 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004072
4073 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman2217f852012-08-14 02:06:07 +00004074 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004075 if (SelID == -1)
4076 S.Diag(Loc, DiagID) << T;
4077 else
4078 S.Diag(Loc, DiagID) << SelID << T;
4079 }
4080 } Diagnoser(DiagID, SelID);
4081
4082 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004083}
4084
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00004085bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004086 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004087 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004088 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004089
Anders Carlsson11f21a02009-03-23 19:10:31 +00004090 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004091 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004092
Ted Kremenek6217b802009-07-29 21:53:49 +00004093 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004094 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004095 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004096 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00004097
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004098 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004099 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004100 }
Mike Stump1eb44332009-09-09 15:08:12 +00004101
Ted Kremenek6217b802009-07-29 21:53:49 +00004102 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004103 if (!RT)
4104 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004105
John McCall86ff3082010-02-04 22:26:26 +00004106 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004107
John McCall94c3b562010-08-18 09:41:07 +00004108 // We can't answer whether something is abstract until it has a
4109 // definition. If it's currently being defined, we'll walk back
4110 // over all the declarations when we have a full definition.
4111 const CXXRecordDecl *Def = RD->getDefinition();
4112 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00004113 return false;
4114
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004115 if (!RD->isAbstract())
4116 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004117
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004118 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00004119 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00004120
John McCall94c3b562010-08-18 09:41:07 +00004121 return true;
4122}
4123
4124void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4125 // Check if we've already emitted the list of pure virtual functions
4126 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004127 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00004128 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Richard Smithcbc820a2013-07-22 02:56:56 +00004130 // If the diagnostic is suppressed, don't emit the notes. We're only
4131 // going to emit them once, so try to attach them to a diagnostic we're
4132 // actually going to show.
4133 if (Diags.isLastDiagnosticIgnored())
4134 return;
4135
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004136 CXXFinalOverriderMap FinalOverriders;
4137 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00004138
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004139 // Keep a set of seen pure methods so we won't diagnose the same method
4140 // more than once.
4141 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4142
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004143 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4144 MEnd = FinalOverriders.end();
4145 M != MEnd;
4146 ++M) {
4147 for (OverridingMethods::iterator SO = M->second.begin(),
4148 SOEnd = M->second.end();
4149 SO != SOEnd; ++SO) {
4150 // C++ [class.abstract]p4:
4151 // A class is abstract if it contains or inherits at least one
4152 // pure virtual function for which the final overrider is pure
4153 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00004154
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004155 //
4156 if (SO->second.size() != 1)
4157 continue;
4158
4159 if (!SO->second.front().Method->isPure())
4160 continue;
4161
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004162 if (!SeenPureMethods.insert(SO->second.front().Method))
4163 continue;
4164
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004165 Diag(SO->second.front().Method->getLocation(),
4166 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00004167 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004168 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004169 }
4170
4171 if (!PureVirtualClassDiagSet)
4172 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4173 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004174}
4175
Anders Carlsson8211eff2009-03-24 01:19:16 +00004176namespace {
John McCall94c3b562010-08-18 09:41:07 +00004177struct AbstractUsageInfo {
4178 Sema &S;
4179 CXXRecordDecl *Record;
4180 CanQualType AbstractType;
4181 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00004182
John McCall94c3b562010-08-18 09:41:07 +00004183 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4184 : S(S), Record(Record),
4185 AbstractType(S.Context.getCanonicalType(
4186 S.Context.getTypeDeclType(Record))),
4187 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00004188
John McCall94c3b562010-08-18 09:41:07 +00004189 void DiagnoseAbstractType() {
4190 if (Invalid) return;
4191 S.DiagnoseAbstractType(Record);
4192 Invalid = true;
4193 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00004194
John McCall94c3b562010-08-18 09:41:07 +00004195 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4196};
4197
4198struct CheckAbstractUsage {
4199 AbstractUsageInfo &Info;
4200 const NamedDecl *Ctx;
4201
4202 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4203 : Info(Info), Ctx(Ctx) {}
4204
4205 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4206 switch (TL.getTypeLocClass()) {
4207#define ABSTRACT_TYPELOC(CLASS, PARENT)
4208#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004209 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004210#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004211 }
John McCall94c3b562010-08-18 09:41:07 +00004212 }
Mike Stump1eb44332009-09-09 15:08:12 +00004213
John McCall94c3b562010-08-18 09:41:07 +00004214 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4215 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4216 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00004217 if (!TL.getArg(I))
4218 continue;
4219
John McCall94c3b562010-08-18 09:41:07 +00004220 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4221 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004222 }
John McCall94c3b562010-08-18 09:41:07 +00004223 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004224
John McCall94c3b562010-08-18 09:41:07 +00004225 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4226 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4227 }
Mike Stump1eb44332009-09-09 15:08:12 +00004228
John McCall94c3b562010-08-18 09:41:07 +00004229 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4230 // Visit the type parameters from a permissive context.
4231 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4232 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4233 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4234 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4235 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4236 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004237 }
John McCall94c3b562010-08-18 09:41:07 +00004238 }
Mike Stump1eb44332009-09-09 15:08:12 +00004239
John McCall94c3b562010-08-18 09:41:07 +00004240 // Visit pointee types from a permissive context.
4241#define CheckPolymorphic(Type) \
4242 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4243 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4244 }
4245 CheckPolymorphic(PointerTypeLoc)
4246 CheckPolymorphic(ReferenceTypeLoc)
4247 CheckPolymorphic(MemberPointerTypeLoc)
4248 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004249 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004250
John McCall94c3b562010-08-18 09:41:07 +00004251 /// Handle all the types we haven't given a more specific
4252 /// implementation for above.
4253 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4254 // Every other kind of type that we haven't called out already
4255 // that has an inner type is either (1) sugar or (2) contains that
4256 // inner type in some way as a subobject.
4257 if (TypeLoc Next = TL.getNextTypeLoc())
4258 return Visit(Next, Sel);
4259
4260 // If there's no inner type and we're in a permissive context,
4261 // don't diagnose.
4262 if (Sel == Sema::AbstractNone) return;
4263
4264 // Check whether the type matches the abstract type.
4265 QualType T = TL.getType();
4266 if (T->isArrayType()) {
4267 Sel = Sema::AbstractArrayType;
4268 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004269 }
John McCall94c3b562010-08-18 09:41:07 +00004270 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4271 if (CT != Info.AbstractType) return;
4272
4273 // It matched; do some magic.
4274 if (Sel == Sema::AbstractArrayType) {
4275 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4276 << T << TL.getSourceRange();
4277 } else {
4278 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4279 << Sel << T << TL.getSourceRange();
4280 }
4281 Info.DiagnoseAbstractType();
4282 }
4283};
4284
4285void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4286 Sema::AbstractDiagSelID Sel) {
4287 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4288}
4289
4290}
4291
4292/// Check for invalid uses of an abstract type in a method declaration.
4293static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4294 CXXMethodDecl *MD) {
4295 // No need to do the check on definitions, which require that
4296 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004297 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004298 return;
4299
4300 // For safety's sake, just ignore it if we don't have type source
4301 // information. This should never happen for non-implicit methods,
4302 // but...
4303 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4304 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4305}
4306
4307/// Check for invalid uses of an abstract type within a class definition.
4308static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4309 CXXRecordDecl *RD) {
4310 for (CXXRecordDecl::decl_iterator
4311 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4312 Decl *D = *I;
4313 if (D->isImplicit()) continue;
4314
4315 // Methods and method templates.
4316 if (isa<CXXMethodDecl>(D)) {
4317 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4318 } else if (isa<FunctionTemplateDecl>(D)) {
4319 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4320 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4321
4322 // Fields and static variables.
4323 } else if (isa<FieldDecl>(D)) {
4324 FieldDecl *FD = cast<FieldDecl>(D);
4325 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4326 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4327 } else if (isa<VarDecl>(D)) {
4328 VarDecl *VD = cast<VarDecl>(D);
4329 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4330 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4331
4332 // Nested classes and class templates.
4333 } else if (isa<CXXRecordDecl>(D)) {
4334 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4335 } else if (isa<ClassTemplateDecl>(D)) {
4336 CheckAbstractClassUsage(Info,
4337 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4338 }
4339 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004340}
4341
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004342/// \brief Perform semantic checks on a class definition that has been
4343/// completing, introducing implicitly-declared members, checking for
4344/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004345void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004346 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004347 return;
4348
John McCall94c3b562010-08-18 09:41:07 +00004349 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4350 AbstractUsageInfo Info(*this, Record);
4351 CheckAbstractClassUsage(Info, Record);
4352 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004353
4354 // If this is not an aggregate type and has no user-declared constructor,
4355 // complain about any non-static data members of reference or const scalar
4356 // type, since they will never get initializers.
4357 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004358 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4359 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004360 bool Complained = false;
4361 for (RecordDecl::field_iterator F = Record->field_begin(),
4362 FEnd = Record->field_end();
4363 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004364 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004365 continue;
4366
Douglas Gregor325e5932010-04-15 00:00:53 +00004367 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004368 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004369 if (!Complained) {
4370 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4371 << Record->getTagKind() << Record;
4372 Complained = true;
4373 }
4374
4375 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4376 << F->getType()->isReferenceType()
4377 << F->getDeclName();
4378 }
4379 }
4380 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004381
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004382 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004383 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004384
4385 if (Record->getIdentifier()) {
4386 // C++ [class.mem]p13:
4387 // If T is the name of a class, then each of the following shall have a
4388 // name different from T:
4389 // - every member of every anonymous union that is a member of class T.
4390 //
4391 // C++ [class.mem]p14:
4392 // In addition, if class T has a user-declared constructor (12.1), every
4393 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004394 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4395 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4396 ++I) {
4397 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004398 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4399 isa<IndirectFieldDecl>(D)) {
4400 Diag(D->getLocation(), diag::err_member_name_of_class)
4401 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004402 break;
4403 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004404 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004405 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004406
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004407 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004408 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004409 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004410 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004411 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4412 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4413 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004414
David Majnemer7121bdb2013-10-18 00:33:31 +00004415 if (Record->isAbstract()) {
4416 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4417 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4418 << FA->isSpelledAsSealed();
4419 DiagnoseAbstractType(Record);
4420 }
David Blaikieb6b5b972012-09-21 03:21:07 +00004421 }
4422
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004423 if (!Record->isDependentType()) {
4424 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4425 MEnd = Record->method_end();
4426 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004427 // See if a method overloads virtual methods in a base
4428 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004429 if (!M->isStatic())
Eli Friedmandae92712013-09-05 23:51:03 +00004430 DiagnoseHiddenVirtualMethods(*M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004431
4432 // Check whether the explicitly-defaulted special members are valid.
4433 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4434 CheckExplicitlyDefaultedSpecialMember(*M);
4435
4436 // For an explicitly defaulted or deleted special member, we defer
4437 // determining triviality until the class is complete. That time is now!
4438 if (!M->isImplicit() && !M->isUserProvided()) {
4439 CXXSpecialMember CSM = getSpecialMember(*M);
4440 if (CSM != CXXInvalid) {
4441 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4442
4443 // Inform the class that we've finished declaring this member.
4444 Record->finishedDefaultedOrDeletedMember(*M);
4445 }
4446 }
4447 }
4448 }
4449
4450 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4451 // function that is not a constructor declares that member function to be
4452 // const. [...] The class of which that function is a member shall be
4453 // a literal type.
4454 //
4455 // If the class has virtual bases, any constexpr members will already have
4456 // been diagnosed by the checks performed on the member declaration, so
4457 // suppress this (less useful) diagnostic.
4458 //
4459 // We delay this until we know whether an explicitly-defaulted (or deleted)
4460 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004461 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004462 !Record->isLiteral() && !Record->getNumVBases()) {
4463 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4464 MEnd = Record->method_end();
4465 M != MEnd; ++M) {
4466 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4467 switch (Record->getTemplateSpecializationKind()) {
4468 case TSK_ImplicitInstantiation:
4469 case TSK_ExplicitInstantiationDeclaration:
4470 case TSK_ExplicitInstantiationDefinition:
4471 // If a template instantiates to a non-literal type, but its members
4472 // instantiate to constexpr functions, the template is technically
4473 // ill-formed, but we allow it for sanity.
4474 continue;
4475
4476 case TSK_Undeclared:
4477 case TSK_ExplicitSpecialization:
4478 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4479 diag::err_constexpr_method_non_literal);
4480 break;
4481 }
4482
4483 // Only produce one error per class.
4484 break;
4485 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004486 }
4487 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004488
Warren Huntb2969b12013-10-11 20:19:00 +00004489 // Check to see if we're trying to lay out a struct using the ms_struct
4490 // attribute that is dynamic.
4491 if (Record->isMsStruct(Context) && Record->isDynamicClass()) {
4492 Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed);
4493 Record->dropAttr<MsStructAttr>();
4494 }
4495
Richard Smith07b0fdc2013-03-18 21:12:30 +00004496 // Declare inheriting constructors. We do this eagerly here because:
4497 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004498 // constructors from different classes.
4499 // - The lazy declaration of the other implicit constructors is so as to not
4500 // waste space and performance on classes that are not meant to be
4501 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004502 // have inheriting constructors.
4503 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004504}
4505
Richard Smith7756afa2012-06-10 05:43:50 +00004506/// Is the special member function which would be selected to perform the
4507/// specified operation on the specified class type a constexpr constructor?
4508static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4509 Sema::CXXSpecialMember CSM,
4510 bool ConstArg) {
4511 Sema::SpecialMemberOverloadResult *SMOR =
4512 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4513 false, false, false, false);
4514 if (!SMOR || !SMOR->getMethod())
4515 // A constructor we wouldn't select can't be "involved in initializing"
4516 // anything.
4517 return true;
4518 return SMOR->getMethod()->isConstexpr();
4519}
4520
4521/// Determine whether the specified special member function would be constexpr
4522/// if it were implicitly defined.
4523static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4524 Sema::CXXSpecialMember CSM,
4525 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004526 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004527 return false;
4528
4529 // C++11 [dcl.constexpr]p4:
4530 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004531 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004532 switch (CSM) {
4533 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004534 // Since default constructor lookup is essentially trivial (and cannot
4535 // involve, for instance, template instantiation), we compute whether a
4536 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4537 //
4538 // This is important for performance; we need to know whether the default
4539 // constructor is constexpr to determine whether the type is a literal type.
4540 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4541
Richard Smith7756afa2012-06-10 05:43:50 +00004542 case Sema::CXXCopyConstructor:
4543 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004544 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004545 break;
4546
4547 case Sema::CXXCopyAssignment:
4548 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004549 if (!S.getLangOpts().CPlusPlus1y)
4550 return false;
4551 // In C++1y, we need to perform overload resolution.
4552 Ctor = false;
4553 break;
4554
Richard Smith7756afa2012-06-10 05:43:50 +00004555 case Sema::CXXDestructor:
4556 case Sema::CXXInvalid:
4557 return false;
4558 }
4559
4560 // -- if the class is a non-empty union, or for each non-empty anonymous
4561 // union member of a non-union class, exactly one non-static data member
4562 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004563 //
4564 // If we squint, this is guaranteed, since exactly one non-static data member
4565 // will be initialized (if the constructor isn't deleted), we just don't know
4566 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004567 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004568 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004569
4570 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004571 if (Ctor && ClassDecl->getNumVBases())
4572 return false;
4573
4574 // C++1y [class.copy]p26:
4575 // -- [the class] is a literal type, and
4576 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004577 return false;
4578
4579 // -- every constructor involved in initializing [...] base class
4580 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004581 // -- the assignment operator selected to copy/move each direct base
4582 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004583 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4584 BEnd = ClassDecl->bases_end();
4585 B != BEnd; ++B) {
4586 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4587 if (!BaseType) continue;
4588
4589 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4590 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4591 return false;
4592 }
4593
4594 // -- every constructor involved in initializing non-static data members
4595 // [...] shall be a constexpr constructor;
4596 // -- every non-static data member and base class sub-object shall be
4597 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004598 // -- for each non-stastic data member of X that is of class type (or array
4599 // thereof), the assignment operator selected to copy/move that member is
4600 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004601 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4602 FEnd = ClassDecl->field_end();
4603 F != FEnd; ++F) {
4604 if (F->isInvalidDecl())
4605 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004606 if (const RecordType *RecordTy =
4607 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004608 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4609 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4610 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004611 }
4612 }
4613
4614 // All OK, it's constexpr!
4615 return true;
4616}
4617
Richard Smithb9d0b762012-07-27 04:22:15 +00004618static Sema::ImplicitExceptionSpecification
4619computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4620 switch (S.getSpecialMember(MD)) {
4621 case Sema::CXXDefaultConstructor:
4622 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4623 case Sema::CXXCopyConstructor:
4624 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4625 case Sema::CXXCopyAssignment:
4626 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4627 case Sema::CXXMoveConstructor:
4628 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4629 case Sema::CXXMoveAssignment:
4630 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4631 case Sema::CXXDestructor:
4632 return S.ComputeDefaultedDtorExceptionSpec(MD);
4633 case Sema::CXXInvalid:
4634 break;
4635 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004636 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4637 "only special members have implicit exception specs");
4638 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004639}
4640
Richard Smithdd25e802012-07-30 23:48:14 +00004641static void
4642updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4643 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4644 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4645 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004646 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4647 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004648}
4649
Reid Kleckneref072032013-08-27 23:08:25 +00004650static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4651 CXXMethodDecl *MD) {
4652 FunctionProtoType::ExtProtoInfo EPI;
4653
4654 // Build an exception specification pointing back at this member.
4655 EPI.ExceptionSpecType = EST_Unevaluated;
4656 EPI.ExceptionSpecDecl = MD;
4657
4658 // Set the calling convention to the default for C++ instance methods.
4659 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4660 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4661 /*IsCXXMethod=*/true));
4662 return EPI;
4663}
4664
Richard Smithb9d0b762012-07-27 04:22:15 +00004665void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4666 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4667 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4668 return;
4669
Richard Smithdd25e802012-07-30 23:48:14 +00004670 // Evaluate the exception specification.
4671 ImplicitExceptionSpecification ExceptSpec =
4672 computeImplicitExceptionSpec(*this, Loc, MD);
4673
4674 // Update the type of the special member to use it.
4675 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4676
4677 // A user-provided destructor can be defined outside the class. When that
4678 // happens, be sure to update the exception specification on both
4679 // declarations.
4680 const FunctionProtoType *CanonicalFPT =
4681 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4682 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4683 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4684 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004685}
4686
Richard Smith3003e1d2012-05-15 04:39:51 +00004687void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4688 CXXRecordDecl *RD = MD->getParent();
4689 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004690
Richard Smith3003e1d2012-05-15 04:39:51 +00004691 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4692 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004693
4694 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004695 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004696 bool First = MD == MD->getCanonicalDecl();
4697
4698 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004699
4700 // C++11 [dcl.fct.def.default]p1:
4701 // A function that is explicitly defaulted shall
4702 // -- be a special member function (checked elsewhere),
4703 // -- have the same type (except for ref-qualifiers, and except that a
4704 // copy operation can take a non-const reference) as an implicit
4705 // declaration, and
4706 // -- not have default arguments.
4707 unsigned ExpectedParams = 1;
4708 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4709 ExpectedParams = 0;
4710 if (MD->getNumParams() != ExpectedParams) {
4711 // This also checks for default arguments: a copy or move constructor with a
4712 // default argument is classified as a default constructor, and assignment
4713 // operations and destructors can't have default arguments.
4714 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4715 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004716 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004717 } else if (MD->isVariadic()) {
4718 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4719 << CSM << MD->getSourceRange();
4720 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004721 }
4722
Richard Smith3003e1d2012-05-15 04:39:51 +00004723 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004724
Richard Smith7756afa2012-06-10 05:43:50 +00004725 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004726 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004727 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004728 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004729 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004730
Richard Smith3003e1d2012-05-15 04:39:51 +00004731 QualType ReturnType = Context.VoidTy;
4732 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4733 // Check for return type matching.
4734 ReturnType = Type->getResultType();
4735 QualType ExpectedReturnType =
4736 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4737 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4738 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4739 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4740 HadError = true;
4741 }
4742
4743 // A defaulted special member cannot have cv-qualifiers.
4744 if (Type->getTypeQuals()) {
4745 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004746 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004747 HadError = true;
4748 }
4749 }
4750
4751 // Check for parameter type matching.
4752 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004753 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004754 if (ExpectedParams && ArgType->isReferenceType()) {
4755 // Argument must be reference to possibly-const T.
4756 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004757 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004758
4759 if (ReferentType.isVolatileQualified()) {
4760 Diag(MD->getLocation(),
4761 diag::err_defaulted_special_member_volatile_param) << CSM;
4762 HadError = true;
4763 }
4764
Richard Smith7756afa2012-06-10 05:43:50 +00004765 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004766 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4767 Diag(MD->getLocation(),
4768 diag::err_defaulted_special_member_copy_const_param)
4769 << (CSM == CXXCopyAssignment);
4770 // FIXME: Explain why this special member can't be const.
4771 } else {
4772 Diag(MD->getLocation(),
4773 diag::err_defaulted_special_member_move_const_param)
4774 << (CSM == CXXMoveAssignment);
4775 }
4776 HadError = true;
4777 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004778 } else if (ExpectedParams) {
4779 // A copy assignment operator can take its argument by value, but a
4780 // defaulted one cannot.
4781 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004782 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004783 HadError = true;
4784 }
Sean Huntbe631222011-05-17 20:44:43 +00004785
Richard Smith61802452011-12-22 02:22:31 +00004786 // C++11 [dcl.fct.def.default]p2:
4787 // An explicitly-defaulted function may be declared constexpr only if it
4788 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004789 // Do not apply this rule to members of class templates, since core issue 1358
4790 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004791 // functions which cannot be constexpr (for non-constructors in C++11 and for
4792 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004793 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4794 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004795 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4796 : isa<CXXConstructorDecl>(MD)) &&
4797 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004798 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4799 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004800 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004801 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004802 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004803
Richard Smith61802452011-12-22 02:22:31 +00004804 // and may have an explicit exception-specification only if it is compatible
4805 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004806 if (Type->hasExceptionSpec()) {
4807 // Delay the check if this is the first declaration of the special member,
4808 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004809 if (First) {
4810 // If the exception specification needs to be instantiated, do so now,
4811 // before we clobber it with an EST_Unevaluated specification below.
4812 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4813 InstantiateExceptionSpec(MD->getLocStart(), MD);
4814 Type = MD->getType()->getAs<FunctionProtoType>();
4815 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004816 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004817 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004818 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4819 }
Richard Smith61802452011-12-22 02:22:31 +00004820
4821 // If a function is explicitly defaulted on its first declaration,
4822 if (First) {
4823 // -- it is implicitly considered to be constexpr if the implicit
4824 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004825 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004826
Richard Smith3003e1d2012-05-15 04:39:51 +00004827 // -- it is implicitly considered to have the same exception-specification
4828 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004829 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4830 EPI.ExceptionSpecType = EST_Unevaluated;
4831 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004832 MD->setType(Context.getFunctionType(ReturnType,
4833 ArrayRef<QualType>(&ArgType,
4834 ExpectedParams),
4835 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004836 }
4837
Richard Smith3003e1d2012-05-15 04:39:51 +00004838 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004839 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004840 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004841 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004842 // C++11 [dcl.fct.def.default]p4:
4843 // [For a] user-provided explicitly-defaulted function [...] if such a
4844 // function is implicitly defined as deleted, the program is ill-formed.
4845 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4846 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004847 }
4848 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004849
Richard Smith3003e1d2012-05-15 04:39:51 +00004850 if (HadError)
4851 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004852}
4853
Richard Smith1d28caf2012-12-11 01:14:52 +00004854/// Check whether the exception specification provided for an
4855/// explicitly-defaulted special member matches the exception specification
4856/// that would have been generated for an implicit special member, per
4857/// C++11 [dcl.fct.def.default]p2.
4858void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4859 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4860 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00004861 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4862 /*IsCXXMethod=*/true);
4863 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith1d28caf2012-12-11 01:14:52 +00004864 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4865 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004866 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004867
4868 // Ensure that it matches.
4869 CheckEquivalentExceptionSpec(
4870 PDiag(diag::err_incorrect_defaulted_exception_spec)
4871 << getSpecialMember(MD), PDiag(),
4872 ImplicitType, SourceLocation(),
4873 SpecifiedType, MD->getLocation());
4874}
4875
Alp Toker08235662013-10-18 05:54:19 +00004876void Sema::CheckDelayedMemberExceptionSpecs() {
4877 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4878 2> Checks;
4879 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smith1d28caf2012-12-11 01:14:52 +00004880
Alp Toker08235662013-10-18 05:54:19 +00004881 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4882 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4883
4884 // Perform any deferred checking of exception specifications for virtual
4885 // destructors.
4886 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4887 const CXXDestructorDecl *Dtor = Checks[i].first;
4888 assert(!Dtor->getParent()->isDependentType() &&
4889 "Should not ever add destructors of templates into the list.");
4890 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4891 }
4892
4893 // Check that any explicitly-defaulted methods have exception specifications
4894 // compatible with their implicit exception specifications.
4895 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4896 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4897 Specs[I].second);
Richard Smith1d28caf2012-12-11 01:14:52 +00004898}
4899
Richard Smith7d5088a2012-02-18 02:02:13 +00004900namespace {
4901struct SpecialMemberDeletionInfo {
4902 Sema &S;
4903 CXXMethodDecl *MD;
4904 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004905 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004906
4907 // Properties of the special member, computed for convenience.
4908 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4909 SourceLocation Loc;
4910
4911 bool AllFieldsAreConst;
4912
4913 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004914 Sema::CXXSpecialMember CSM, bool Diagnose)
4915 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004916 IsConstructor(false), IsAssignment(false), IsMove(false),
4917 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4918 AllFieldsAreConst(true) {
4919 switch (CSM) {
4920 case Sema::CXXDefaultConstructor:
4921 case Sema::CXXCopyConstructor:
4922 IsConstructor = true;
4923 break;
4924 case Sema::CXXMoveConstructor:
4925 IsConstructor = true;
4926 IsMove = true;
4927 break;
4928 case Sema::CXXCopyAssignment:
4929 IsAssignment = true;
4930 break;
4931 case Sema::CXXMoveAssignment:
4932 IsAssignment = true;
4933 IsMove = true;
4934 break;
4935 case Sema::CXXDestructor:
4936 break;
4937 case Sema::CXXInvalid:
4938 llvm_unreachable("invalid special member kind");
4939 }
4940
4941 if (MD->getNumParams()) {
4942 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4943 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4944 }
4945 }
4946
4947 bool inUnion() const { return MD->getParent()->isUnion(); }
4948
4949 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004950 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4951 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004952 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004953 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4954 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4955 Quals = 0;
4956 return S.LookupSpecialMember(Class, CSM,
4957 ConstArg || (Quals & Qualifiers::Const),
4958 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004959 MD->getRefQualifier() == RQ_RValue,
4960 TQ & Qualifiers::Const,
4961 TQ & Qualifiers::Volatile);
4962 }
4963
Richard Smith6c4c36c2012-03-30 20:53:28 +00004964 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004965
Richard Smith6c4c36c2012-03-30 20:53:28 +00004966 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004967 bool shouldDeleteForField(FieldDecl *FD);
4968 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004969
Richard Smith517bb842012-07-18 03:51:16 +00004970 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4971 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004972 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4973 Sema::SpecialMemberOverloadResult *SMOR,
4974 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004975
4976 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004977};
4978}
4979
John McCall12d8d802012-04-09 20:53:23 +00004980/// Is the given special member inaccessible when used on the given
4981/// sub-object.
4982bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4983 CXXMethodDecl *target) {
4984 /// If we're operating on a base class, the object type is the
4985 /// type of this special member.
4986 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004987 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004988 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4989 objectTy = S.Context.getTypeDeclType(MD->getParent());
4990 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4991
4992 // If we're operating on a field, the object type is the type of the field.
4993 } else {
4994 objectTy = S.Context.getTypeDeclType(target->getParent());
4995 }
4996
4997 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4998}
4999
Richard Smith6c4c36c2012-03-30 20:53:28 +00005000/// Check whether we should delete a special member due to the implicit
5001/// definition containing a call to a special member of a subobject.
5002bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5003 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5004 bool IsDtorCallInCtor) {
5005 CXXMethodDecl *Decl = SMOR->getMethod();
5006 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5007
5008 int DiagKind = -1;
5009
5010 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5011 DiagKind = !Decl ? 0 : 1;
5012 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5013 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00005014 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00005015 DiagKind = 3;
5016 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5017 !Decl->isTrivial()) {
5018 // A member of a union must have a trivial corresponding special member.
5019 // As a weird special case, a destructor call from a union's constructor
5020 // must be accessible and non-deleted, but need not be trivial. Such a
5021 // destructor is never actually called, but is semantically checked as
5022 // if it were.
5023 DiagKind = 4;
5024 }
5025
5026 if (DiagKind == -1)
5027 return false;
5028
5029 if (Diagnose) {
5030 if (Field) {
5031 S.Diag(Field->getLocation(),
5032 diag::note_deleted_special_member_class_subobject)
5033 << CSM << MD->getParent() << /*IsField*/true
5034 << Field << DiagKind << IsDtorCallInCtor;
5035 } else {
5036 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5037 S.Diag(Base->getLocStart(),
5038 diag::note_deleted_special_member_class_subobject)
5039 << CSM << MD->getParent() << /*IsField*/false
5040 << Base->getType() << DiagKind << IsDtorCallInCtor;
5041 }
5042
5043 if (DiagKind == 1)
5044 S.NoteDeletedFunction(Decl);
5045 // FIXME: Explain inaccessibility if DiagKind == 3.
5046 }
5047
5048 return true;
5049}
5050
Richard Smith9a561d52012-02-26 09:11:52 +00005051/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00005052/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00005053bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00005054 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005055 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00005056
5057 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00005058 // -- any direct or virtual base class, or non-static data member with no
5059 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00005060 // either M has no default constructor or overload resolution as applied
5061 // to M's default constructor results in an ambiguity or in a function
5062 // that is deleted or inaccessible
5063 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5064 // -- a direct or virtual base class B that cannot be copied/moved because
5065 // overload resolution, as applied to B's corresponding special member,
5066 // results in an ambiguity or a function that is deleted or inaccessible
5067 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00005068 // C++11 [class.dtor]p5:
5069 // -- any direct or virtual base class [...] has a type with a destructor
5070 // that is deleted or inaccessible
5071 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00005072 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00005073 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00005074 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005075
Richard Smith6c4c36c2012-03-30 20:53:28 +00005076 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5077 // -- any direct or virtual base class or non-static data member has a
5078 // type with a destructor that is deleted or inaccessible
5079 if (IsConstructor) {
5080 Sema::SpecialMemberOverloadResult *SMOR =
5081 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5082 false, false, false, false, false);
5083 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5084 return true;
5085 }
5086
Richard Smith9a561d52012-02-26 09:11:52 +00005087 return false;
5088}
5089
5090/// Check whether we should delete a special member function due to the class
5091/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005092bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00005093 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00005094 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00005095}
5096
5097/// Check whether we should delete a special member function due to the class
5098/// having a particular non-static data member.
5099bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5100 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5101 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5102
5103 if (CSM == Sema::CXXDefaultConstructor) {
5104 // For a default constructor, all references must be initialized in-class
5105 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005106 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5107 if (Diagnose)
5108 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5109 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005110 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005111 }
Richard Smith79363f52012-02-27 06:07:25 +00005112 // C++11 [class.ctor]p5: any non-variant non-static data member of
5113 // const-qualified type (or array thereof) with no
5114 // brace-or-equal-initializer does not have a user-provided default
5115 // constructor.
5116 if (!inUnion() && FieldType.isConstQualified() &&
5117 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005118 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5119 if (Diagnose)
5120 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005121 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00005122 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005123 }
5124
5125 if (inUnion() && !FieldType.isConstQualified())
5126 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005127 } else if (CSM == Sema::CXXCopyConstructor) {
5128 // For a copy constructor, data members must not be of rvalue reference
5129 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005130 if (FieldType->isRValueReferenceType()) {
5131 if (Diagnose)
5132 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5133 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00005134 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005135 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005136 } else if (IsAssignment) {
5137 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005138 if (FieldType->isReferenceType()) {
5139 if (Diagnose)
5140 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5141 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005142 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005143 }
5144 if (!FieldRecord && FieldType.isConstQualified()) {
5145 // C++11 [class.copy]p23:
5146 // -- a non-static data member of const non-class type (or array thereof)
5147 if (Diagnose)
5148 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005149 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005150 return true;
5151 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005152 }
5153
5154 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005155 // Some additional restrictions exist on the variant members.
5156 if (!inUnion() && FieldRecord->isUnion() &&
5157 FieldRecord->isAnonymousStructOrUnion()) {
5158 bool AllVariantFieldsAreConst = true;
5159
Richard Smithdf8dc862012-03-29 19:00:10 +00005160 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00005161 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5162 UE = FieldRecord->field_end();
5163 UI != UE; ++UI) {
5164 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00005165
5166 if (!UnionFieldType.isConstQualified())
5167 AllVariantFieldsAreConst = false;
5168
Richard Smith9a561d52012-02-26 09:11:52 +00005169 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5170 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00005171 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5172 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00005173 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005174 }
5175
5176 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00005177 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005178 FieldRecord->field_begin() != FieldRecord->field_end()) {
5179 if (Diagnose)
5180 S.Diag(FieldRecord->getLocation(),
5181 diag::note_deleted_default_ctor_all_const)
5182 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00005183 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005184 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005185
Richard Smithdf8dc862012-03-29 19:00:10 +00005186 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00005187 // This is technically non-conformant, but sanity demands it.
5188 return false;
5189 }
5190
Richard Smith517bb842012-07-18 03:51:16 +00005191 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5192 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00005193 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005194 }
5195
5196 return false;
5197}
5198
5199/// C++11 [class.ctor] p5:
5200/// A defaulted default constructor for a class X is defined as deleted if
5201/// X is a union and all of its variant members are of const-qualified type.
5202bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00005203 // This is a silly definition, because it gives an empty union a deleted
5204 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005205 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5206 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5207 if (Diagnose)
5208 S.Diag(MD->getParent()->getLocation(),
5209 diag::note_deleted_default_ctor_all_const)
5210 << MD->getParent() << /*not anonymous union*/0;
5211 return true;
5212 }
5213 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005214}
5215
5216/// Determine whether a defaulted special member function should be defined as
5217/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5218/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005219bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5220 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00005221 if (MD->isInvalidDecl())
5222 return false;
Sean Hunte16da072011-10-10 06:18:57 +00005223 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00005224 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00005225 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005226 return false;
5227
Richard Smith7d5088a2012-02-18 02:02:13 +00005228 // C++11 [expr.lambda.prim]p19:
5229 // The closure type associated with a lambda-expression has a
5230 // deleted (8.4.3) default constructor and a deleted copy
5231 // assignment operator.
5232 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005233 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5234 if (Diagnose)
5235 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005236 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005237 }
5238
Richard Smith5bdaac52012-04-02 20:59:25 +00005239 // For an anonymous struct or union, the copy and assignment special members
5240 // will never be used, so skip the check. For an anonymous union declared at
5241 // namespace scope, the constructor and destructor are used.
5242 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5243 RD->isAnonymousStructOrUnion())
5244 return false;
5245
Richard Smith6c4c36c2012-03-30 20:53:28 +00005246 // C++11 [class.copy]p7, p18:
5247 // If the class definition declares a move constructor or move assignment
5248 // operator, an implicitly declared copy constructor or copy assignment
5249 // operator is defined as deleted.
5250 if (MD->isImplicit() &&
5251 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5252 CXXMethodDecl *UserDeclaredMove = 0;
5253
5254 // In Microsoft mode, a user-declared move only causes the deletion of the
5255 // corresponding copy operation, not both copy operations.
5256 if (RD->hasUserDeclaredMoveConstructor() &&
5257 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5258 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005259
5260 // Find any user-declared move constructor.
5261 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5262 E = RD->ctor_end(); I != E; ++I) {
5263 if (I->isMoveConstructor()) {
5264 UserDeclaredMove = *I;
5265 break;
5266 }
5267 }
Richard Smith1c931be2012-04-02 18:40:40 +00005268 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005269 } else if (RD->hasUserDeclaredMoveAssignment() &&
5270 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5271 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005272
5273 // Find any user-declared move assignment operator.
5274 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5275 E = RD->method_end(); I != E; ++I) {
5276 if (I->isMoveAssignmentOperator()) {
5277 UserDeclaredMove = *I;
5278 break;
5279 }
5280 }
Richard Smith1c931be2012-04-02 18:40:40 +00005281 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005282 }
5283
5284 if (UserDeclaredMove) {
5285 Diag(UserDeclaredMove->getLocation(),
5286 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005287 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005288 << UserDeclaredMove->isMoveAssignmentOperator();
5289 return true;
5290 }
5291 }
Sean Hunte16da072011-10-10 06:18:57 +00005292
Richard Smith5bdaac52012-04-02 20:59:25 +00005293 // Do access control from the special member function
5294 ContextRAII MethodContext(*this, MD);
5295
Richard Smith9a561d52012-02-26 09:11:52 +00005296 // C++11 [class.dtor]p5:
5297 // -- for a virtual destructor, lookup of the non-array deallocation function
5298 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005299 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005300 FunctionDecl *OperatorDelete = 0;
5301 DeclarationName Name =
5302 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5303 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005304 OperatorDelete, false)) {
5305 if (Diagnose)
5306 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005307 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005308 }
Richard Smith9a561d52012-02-26 09:11:52 +00005309 }
5310
Richard Smith6c4c36c2012-03-30 20:53:28 +00005311 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005312
Sean Huntcdee3fe2011-05-11 22:34:38 +00005313 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005314 BE = RD->bases_end(); BI != BE; ++BI)
5315 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005316 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005317 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005318
Richard Smithe0883602013-07-22 18:06:23 +00005319 // Per DR1611, do not consider virtual bases of constructors of abstract
5320 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005321 if (!RD->isAbstract() || !SMI.IsConstructor) {
5322 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5323 BE = RD->vbases_end();
5324 BI != BE; ++BI)
5325 if (SMI.shouldDeleteForBase(BI))
5326 return true;
5327 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005328
5329 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005330 FE = RD->field_end(); FI != FE; ++FI)
5331 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005332 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005333 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005334
Richard Smith7d5088a2012-02-18 02:02:13 +00005335 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005336 return true;
5337
5338 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005339}
5340
Richard Smithac713512012-12-08 02:53:02 +00005341/// Perform lookup for a special member of the specified kind, and determine
5342/// whether it is trivial. If the triviality can be determined without the
5343/// lookup, skip it. This is intended for use when determining whether a
5344/// special member of a containing object is trivial, and thus does not ever
5345/// perform overload resolution for default constructors.
5346///
5347/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5348/// member that was most likely to be intended to be trivial, if any.
5349static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5350 Sema::CXXSpecialMember CSM, unsigned Quals,
5351 CXXMethodDecl **Selected) {
5352 if (Selected)
5353 *Selected = 0;
5354
5355 switch (CSM) {
5356 case Sema::CXXInvalid:
5357 llvm_unreachable("not a special member");
5358
5359 case Sema::CXXDefaultConstructor:
5360 // C++11 [class.ctor]p5:
5361 // A default constructor is trivial if:
5362 // - all the [direct subobjects] have trivial default constructors
5363 //
5364 // Note, no overload resolution is performed in this case.
5365 if (RD->hasTrivialDefaultConstructor())
5366 return true;
5367
5368 if (Selected) {
5369 // If there's a default constructor which could have been trivial, dig it
5370 // out. Otherwise, if there's any user-provided default constructor, point
5371 // to that as an example of why there's not a trivial one.
5372 CXXConstructorDecl *DefCtor = 0;
5373 if (RD->needsImplicitDefaultConstructor())
5374 S.DeclareImplicitDefaultConstructor(RD);
5375 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5376 CE = RD->ctor_end(); CI != CE; ++CI) {
5377 if (!CI->isDefaultConstructor())
5378 continue;
5379 DefCtor = *CI;
5380 if (!DefCtor->isUserProvided())
5381 break;
5382 }
5383
5384 *Selected = DefCtor;
5385 }
5386
5387 return false;
5388
5389 case Sema::CXXDestructor:
5390 // C++11 [class.dtor]p5:
5391 // A destructor is trivial if:
5392 // - all the direct [subobjects] have trivial destructors
5393 if (RD->hasTrivialDestructor())
5394 return true;
5395
5396 if (Selected) {
5397 if (RD->needsImplicitDestructor())
5398 S.DeclareImplicitDestructor(RD);
5399 *Selected = RD->getDestructor();
5400 }
5401
5402 return false;
5403
5404 case Sema::CXXCopyConstructor:
5405 // C++11 [class.copy]p12:
5406 // A copy constructor is trivial if:
5407 // - the constructor selected to copy each direct [subobject] is trivial
5408 if (RD->hasTrivialCopyConstructor()) {
5409 if (Quals == Qualifiers::Const)
5410 // We must either select the trivial copy constructor or reach an
5411 // ambiguity; no need to actually perform overload resolution.
5412 return true;
5413 } else if (!Selected) {
5414 return false;
5415 }
5416 // In C++98, we are not supposed to perform overload resolution here, but we
5417 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5418 // cases like B as having a non-trivial copy constructor:
5419 // struct A { template<typename T> A(T&); };
5420 // struct B { mutable A a; };
5421 goto NeedOverloadResolution;
5422
5423 case Sema::CXXCopyAssignment:
5424 // C++11 [class.copy]p25:
5425 // A copy assignment operator is trivial if:
5426 // - the assignment operator selected to copy each direct [subobject] is
5427 // trivial
5428 if (RD->hasTrivialCopyAssignment()) {
5429 if (Quals == Qualifiers::Const)
5430 return true;
5431 } else if (!Selected) {
5432 return false;
5433 }
5434 // In C++98, we are not supposed to perform overload resolution here, but we
5435 // treat that as a language defect.
5436 goto NeedOverloadResolution;
5437
5438 case Sema::CXXMoveConstructor:
5439 case Sema::CXXMoveAssignment:
5440 NeedOverloadResolution:
5441 Sema::SpecialMemberOverloadResult *SMOR =
5442 S.LookupSpecialMember(RD, CSM,
5443 Quals & Qualifiers::Const,
5444 Quals & Qualifiers::Volatile,
5445 /*RValueThis*/false, /*ConstThis*/false,
5446 /*VolatileThis*/false);
5447
5448 // The standard doesn't describe how to behave if the lookup is ambiguous.
5449 // We treat it as not making the member non-trivial, just like the standard
5450 // mandates for the default constructor. This should rarely matter, because
5451 // the member will also be deleted.
5452 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5453 return true;
5454
5455 if (!SMOR->getMethod()) {
5456 assert(SMOR->getKind() ==
5457 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5458 return false;
5459 }
5460
5461 // We deliberately don't check if we found a deleted special member. We're
5462 // not supposed to!
5463 if (Selected)
5464 *Selected = SMOR->getMethod();
5465 return SMOR->getMethod()->isTrivial();
5466 }
5467
5468 llvm_unreachable("unknown special method kind");
5469}
5470
Benjamin Kramera574c892013-02-15 12:30:38 +00005471static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005472 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5473 CI != CE; ++CI)
5474 if (!CI->isImplicit())
5475 return *CI;
5476
5477 // Look for constructor templates.
5478 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5479 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5480 if (CXXConstructorDecl *CD =
5481 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5482 return CD;
5483 }
5484
5485 return 0;
5486}
5487
5488/// The kind of subobject we are checking for triviality. The values of this
5489/// enumeration are used in diagnostics.
5490enum TrivialSubobjectKind {
5491 /// The subobject is a base class.
5492 TSK_BaseClass,
5493 /// The subobject is a non-static data member.
5494 TSK_Field,
5495 /// The object is actually the complete object.
5496 TSK_CompleteObject
5497};
5498
5499/// Check whether the special member selected for a given type would be trivial.
5500static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5501 QualType SubType,
5502 Sema::CXXSpecialMember CSM,
5503 TrivialSubobjectKind Kind,
5504 bool Diagnose) {
5505 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5506 if (!SubRD)
5507 return true;
5508
5509 CXXMethodDecl *Selected;
5510 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5511 Diagnose ? &Selected : 0))
5512 return true;
5513
5514 if (Diagnose) {
5515 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5516 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5517 << Kind << SubType.getUnqualifiedType();
5518 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5519 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5520 } else if (!Selected)
5521 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5522 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5523 else if (Selected->isUserProvided()) {
5524 if (Kind == TSK_CompleteObject)
5525 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5526 << Kind << SubType.getUnqualifiedType() << CSM;
5527 else {
5528 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5529 << Kind << SubType.getUnqualifiedType() << CSM;
5530 S.Diag(Selected->getLocation(), diag::note_declared_at);
5531 }
5532 } else {
5533 if (Kind != TSK_CompleteObject)
5534 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5535 << Kind << SubType.getUnqualifiedType() << CSM;
5536
5537 // Explain why the defaulted or deleted special member isn't trivial.
5538 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5539 }
5540 }
5541
5542 return false;
5543}
5544
5545/// Check whether the members of a class type allow a special member to be
5546/// trivial.
5547static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5548 Sema::CXXSpecialMember CSM,
5549 bool ConstArg, bool Diagnose) {
5550 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5551 FE = RD->field_end(); FI != FE; ++FI) {
5552 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5553 continue;
5554
5555 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5556
5557 // Pretend anonymous struct or union members are members of this class.
5558 if (FI->isAnonymousStructOrUnion()) {
5559 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5560 CSM, ConstArg, Diagnose))
5561 return false;
5562 continue;
5563 }
5564
5565 // C++11 [class.ctor]p5:
5566 // A default constructor is trivial if [...]
5567 // -- no non-static data member of its class has a
5568 // brace-or-equal-initializer
5569 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5570 if (Diagnose)
5571 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5572 return false;
5573 }
5574
5575 // Objective C ARC 4.3.5:
5576 // [...] nontrivally ownership-qualified types are [...] not trivially
5577 // default constructible, copy constructible, move constructible, copy
5578 // assignable, move assignable, or destructible [...]
5579 if (S.getLangOpts().ObjCAutoRefCount &&
5580 FieldType.hasNonTrivialObjCLifetime()) {
5581 if (Diagnose)
5582 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5583 << RD << FieldType.getObjCLifetime();
5584 return false;
5585 }
5586
5587 if (ConstArg && !FI->isMutable())
5588 FieldType.addConst();
5589 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5590 TSK_Field, Diagnose))
5591 return false;
5592 }
5593
5594 return true;
5595}
5596
5597/// Diagnose why the specified class does not have a trivial special member of
5598/// the given kind.
5599void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5600 QualType Ty = Context.getRecordType(RD);
5601 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5602 Ty.addConst();
5603
5604 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5605 TSK_CompleteObject, /*Diagnose*/true);
5606}
5607
5608/// Determine whether a defaulted or deleted special member function is trivial,
5609/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5610/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5611bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5612 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005613 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5614
5615 CXXRecordDecl *RD = MD->getParent();
5616
5617 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005618
5619 // C++11 [class.copy]p12, p25:
5620 // A [special member] is trivial if its declared parameter type is the same
5621 // as if it had been implicitly declared [...]
5622 switch (CSM) {
5623 case CXXDefaultConstructor:
5624 case CXXDestructor:
5625 // Trivial default constructors and destructors cannot have parameters.
5626 break;
5627
5628 case CXXCopyConstructor:
5629 case CXXCopyAssignment: {
5630 // Trivial copy operations always have const, non-volatile parameter types.
5631 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005632 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005633 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5634 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5635 if (Diagnose)
5636 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5637 << Param0->getSourceRange() << Param0->getType()
5638 << Context.getLValueReferenceType(
5639 Context.getRecordType(RD).withConst());
5640 return false;
5641 }
5642 break;
5643 }
5644
5645 case CXXMoveConstructor:
5646 case CXXMoveAssignment: {
5647 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005648 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005649 const RValueReferenceType *RT =
5650 Param0->getType()->getAs<RValueReferenceType>();
5651 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5652 if (Diagnose)
5653 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5654 << Param0->getSourceRange() << Param0->getType()
5655 << Context.getRValueReferenceType(Context.getRecordType(RD));
5656 return false;
5657 }
5658 break;
5659 }
5660
5661 case CXXInvalid:
5662 llvm_unreachable("not a special member");
5663 }
5664
5665 // FIXME: We require that the parameter-declaration-clause is equivalent to
5666 // that of an implicit declaration, not just that the declared parameter type
5667 // matches, in order to prevent absuridities like a function simultaneously
5668 // being a trivial copy constructor and a non-trivial default constructor.
5669 // This issue has not yet been assigned a core issue number.
5670 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5671 if (Diagnose)
5672 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5673 diag::note_nontrivial_default_arg)
5674 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5675 return false;
5676 }
5677 if (MD->isVariadic()) {
5678 if (Diagnose)
5679 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5680 return false;
5681 }
5682
5683 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5684 // A copy/move [constructor or assignment operator] is trivial if
5685 // -- the [member] selected to copy/move each direct base class subobject
5686 // is trivial
5687 //
5688 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5689 // A [default constructor or destructor] is trivial if
5690 // -- all the direct base classes have trivial [default constructors or
5691 // destructors]
5692 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5693 BE = RD->bases_end(); BI != BE; ++BI)
5694 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5695 ConstArg ? BI->getType().withConst()
5696 : BI->getType(),
5697 CSM, TSK_BaseClass, Diagnose))
5698 return false;
5699
5700 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5701 // A copy/move [constructor or assignment operator] for a class X is
5702 // trivial if
5703 // -- for each non-static data member of X that is of class type (or array
5704 // thereof), the constructor selected to copy/move that member is
5705 // trivial
5706 //
5707 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5708 // A [default constructor or destructor] is trivial if
5709 // -- for all of the non-static data members of its class that are of class
5710 // type (or array thereof), each such class has a trivial [default
5711 // constructor or destructor]
5712 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5713 return false;
5714
5715 // C++11 [class.dtor]p5:
5716 // A destructor is trivial if [...]
5717 // -- the destructor is not virtual
5718 if (CSM == CXXDestructor && MD->isVirtual()) {
5719 if (Diagnose)
5720 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5721 return false;
5722 }
5723
5724 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5725 // A [special member] for class X is trivial if [...]
5726 // -- class X has no virtual functions and no virtual base classes
5727 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5728 if (!Diagnose)
5729 return false;
5730
5731 if (RD->getNumVBases()) {
5732 // Check for virtual bases. We already know that the corresponding
5733 // member in all bases is trivial, so vbases must all be direct.
5734 CXXBaseSpecifier &BS = *RD->vbases_begin();
5735 assert(BS.isVirtual());
5736 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5737 return false;
5738 }
5739
5740 // Must have a virtual method.
5741 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5742 ME = RD->method_end(); MI != ME; ++MI) {
5743 if (MI->isVirtual()) {
5744 SourceLocation MLoc = MI->getLocStart();
5745 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5746 return false;
5747 }
5748 }
5749
5750 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5751 }
5752
5753 // Looks like it's trivial!
5754 return true;
5755}
5756
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005757/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005758namespace {
5759 struct FindHiddenVirtualMethodData {
5760 Sema *S;
5761 CXXMethodDecl *Method;
5762 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005763 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005764 };
5765}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005766
David Blaikie5f750682012-10-19 00:53:08 +00005767/// \brief Check whether any most overriden method from MD in Methods
5768static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5769 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5770 if (MD->size_overridden_methods() == 0)
5771 return Methods.count(MD->getCanonicalDecl());
5772 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5773 E = MD->end_overridden_methods();
5774 I != E; ++I)
5775 if (CheckMostOverridenMethods(*I, Methods))
5776 return true;
5777 return false;
5778}
5779
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005780/// \brief Member lookup function that determines whether a given C++
5781/// method overloads virtual methods in a base class without overriding any,
5782/// to be used with CXXRecordDecl::lookupInBases().
5783static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5784 CXXBasePath &Path,
5785 void *UserData) {
5786 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5787
5788 FindHiddenVirtualMethodData &Data
5789 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5790
5791 DeclarationName Name = Data.Method->getDeclName();
5792 assert(Name.getNameKind() == DeclarationName::Identifier);
5793
5794 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005795 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005796 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005797 !Path.Decls.empty();
5798 Path.Decls = Path.Decls.slice(1)) {
5799 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005800 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005801 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005802 foundSameNameMethod = true;
5803 // Interested only in hidden virtual methods.
5804 if (!MD->isVirtual())
5805 continue;
5806 // If the method we are checking overrides a method from its base
5807 // don't warn about the other overloaded methods.
5808 if (!Data.S->IsOverload(Data.Method, MD, false))
5809 return true;
5810 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005811 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005812 overloadedMethods.push_back(MD);
5813 }
5814 }
5815
5816 if (foundSameNameMethod)
5817 Data.OverloadedMethods.append(overloadedMethods.begin(),
5818 overloadedMethods.end());
5819 return foundSameNameMethod;
5820}
5821
David Blaikie5f750682012-10-19 00:53:08 +00005822/// \brief Add the most overriden methods from MD to Methods
5823static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5824 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5825 if (MD->size_overridden_methods() == 0)
5826 Methods.insert(MD->getCanonicalDecl());
5827 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5828 E = MD->end_overridden_methods();
5829 I != E; ++I)
5830 AddMostOverridenMethods(*I, Methods);
5831}
5832
Eli Friedmandae92712013-09-05 23:51:03 +00005833/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005834/// overriding any.
Eli Friedmandae92712013-09-05 23:51:03 +00005835void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5836 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramerc4704422012-05-19 16:03:58 +00005837 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005838 return;
5839
5840 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5841 /*bool RecordPaths=*/false,
5842 /*bool DetectVirtual=*/false);
5843 FindHiddenVirtualMethodData Data;
5844 Data.Method = MD;
5845 Data.S = this;
5846
5847 // Keep the base methods that were overriden or introduced in the subclass
5848 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmandae92712013-09-05 23:51:03 +00005849 CXXRecordDecl *DC = MD->getParent();
David Blaikie3bc93e32012-12-19 00:45:41 +00005850 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5851 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5852 NamedDecl *ND = *I;
5853 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005854 ND = shad->getTargetDecl();
5855 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5856 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005857 }
5858
Eli Friedmandae92712013-09-05 23:51:03 +00005859 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5860 OverloadedMethods = Data.OverloadedMethods;
5861}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005862
Eli Friedmandae92712013-09-05 23:51:03 +00005863void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5864 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5865 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5866 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5867 PartialDiagnostic PD = PDiag(
5868 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5869 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5870 Diag(overloadedMD->getLocation(), PD);
5871 }
5872}
5873
5874/// \brief Diagnose methods which overload virtual methods in a base class
5875/// without overriding any.
5876void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5877 if (MD->isInvalidDecl())
5878 return;
5879
5880 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5881 MD->getLocation()) == DiagnosticsEngine::Ignored)
5882 return;
5883
5884 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5885 FindHiddenVirtualMethods(MD, OverloadedMethods);
5886 if (!OverloadedMethods.empty()) {
5887 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5888 << MD << (OverloadedMethods.size() > 1);
5889
5890 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005891 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005892}
5893
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005894void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005895 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005896 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005897 SourceLocation RBrac,
5898 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005899 if (!TagDecl)
5900 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005901
Douglas Gregor42af25f2009-05-11 19:58:34 +00005902 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005903
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005904 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5905 if (l->getKind() != AttributeList::AT_Visibility)
5906 continue;
5907 l->setInvalid();
5908 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5909 l->getName();
5910 }
5911
David Blaikie77b6de02011-09-22 02:58:26 +00005912 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005913 // strict aliasing violation!
5914 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005915 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005916
Douglas Gregor23c94db2010-07-02 17:43:08 +00005917 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005918 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005919}
5920
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005921/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5922/// special functions, such as the default constructor, copy
5923/// constructor, or destructor, to the given C++ class (C++
5924/// [special]p1). This routine can only be executed just before the
5925/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005926void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005927 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005928 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005929
Richard Smithbc2a35d2012-12-08 08:32:28 +00005930 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005931 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005932
Richard Smithbc2a35d2012-12-08 08:32:28 +00005933 // If the properties or semantics of the copy constructor couldn't be
5934 // determined while the class was being declared, force a declaration
5935 // of it now.
5936 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5937 DeclareImplicitCopyConstructor(ClassDecl);
5938 }
5939
Richard Smith80ad52f2013-01-02 11:42:31 +00005940 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005941 ++ASTContext::NumImplicitMoveConstructors;
5942
Richard Smithbc2a35d2012-12-08 08:32:28 +00005943 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5944 DeclareImplicitMoveConstructor(ClassDecl);
5945 }
5946
Douglas Gregora376d102010-07-02 21:50:04 +00005947 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5948 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005949
5950 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005951 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005952 // it shows up in the right place in the vtable and that we diagnose
5953 // problems with the implicit exception specification.
5954 if (ClassDecl->isDynamicClass() ||
5955 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005956 DeclareImplicitCopyAssignment(ClassDecl);
5957 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005958
Richard Smith80ad52f2013-01-02 11:42:31 +00005959 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005960 ++ASTContext::NumImplicitMoveAssignmentOperators;
5961
5962 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005963 if (ClassDecl->isDynamicClass() ||
5964 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005965 DeclareImplicitMoveAssignment(ClassDecl);
5966 }
5967
Douglas Gregor4923aa22010-07-02 20:37:36 +00005968 if (!ClassDecl->hasUserDeclaredDestructor()) {
5969 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005970
5971 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005972 // have to declare the destructor immediately. This ensures that, e.g., it
5973 // shows up in the right place in the vtable and that we diagnose problems
5974 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005975 if (ClassDecl->isDynamicClass() ||
5976 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005977 DeclareImplicitDestructor(ClassDecl);
5978 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005979}
5980
Francois Pichet8387e2a2011-04-22 22:18:13 +00005981void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5982 if (!D)
5983 return;
5984
5985 int NumParamList = D->getNumTemplateParameterLists();
5986 for (int i = 0; i < NumParamList; i++) {
5987 TemplateParameterList* Params = D->getTemplateParameterList(i);
5988 for (TemplateParameterList::iterator Param = Params->begin(),
5989 ParamEnd = Params->end();
5990 Param != ParamEnd; ++Param) {
5991 NamedDecl *Named = cast<NamedDecl>(*Param);
5992 if (Named->getDeclName()) {
5993 S->AddDecl(Named);
5994 IdResolver.AddDecl(Named);
5995 }
5996 }
5997 }
5998}
5999
John McCalld226f652010-08-21 09:40:31 +00006000void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00006001 if (!D)
6002 return;
6003
6004 TemplateParameterList *Params = 0;
6005 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
6006 Params = Template->getTemplateParameters();
6007 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6008 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6009 Params = PartialSpec->getTemplateParameters();
6010 else
Douglas Gregor6569d682009-05-27 23:11:45 +00006011 return;
6012
Douglas Gregor6569d682009-05-27 23:11:45 +00006013 for (TemplateParameterList::iterator Param = Params->begin(),
6014 ParamEnd = Params->end();
6015 Param != ParamEnd; ++Param) {
6016 NamedDecl *Named = cast<NamedDecl>(*Param);
6017 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00006018 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00006019 IdResolver.AddDecl(Named);
6020 }
6021 }
6022}
6023
John McCalld226f652010-08-21 09:40:31 +00006024void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00006025 if (!RecordD) return;
6026 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00006027 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00006028 PushDeclContext(S, Record);
6029}
6030
John McCalld226f652010-08-21 09:40:31 +00006031void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00006032 if (!RecordD) return;
6033 PopDeclContext();
6034}
6035
Douglas Gregor72b505b2008-12-16 21:30:33 +00006036/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6037/// parsing a top-level (non-nested) C++ class, and we are now
6038/// parsing those parts of the given Method declaration that could
6039/// not be parsed earlier (C++ [class.mem]p2), such as default
6040/// arguments. This action should enter the scope of the given
6041/// Method declaration as if we had just parsed the qualified method
6042/// name. However, it should not bring the parameters into scope;
6043/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00006044void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006045}
6046
6047/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6048/// C++ method declaration. We're (re-)introducing the given
6049/// function parameter into scope for use in parsing later parts of
6050/// the method declaration. For example, we could see an
6051/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00006052void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006053 if (!ParamD)
6054 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006055
John McCalld226f652010-08-21 09:40:31 +00006056 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00006057
6058 // If this parameter has an unparsed default argument, clear it out
6059 // to make way for the parsed default argument.
6060 if (Param->hasUnparsedDefaultArg())
6061 Param->setDefaultArg(0);
6062
John McCalld226f652010-08-21 09:40:31 +00006063 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006064 if (Param->getDeclName())
6065 IdResolver.AddDecl(Param);
6066}
6067
6068/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6069/// processing the delayed method declaration for Method. The method
6070/// declaration is now considered finished. There may be a separate
6071/// ActOnStartOfFunctionDef action later (not necessarily
6072/// immediately!) for this method, if it was also defined inside the
6073/// class body.
John McCalld226f652010-08-21 09:40:31 +00006074void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006075 if (!MethodD)
6076 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006077
Douglas Gregorefd5bda2009-08-24 11:57:43 +00006078 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00006079
John McCalld226f652010-08-21 09:40:31 +00006080 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006081
6082 // Now that we have our default arguments, check the constructor
6083 // again. It could produce additional diagnostics or affect whether
6084 // the class has implicitly-declared destructors, among other
6085 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00006086 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6087 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006088
6089 // Check the default arguments, which we may have added.
6090 if (!Method->isInvalidDecl())
6091 CheckCXXDefaultArguments(Method);
6092}
6093
Douglas Gregor42a552f2008-11-05 20:51:48 +00006094/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00006095/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00006096/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006097/// emit diagnostics and set the invalid bit to true. In any case, the type
6098/// will be updated to reflect a well-formed type for the constructor and
6099/// returned.
6100QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006101 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006102 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006103
6104 // C++ [class.ctor]p3:
6105 // A constructor shall not be virtual (10.3) or static (9.4). A
6106 // constructor can be invoked for a const, volatile or const
6107 // volatile object. A constructor shall not be declared const,
6108 // volatile, or const volatile (9.3.2).
6109 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00006110 if (!D.isInvalidType())
6111 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6112 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6113 << SourceRange(D.getIdentifierLoc());
6114 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006115 }
John McCalld931b082010-08-26 03:08:43 +00006116 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006117 if (!D.isInvalidType())
6118 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6119 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6120 << SourceRange(D.getIdentifierLoc());
6121 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006122 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006123 }
Mike Stump1eb44332009-09-09 15:08:12 +00006124
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006125 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006126 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00006127 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006128 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6129 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006130 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006131 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6132 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006133 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006134 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6135 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00006136 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006137 }
Mike Stump1eb44332009-09-09 15:08:12 +00006138
Douglas Gregorc938c162011-01-26 05:01:58 +00006139 // C++0x [class.ctor]p4:
6140 // A constructor shall not be declared with a ref-qualifier.
6141 if (FTI.hasRefQualifier()) {
6142 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6143 << FTI.RefQualifierIsLValueRef
6144 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6145 D.setInvalidType();
6146 }
6147
Douglas Gregor42a552f2008-11-05 20:51:48 +00006148 // Rebuild the function type "R" without any type qualifiers (in
6149 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00006150 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00006151 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006152 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6153 return R;
6154
6155 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6156 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006157 EPI.RefQualifier = RQ_None;
6158
Richard Smith07b0fdc2013-03-18 21:12:30 +00006159 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006160}
6161
Douglas Gregor72b505b2008-12-16 21:30:33 +00006162/// CheckConstructor - Checks a fully-formed constructor for
6163/// well-formedness, issuing any diagnostics required. Returns true if
6164/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00006165void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00006166 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00006167 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6168 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00006169 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006170
6171 // C++ [class.copy]p3:
6172 // A declaration of a constructor for a class X is ill-formed if
6173 // its first parameter is of type (optionally cv-qualified) X and
6174 // either there are no other parameters or else all other
6175 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00006176 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006177 ((Constructor->getNumParams() == 1) ||
6178 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00006179 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6180 Constructor->getTemplateSpecializationKind()
6181 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006182 QualType ParamType = Constructor->getParamDecl(0)->getType();
6183 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6184 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00006185 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006186 const char *ConstRef
6187 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6188 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00006189 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006190 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00006191
6192 // FIXME: Rather that making the constructor invalid, we should endeavor
6193 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00006194 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006195 }
6196 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00006197}
6198
John McCall15442822010-08-04 01:04:25 +00006199/// CheckDestructor - Checks a fully-formed destructor definition for
6200/// well-formedness, issuing any diagnostics required. Returns true
6201/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006202bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006203 CXXRecordDecl *RD = Destructor->getParent();
6204
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006205 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006206 SourceLocation Loc;
6207
6208 if (!Destructor->isImplicit())
6209 Loc = Destructor->getLocation();
6210 else
6211 Loc = RD->getLocation();
6212
6213 // If we have a virtual destructor, look up the deallocation function
6214 FunctionDecl *OperatorDelete = 0;
6215 DeclarationName Name =
6216 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006217 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00006218 return true;
John McCall5efd91a2010-07-03 18:33:00 +00006219
Eli Friedman5f2987c2012-02-02 03:46:19 +00006220 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00006221
6222 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00006223 }
Anders Carlsson37909802009-11-30 21:24:50 +00006224
6225 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00006226}
6227
Mike Stump1eb44332009-09-09 15:08:12 +00006228static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006229FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6230 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6231 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006232 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006233}
6234
Douglas Gregor42a552f2008-11-05 20:51:48 +00006235/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6236/// the well-formednes of the destructor declarator @p D with type @p
6237/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006238/// emit diagnostics and set the declarator to invalid. Even if this happens,
6239/// will be updated to reflect a well-formed type for the destructor and
6240/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00006241QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006242 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006243 // C++ [class.dtor]p1:
6244 // [...] A typedef-name that names a class is a class-name
6245 // (7.1.3); however, a typedef-name that names a class shall not
6246 // be used as the identifier in the declarator for a destructor
6247 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006248 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006249 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006250 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006251 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006252 else if (const TemplateSpecializationType *TST =
6253 DeclaratorType->getAs<TemplateSpecializationType>())
6254 if (TST->isTypeAlias())
6255 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6256 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006257
6258 // C++ [class.dtor]p2:
6259 // A destructor is used to destroy objects of its class type. A
6260 // destructor takes no parameters, and no return type can be
6261 // specified for it (not even void). The address of a destructor
6262 // shall not be taken. A destructor shall not be static. A
6263 // destructor can be invoked for a const, volatile or const
6264 // volatile object. A destructor shall not be declared const,
6265 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006266 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006267 if (!D.isInvalidType())
6268 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6269 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006270 << SourceRange(D.getIdentifierLoc())
6271 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6272
John McCalld931b082010-08-26 03:08:43 +00006273 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006274 }
Chris Lattner65401802009-04-25 08:28:21 +00006275 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006276 // Destructors don't have return types, but the parser will
6277 // happily parse something like:
6278 //
6279 // class X {
6280 // float ~X();
6281 // };
6282 //
6283 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006284 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6285 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6286 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006287 }
Mike Stump1eb44332009-09-09 15:08:12 +00006288
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006289 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006290 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006291 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006292 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6293 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006294 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006295 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6296 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006297 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006298 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6299 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006300 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006301 }
6302
Douglas Gregorc938c162011-01-26 05:01:58 +00006303 // C++0x [class.dtor]p2:
6304 // A destructor shall not be declared with a ref-qualifier.
6305 if (FTI.hasRefQualifier()) {
6306 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6307 << FTI.RefQualifierIsLValueRef
6308 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6309 D.setInvalidType();
6310 }
6311
Douglas Gregor42a552f2008-11-05 20:51:48 +00006312 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006313 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006314 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6315
6316 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006317 FTI.freeArgs();
6318 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006319 }
6320
Mike Stump1eb44332009-09-09 15:08:12 +00006321 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006322 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006323 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006324 D.setInvalidType();
6325 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006326
6327 // Rebuild the function type "R" without any type qualifiers or
6328 // parameters (in case any of the errors above fired) and with
6329 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006330 // types.
John McCalle23cf432010-12-14 08:05:40 +00006331 if (!D.isInvalidType())
6332 return R;
6333
Douglas Gregord92ec472010-07-01 05:10:53 +00006334 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006335 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6336 EPI.Variadic = false;
6337 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006338 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006339 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006340}
6341
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006342/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6343/// well-formednes of the conversion function declarator @p D with
6344/// type @p R. If there are any errors in the declarator, this routine
6345/// will emit diagnostics and return true. Otherwise, it will return
6346/// false. Either way, the type @p R will be updated to reflect a
6347/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006348void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006349 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006350 // C++ [class.conv.fct]p1:
6351 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006352 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006353 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006354 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006355 if (!D.isInvalidType())
6356 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006357 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6358 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006359 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006360 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006361 }
John McCalla3f81372010-04-13 00:04:31 +00006362
6363 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6364
Chris Lattner6e475012009-04-25 08:35:12 +00006365 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006366 // Conversion functions don't have return types, but the parser will
6367 // happily parse something like:
6368 //
6369 // class X {
6370 // float operator bool();
6371 // };
6372 //
6373 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006374 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6375 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6376 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006377 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006378 }
6379
John McCalla3f81372010-04-13 00:04:31 +00006380 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6381
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006382 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006383 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006384 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6385
6386 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006387 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006388 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006389 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006390 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006391 D.setInvalidType();
6392 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006393
John McCalla3f81372010-04-13 00:04:31 +00006394 // Diagnose "&operator bool()" and other such nonsense. This
6395 // is actually a gcc extension which we don't support.
6396 if (Proto->getResultType() != ConvType) {
6397 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6398 << Proto->getResultType();
6399 D.setInvalidType();
6400 ConvType = Proto->getResultType();
6401 }
6402
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006403 // C++ [class.conv.fct]p4:
6404 // The conversion-type-id shall not represent a function type nor
6405 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006406 if (ConvType->isArrayType()) {
6407 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6408 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006409 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006410 } else if (ConvType->isFunctionType()) {
6411 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6412 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006413 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006414 }
6415
6416 // Rebuild the function type "R" without any parameters (in case any
6417 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006418 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006419 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006420 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006421
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006422 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006423 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006424 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006425 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006426 diag::warn_cxx98_compat_explicit_conversion_functions :
6427 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006428 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006429}
6430
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006431/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6432/// the declaration of the given C++ conversion function. This routine
6433/// is responsible for recording the conversion function in the C++
6434/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006435Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006436 assert(Conversion && "Expected to receive a conversion function declaration");
6437
Douglas Gregor9d350972008-12-12 08:25:50 +00006438 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006439
6440 // Make sure we aren't redeclaring the conversion function.
6441 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006442
6443 // C++ [class.conv.fct]p1:
6444 // [...] A conversion function is never used to convert a
6445 // (possibly cv-qualified) object to the (possibly cv-qualified)
6446 // same object type (or a reference to it), to a (possibly
6447 // cv-qualified) base class of that type (or a reference to it),
6448 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006449 // FIXME: Suppress this warning if the conversion function ends up being a
6450 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006451 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006452 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006453 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006454 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006455 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6456 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006457 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006458 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006459 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6460 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006461 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006462 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006463 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006464 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006465 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006466 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006467 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006468 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006469 }
6470
Douglas Gregore80622f2010-09-29 04:25:11 +00006471 if (FunctionTemplateDecl *ConversionTemplate
6472 = Conversion->getDescribedFunctionTemplate())
6473 return ConversionTemplate;
6474
John McCalld226f652010-08-21 09:40:31 +00006475 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006476}
6477
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006478//===----------------------------------------------------------------------===//
6479// Namespace Handling
6480//===----------------------------------------------------------------------===//
6481
Richard Smithd1a55a62012-10-04 22:13:39 +00006482/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6483/// reopened.
6484static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6485 SourceLocation Loc,
6486 IdentifierInfo *II, bool *IsInline,
6487 NamespaceDecl *PrevNS) {
6488 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006489
Richard Smithc969e6a2012-10-05 01:46:25 +00006490 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6491 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6492 // inline namespaces, with the intention of bringing names into namespace std.
6493 //
6494 // We support this just well enough to get that case working; this is not
6495 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006496 if (*IsInline && II && II->getName().startswith("__atomic") &&
6497 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006498 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006499 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6500 NS = NS->getPreviousDecl())
6501 NS->setInline(*IsInline);
6502 // Patch up the lookup table for the containing namespace. This isn't really
6503 // correct, but it's good enough for this particular case.
6504 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6505 E = PrevNS->decls_end(); I != E; ++I)
6506 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6507 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6508 return;
6509 }
6510
6511 if (PrevNS->isInline())
6512 // The user probably just forgot the 'inline', so suggest that it
6513 // be added back.
6514 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6515 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6516 else
6517 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6518 << IsInline;
6519
6520 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6521 *IsInline = PrevNS->isInline();
6522}
John McCallea318642010-08-26 09:15:37 +00006523
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006524/// ActOnStartNamespaceDef - This is called at the start of a namespace
6525/// definition.
John McCalld226f652010-08-21 09:40:31 +00006526Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006527 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006528 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006529 SourceLocation IdentLoc,
6530 IdentifierInfo *II,
6531 SourceLocation LBrace,
6532 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006533 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6534 // For anonymous namespace, take the location of the left brace.
6535 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006536 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006537 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006538 bool IsStd = false;
6539 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006540 Scope *DeclRegionScope = NamespcScope->getParent();
6541
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006542 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006543 if (II) {
6544 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006545 // The identifier in an original-namespace-definition shall not
6546 // have been previously defined in the declarative region in
6547 // which the original-namespace-definition appears. The
6548 // identifier in an original-namespace-definition is the name of
6549 // the namespace. Subsequently in that declarative region, it is
6550 // treated as an original-namespace-name.
6551 //
6552 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006553 // look through using directives, just look for any ordinary names.
6554
6555 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006556 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6557 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006558 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006559 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6560 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6561 ++I) {
6562 if ((*I)->getIdentifierNamespace() & IDNS) {
6563 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006564 break;
6565 }
6566 }
6567
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006568 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6569
6570 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006571 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006572 if (IsInline != PrevNS->isInline())
6573 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6574 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006575 } else if (PrevDecl) {
6576 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006577 Diag(Loc, diag::err_redefinition_different_kind)
6578 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006579 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006580 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006581 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006582 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006583 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006584 // This is the first "real" definition of the namespace "std", so update
6585 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006586 PrevNS = getStdNamespace();
6587 IsStd = true;
6588 AddToKnown = !IsInline;
6589 } else {
6590 // We've seen this namespace for the first time.
6591 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006592 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006593 } else {
John McCall9aeed322009-10-01 00:25:31 +00006594 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006595
6596 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006597 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006598 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006599 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006600 } else {
6601 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006602 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006603 }
6604
Richard Smithd1a55a62012-10-04 22:13:39 +00006605 if (PrevNS && IsInline != PrevNS->isInline())
6606 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6607 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006608 }
6609
6610 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6611 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006612 if (IsInvalid)
6613 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006614
6615 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006616
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006617 // FIXME: Should we be merging attributes?
6618 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006619 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006620
6621 if (IsStd)
6622 StdNamespace = Namespc;
6623 if (AddToKnown)
6624 KnownNamespaces[Namespc] = false;
6625
6626 if (II) {
6627 PushOnScopeChains(Namespc, DeclRegionScope);
6628 } else {
6629 // Link the anonymous namespace into its parent.
6630 DeclContext *Parent = CurContext->getRedeclContext();
6631 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6632 TU->setAnonymousNamespace(Namespc);
6633 } else {
6634 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006635 }
John McCall9aeed322009-10-01 00:25:31 +00006636
Douglas Gregora4181472010-03-24 00:46:35 +00006637 CurContext->addDecl(Namespc);
6638
John McCall9aeed322009-10-01 00:25:31 +00006639 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6640 // behaves as if it were replaced by
6641 // namespace unique { /* empty body */ }
6642 // using namespace unique;
6643 // namespace unique { namespace-body }
6644 // where all occurrences of 'unique' in a translation unit are
6645 // replaced by the same identifier and this identifier differs
6646 // from all other identifiers in the entire program.
6647
6648 // We just create the namespace with an empty name and then add an
6649 // implicit using declaration, just like the standard suggests.
6650 //
6651 // CodeGen enforces the "universally unique" aspect by giving all
6652 // declarations semantically contained within an anonymous
6653 // namespace internal linkage.
6654
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006655 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006656 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006657 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006658 /* 'using' */ LBrace,
6659 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006660 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006661 /* identifier */ SourceLocation(),
6662 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006663 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006664 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006665 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006666 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006667 }
6668
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006669 ActOnDocumentableDecl(Namespc);
6670
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006671 // Although we could have an invalid decl (i.e. the namespace name is a
6672 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006673 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6674 // for the namespace has the declarations that showed up in that particular
6675 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006676 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006677 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006678}
6679
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006680/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6681/// is a namespace alias, returns the namespace it points to.
6682static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6683 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6684 return AD->getNamespace();
6685 return dyn_cast_or_null<NamespaceDecl>(D);
6686}
6687
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006688/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6689/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006690void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006691 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6692 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006693 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006694 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006695 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006696 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006697}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006698
John McCall384aff82010-08-25 07:42:41 +00006699CXXRecordDecl *Sema::getStdBadAlloc() const {
6700 return cast_or_null<CXXRecordDecl>(
6701 StdBadAlloc.get(Context.getExternalSource()));
6702}
6703
6704NamespaceDecl *Sema::getStdNamespace() const {
6705 return cast_or_null<NamespaceDecl>(
6706 StdNamespace.get(Context.getExternalSource()));
6707}
6708
Douglas Gregor66992202010-06-29 17:53:46 +00006709/// \brief Retrieve the special "std" namespace, which may require us to
6710/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006711NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006712 if (!StdNamespace) {
6713 // The "std" namespace has not yet been defined, so build one implicitly.
6714 StdNamespace = NamespaceDecl::Create(Context,
6715 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006716 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006717 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006718 &PP.getIdentifierTable().get("std"),
6719 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006720 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006721 }
6722
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006723 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006724}
6725
Sebastian Redl395e04d2012-01-17 22:49:33 +00006726bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006727 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006728 "Looking for std::initializer_list outside of C++.");
6729
6730 // We're looking for implicit instantiations of
6731 // template <typename E> class std::initializer_list.
6732
6733 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6734 return false;
6735
Sebastian Redl84760e32012-01-17 22:49:58 +00006736 ClassTemplateDecl *Template = 0;
6737 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006738
Sebastian Redl84760e32012-01-17 22:49:58 +00006739 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006740
Sebastian Redl84760e32012-01-17 22:49:58 +00006741 ClassTemplateSpecializationDecl *Specialization =
6742 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6743 if (!Specialization)
6744 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006745
Sebastian Redl84760e32012-01-17 22:49:58 +00006746 Template = Specialization->getSpecializedTemplate();
6747 Arguments = Specialization->getTemplateArgs().data();
6748 } else if (const TemplateSpecializationType *TST =
6749 Ty->getAs<TemplateSpecializationType>()) {
6750 Template = dyn_cast_or_null<ClassTemplateDecl>(
6751 TST->getTemplateName().getAsTemplateDecl());
6752 Arguments = TST->getArgs();
6753 }
6754 if (!Template)
6755 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006756
6757 if (!StdInitializerList) {
6758 // Haven't recognized std::initializer_list yet, maybe this is it.
6759 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6760 if (TemplateClass->getIdentifier() !=
6761 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006762 !getStdNamespace()->InEnclosingNamespaceSetOf(
6763 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006764 return false;
6765 // This is a template called std::initializer_list, but is it the right
6766 // template?
6767 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006768 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006769 return false;
6770 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6771 return false;
6772
6773 // It's the right template.
6774 StdInitializerList = Template;
6775 }
6776
6777 if (Template != StdInitializerList)
6778 return false;
6779
6780 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006781 if (Element)
6782 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006783 return true;
6784}
6785
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006786static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6787 NamespaceDecl *Std = S.getStdNamespace();
6788 if (!Std) {
6789 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6790 return 0;
6791 }
6792
6793 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6794 Loc, Sema::LookupOrdinaryName);
6795 if (!S.LookupQualifiedName(Result, Std)) {
6796 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6797 return 0;
6798 }
6799 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6800 if (!Template) {
6801 Result.suppressDiagnostics();
6802 // We found something weird. Complain about the first thing we found.
6803 NamedDecl *Found = *Result.begin();
6804 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6805 return 0;
6806 }
6807
6808 // We found some template called std::initializer_list. Now verify that it's
6809 // correct.
6810 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006811 if (Params->getMinRequiredArguments() != 1 ||
6812 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006813 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6814 return 0;
6815 }
6816
6817 return Template;
6818}
6819
6820QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6821 if (!StdInitializerList) {
6822 StdInitializerList = LookupStdInitializerList(*this, Loc);
6823 if (!StdInitializerList)
6824 return QualType();
6825 }
6826
6827 TemplateArgumentListInfo Args(Loc, Loc);
6828 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6829 Context.getTrivialTypeSourceInfo(Element,
6830 Loc)));
6831 return Context.getCanonicalType(
6832 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6833}
6834
Sebastian Redl98d36062012-01-17 22:50:14 +00006835bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6836 // C++ [dcl.init.list]p2:
6837 // A constructor is an initializer-list constructor if its first parameter
6838 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6839 // std::initializer_list<E> for some type E, and either there are no other
6840 // parameters or else all other parameters have default arguments.
6841 if (Ctor->getNumParams() < 1 ||
6842 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6843 return false;
6844
6845 QualType ArgType = Ctor->getParamDecl(0)->getType();
6846 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6847 ArgType = RT->getPointeeType().getUnqualifiedType();
6848
6849 return isStdInitializerList(ArgType, 0);
6850}
6851
Douglas Gregor9172aa62011-03-26 22:25:30 +00006852/// \brief Determine whether a using statement is in a context where it will be
6853/// apply in all contexts.
6854static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6855 switch (CurContext->getDeclKind()) {
6856 case Decl::TranslationUnit:
6857 return true;
6858 case Decl::LinkageSpec:
6859 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6860 default:
6861 return false;
6862 }
6863}
6864
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006865namespace {
6866
6867// Callback to only accept typo corrections that are namespaces.
6868class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006869public:
6870 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6871 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006872 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006873 return false;
6874 }
6875};
6876
6877}
6878
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006879static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6880 CXXScopeSpec &SS,
6881 SourceLocation IdentLoc,
6882 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006883 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006884 R.clear();
6885 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006886 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006887 Validator)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006888 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00006889 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6890 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006891 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00006892 S.diagnoseTypo(Corrected,
6893 S.PDiag(diag::err_using_directive_member_suggest)
6894 << Ident << DC << DroppedSpecifier << SS.getRange(),
6895 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006896 } else {
Richard Smith2d670972013-08-17 00:46:16 +00006897 S.diagnoseTypo(Corrected,
6898 S.PDiag(diag::err_using_directive_suggest) << Ident,
6899 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006900 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006901 R.addDecl(Corrected.getCorrectionDecl());
6902 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006903 }
6904 return false;
6905}
6906
John McCalld226f652010-08-21 09:40:31 +00006907Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006908 SourceLocation UsingLoc,
6909 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006910 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006911 SourceLocation IdentLoc,
6912 IdentifierInfo *NamespcName,
6913 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006914 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6915 assert(NamespcName && "Invalid NamespcName.");
6916 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006917
6918 // This can only happen along a recovery path.
6919 while (S->getFlags() & Scope::TemplateParamScope)
6920 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006921 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006922
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006923 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006924 NestedNameSpecifier *Qualifier = 0;
6925 if (SS.isSet())
6926 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6927
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006928 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006929 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6930 LookupParsedName(R, S, &SS);
6931 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006932 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006933
Douglas Gregor66992202010-06-29 17:53:46 +00006934 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006935 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006936 // Allow "using namespace std;" or "using namespace ::std;" even if
6937 // "std" hasn't been defined yet, for GCC compatibility.
6938 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6939 NamespcName->isStr("std")) {
6940 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006941 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006942 R.resolveKind();
6943 }
6944 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006945 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006946 }
6947
John McCallf36e02d2009-10-09 21:13:30 +00006948 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006949 NamedDecl *Named = R.getFoundDecl();
6950 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6951 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006952 // C++ [namespace.udir]p1:
6953 // A using-directive specifies that the names in the nominated
6954 // namespace can be used in the scope in which the
6955 // using-directive appears after the using-directive. During
6956 // unqualified name lookup (3.4.1), the names appear as if they
6957 // were declared in the nearest enclosing namespace which
6958 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006959 // namespace. [Note: in this context, "contains" means "contains
6960 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006961
6962 // Find enclosing context containing both using-directive and
6963 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006964 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006965 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6966 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6967 CommonAncestor = CommonAncestor->getParent();
6968
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006969 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006970 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006971 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006972
Douglas Gregor9172aa62011-03-26 22:25:30 +00006973 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00006974 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006975 Diag(IdentLoc, diag::warn_using_directive_in_header);
6976 }
6977
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006978 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006979 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006980 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006981 }
6982
Richard Smith6b3d3e52013-02-20 19:22:51 +00006983 if (UDir)
6984 ProcessDeclAttributeList(S, UDir, AttrList);
6985
John McCalld226f652010-08-21 09:40:31 +00006986 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006987}
6988
6989void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006990 // If the scope has an associated entity and the using directive is at
6991 // namespace or translation unit scope, add the UsingDirectiveDecl into
6992 // its lookup structure so qualified name lookup can find it.
Ted Kremenekf0d58612013-10-08 17:08:03 +00006993 DeclContext *Ctx = S->getEntity();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006994 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006995 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006996 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006997 // Otherwise, it is at block sope. The using-directives will affect lookup
6998 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006999 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00007000}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007001
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007002
John McCalld226f652010-08-21 09:40:31 +00007003Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00007004 AccessSpecifier AS,
7005 bool HasUsingKeyword,
7006 SourceLocation UsingLoc,
7007 CXXScopeSpec &SS,
7008 UnqualifiedId &Name,
7009 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007010 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00007011 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007012 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00007013
Douglas Gregor12c118a2009-11-04 16:30:06 +00007014 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00007015 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00007016 case UnqualifiedId::IK_Identifier:
7017 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00007018 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00007019 case UnqualifiedId::IK_ConversionFunctionId:
7020 break;
7021
7022 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00007023 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00007024 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00007025 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00007026 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00007027 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00007028 diag::err_using_decl_constructor)
7029 << SS.getRange();
7030
Richard Smith80ad52f2013-01-02 11:42:31 +00007031 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00007032
John McCalld226f652010-08-21 09:40:31 +00007033 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00007034
7035 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00007036 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00007037 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007038 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00007039
7040 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00007041 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00007042 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00007043 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00007044 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007045
7046 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7047 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00007048 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00007049 return 0;
John McCall604e7f12009-12-08 07:46:18 +00007050
Richard Smith07b0fdc2013-03-18 21:12:30 +00007051 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00007052 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00007053 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00007054 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7055 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00007056 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00007057 }
7058
Douglas Gregor56c04582010-12-16 00:46:58 +00007059 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7060 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7061 return 0;
7062
John McCall9488ea12009-11-17 05:59:44 +00007063 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007064 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007065 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007066 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00007067 if (UD)
7068 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00007069
John McCalld226f652010-08-21 09:40:31 +00007070 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00007071}
7072
Douglas Gregor09acc982010-07-07 23:08:52 +00007073/// \brief Determine whether a using declaration considers the given
7074/// declarations as "equivalent", e.g., if they are redeclarations of
7075/// the same entity or are both typedefs of the same type.
7076static bool
7077IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
7078 bool &SuppressRedeclaration) {
7079 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
7080 SuppressRedeclaration = false;
7081 return true;
7082 }
7083
Richard Smith162e1c12011-04-15 14:24:37 +00007084 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7085 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00007086 SuppressRedeclaration = true;
7087 return Context.hasSameType(TD1->getUnderlyingType(),
7088 TD2->getUnderlyingType());
7089 }
7090
7091 return false;
7092}
7093
7094
John McCall9f54ad42009-12-10 09:41:52 +00007095/// Determines whether to create a using shadow decl for a particular
7096/// decl, given the set of decls existing prior to this using lookup.
7097bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7098 const LookupResult &Previous) {
7099 // Diagnose finding a decl which is not from a base class of the
7100 // current class. We do this now because there are cases where this
7101 // function will silently decide not to build a shadow decl, which
7102 // will pre-empt further diagnostics.
7103 //
7104 // We don't need to do this in C++0x because we do the check once on
7105 // the qualifier.
7106 //
7107 // FIXME: diagnose the following if we care enough:
7108 // struct A { int foo; };
7109 // struct B : A { using A::foo; };
7110 // template <class T> struct C : A {};
7111 // template <class T> struct D : C<T> { using B::foo; } // <---
7112 // This is invalid (during instantiation) in C++03 because B::foo
7113 // resolves to the using decl in B, which is not a base class of D<T>.
7114 // We can't diagnose it immediately because C<T> is an unknown
7115 // specialization. The UsingShadowDecl in D<T> then points directly
7116 // to A::foo, which will look well-formed when we instantiate.
7117 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00007118 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00007119 DeclContext *OrigDC = Orig->getDeclContext();
7120
7121 // Handle enums and anonymous structs.
7122 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7123 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7124 while (OrigRec->isAnonymousStructOrUnion())
7125 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7126
7127 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7128 if (OrigDC == CurContext) {
7129 Diag(Using->getLocation(),
7130 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007131 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007132 Diag(Orig->getLocation(), diag::note_using_decl_target);
7133 return true;
7134 }
7135
Douglas Gregordc355712011-02-25 00:36:19 +00007136 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00007137 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007138 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00007139 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00007140 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007141 Diag(Orig->getLocation(), diag::note_using_decl_target);
7142 return true;
7143 }
7144 }
7145
7146 if (Previous.empty()) return false;
7147
7148 NamedDecl *Target = Orig;
7149 if (isa<UsingShadowDecl>(Target))
7150 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7151
John McCalld7533ec2009-12-11 02:33:26 +00007152 // If the target happens to be one of the previous declarations, we
7153 // don't have a conflict.
7154 //
7155 // FIXME: but we might be increasing its access, in which case we
7156 // should redeclare it.
7157 NamedDecl *NonTag = 0, *Tag = 0;
7158 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7159 I != E; ++I) {
7160 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00007161 bool Result;
7162 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
7163 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00007164
7165 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7166 }
7167
John McCall9f54ad42009-12-10 09:41:52 +00007168 if (Target->isFunctionOrFunctionTemplate()) {
7169 FunctionDecl *FD;
7170 if (isa<FunctionTemplateDecl>(Target))
7171 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7172 else
7173 FD = cast<FunctionDecl>(Target);
7174
7175 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00007176 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00007177 case Ovl_Overload:
7178 return false;
7179
7180 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00007181 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007182 break;
7183
7184 // We found a decl with the exact signature.
7185 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007186 // If we're in a record, we want to hide the target, so we
7187 // return true (without a diagnostic) to tell the caller not to
7188 // build a shadow decl.
7189 if (CurContext->isRecord())
7190 return true;
7191
7192 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00007193 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007194 break;
7195 }
7196
7197 Diag(Target->getLocation(), diag::note_using_decl_target);
7198 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7199 return true;
7200 }
7201
7202 // Target is not a function.
7203
John McCall9f54ad42009-12-10 09:41:52 +00007204 if (isa<TagDecl>(Target)) {
7205 // No conflict between a tag and a non-tag.
7206 if (!Tag) return false;
7207
John McCall41ce66f2009-12-10 19:51:03 +00007208 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007209 Diag(Target->getLocation(), diag::note_using_decl_target);
7210 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7211 return true;
7212 }
7213
7214 // No conflict between a tag and a non-tag.
7215 if (!NonTag) return false;
7216
John McCall41ce66f2009-12-10 19:51:03 +00007217 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007218 Diag(Target->getLocation(), diag::note_using_decl_target);
7219 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7220 return true;
7221}
7222
John McCall9488ea12009-11-17 05:59:44 +00007223/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00007224UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00007225 UsingDecl *UD,
7226 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00007227
7228 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00007229 NamedDecl *Target = Orig;
7230 if (isa<UsingShadowDecl>(Target)) {
7231 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7232 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00007233 }
7234
7235 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00007236 = UsingShadowDecl::Create(Context, CurContext,
7237 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00007238 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00007239
7240 Shadow->setAccess(UD->getAccess());
7241 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7242 Shadow->setInvalidDecl();
7243
John McCall9488ea12009-11-17 05:59:44 +00007244 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007245 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007246 else
John McCall604e7f12009-12-08 07:46:18 +00007247 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007248
John McCall604e7f12009-12-08 07:46:18 +00007249
John McCall9f54ad42009-12-10 09:41:52 +00007250 return Shadow;
7251}
John McCall604e7f12009-12-08 07:46:18 +00007252
John McCall9f54ad42009-12-10 09:41:52 +00007253/// Hides a using shadow declaration. This is required by the current
7254/// using-decl implementation when a resolvable using declaration in a
7255/// class is followed by a declaration which would hide or override
7256/// one or more of the using decl's targets; for example:
7257///
7258/// struct Base { void foo(int); };
7259/// struct Derived : Base {
7260/// using Base::foo;
7261/// void foo(int);
7262/// };
7263///
7264/// The governing language is C++03 [namespace.udecl]p12:
7265///
7266/// When a using-declaration brings names from a base class into a
7267/// derived class scope, member functions in the derived class
7268/// override and/or hide member functions with the same name and
7269/// parameter types in a base class (rather than conflicting).
7270///
7271/// There are two ways to implement this:
7272/// (1) optimistically create shadow decls when they're not hidden
7273/// by existing declarations, or
7274/// (2) don't create any shadow decls (or at least don't make them
7275/// visible) until we've fully parsed/instantiated the class.
7276/// The problem with (1) is that we might have to retroactively remove
7277/// a shadow decl, which requires several O(n) operations because the
7278/// decl structures are (very reasonably) not designed for removal.
7279/// (2) avoids this but is very fiddly and phase-dependent.
7280void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007281 if (Shadow->getDeclName().getNameKind() ==
7282 DeclarationName::CXXConversionFunctionName)
7283 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7284
John McCall9f54ad42009-12-10 09:41:52 +00007285 // Remove it from the DeclContext...
7286 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007287
John McCall9f54ad42009-12-10 09:41:52 +00007288 // ...and the scope, if applicable...
7289 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007290 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007291 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007292 }
7293
John McCall9f54ad42009-12-10 09:41:52 +00007294 // ...and the using decl.
7295 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7296
7297 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007298 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007299}
7300
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007301namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007302class UsingValidatorCCC : public CorrectionCandidateCallback {
7303public:
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007304 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7305 bool RequireMember)
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007306 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007307 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007308
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007309 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7310 NamedDecl *ND = Candidate.getCorrectionDecl();
7311
7312 // Keywords are not valid here.
7313 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007314 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007315
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007316 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7317 !isa<TypeDecl>(ND))
7318 return false;
7319
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007320 // Completely unqualified names are invalid for a 'using' declaration.
7321 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7322 return false;
7323
7324 if (isa<TypeDecl>(ND))
7325 return HasTypenameKeyword || !IsInstantiation;
7326
7327 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007328 }
7329
7330private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007331 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007332 bool IsInstantiation;
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007333 bool RequireMember;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007334};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007335} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007336
John McCall7ba107a2009-11-18 02:36:19 +00007337/// Builds a using declaration.
7338///
7339/// \param IsInstantiation - Whether this call arises from an
7340/// instantiation of an unresolved using declaration. We treat
7341/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007342NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7343 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007344 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007345 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007346 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007347 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007348 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007349 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007350 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007351 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007352 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007353
Anders Carlsson550b14b2009-08-28 05:49:21 +00007354 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007355
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007356 if (SS.isEmpty()) {
7357 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007358 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007359 }
Mike Stump1eb44332009-09-09 15:08:12 +00007360
John McCall9f54ad42009-12-10 09:41:52 +00007361 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007362 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007363 ForRedeclaration);
7364 Previous.setHideTags(false);
7365 if (S) {
7366 LookupName(Previous, S);
7367
7368 // It is really dumb that we have to do this.
7369 LookupResult::Filter F = Previous.makeFilter();
7370 while (F.hasNext()) {
7371 NamedDecl *D = F.next();
7372 if (!isDeclInScope(D, CurContext, S))
7373 F.erase();
7374 }
7375 F.done();
7376 } else {
7377 assert(IsInstantiation && "no scope in non-instantiation");
7378 assert(CurContext->isRecord() && "scope not record in instantiation");
7379 LookupQualifiedName(Previous, CurContext);
7380 }
7381
John McCall9f54ad42009-12-10 09:41:52 +00007382 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007383 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7384 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007385 return 0;
7386
7387 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007388 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7389 return 0;
7390
John McCallaf8e6ed2009-11-12 03:15:40 +00007391 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007392 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007393 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007394 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007395 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007396 // FIXME: not all declaration name kinds are legal here
7397 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7398 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007399 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007400 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007401 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007402 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7403 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007404 }
John McCalled976492009-12-04 22:46:56 +00007405 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007406 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007407 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007408 }
John McCalled976492009-12-04 22:46:56 +00007409 D->setAccess(AS);
7410 CurContext->addDecl(D);
7411
7412 if (!LookupContext) return D;
7413 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007414
John McCall77bb1aa2010-05-01 00:40:08 +00007415 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007416 UD->setInvalidDecl();
7417 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007418 }
7419
Richard Smithc5a89a12012-04-02 01:30:27 +00007420 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007421 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007422 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007423 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007424 return UD;
7425 }
7426
7427 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007428
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007429 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007430
John McCall604e7f12009-12-08 07:46:18 +00007431 // Unlike most lookups, we don't always want to hide tag
7432 // declarations: tag names are visible through the using declaration
7433 // even if hidden by ordinary names, *except* in a dependent context
7434 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007435 if (!IsInstantiation)
7436 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007437
John McCallb9abd8722012-04-07 03:04:20 +00007438 // For the purposes of this lookup, we have a base object type
7439 // equal to that of the current context.
7440 if (CurContext->isRecord()) {
7441 R.setBaseObjectType(
7442 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7443 }
7444
John McCalla24dc2e2009-11-17 02:14:36 +00007445 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007446
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007447 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007448 if (R.empty()) {
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007449 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7450 CurContext->isRecord());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007451 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7452 R.getLookupKind(), S, &SS, CCC)){
7453 // We reject any correction for which ND would be NULL.
7454 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007455 R.setLookupName(Corrected.getCorrection());
7456 R.addDecl(ND);
Richard Smith2d670972013-08-17 00:46:16 +00007457 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007458 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007459 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7460 << NameInfo.getName() << LookupContext << 0
7461 << SS.getRange());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007462 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007463 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007464 << NameInfo.getName() << LookupContext << SS.getRange();
7465 UD->setInvalidDecl();
7466 return UD;
7467 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007468 }
7469
John McCalled976492009-12-04 22:46:56 +00007470 if (R.isAmbiguous()) {
7471 UD->setInvalidDecl();
7472 return UD;
7473 }
Mike Stump1eb44332009-09-09 15:08:12 +00007474
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007475 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007476 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007477 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007478 Diag(IdentLoc, diag::err_using_typename_non_type);
7479 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7480 Diag((*I)->getUnderlyingDecl()->getLocation(),
7481 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007482 UD->setInvalidDecl();
7483 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007484 }
7485 } else {
7486 // If we asked for a non-typename and we got a type, error out,
7487 // but only if this is an instantiation of an unresolved using
7488 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007489 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007490 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7491 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007492 UD->setInvalidDecl();
7493 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007494 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007495 }
7496
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007497 // C++0x N2914 [namespace.udecl]p6:
7498 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007499 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007500 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7501 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007502 UD->setInvalidDecl();
7503 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007504 }
Mike Stump1eb44332009-09-09 15:08:12 +00007505
John McCall9f54ad42009-12-10 09:41:52 +00007506 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7507 if (!CheckUsingShadowDecl(UD, *I, Previous))
7508 BuildUsingShadowDecl(S, UD, *I);
7509 }
John McCall9488ea12009-11-17 05:59:44 +00007510
7511 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007512}
7513
Sebastian Redlf677ea32011-02-05 19:23:19 +00007514/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007515bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007516 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007517
Douglas Gregordc355712011-02-25 00:36:19 +00007518 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007519 assert(SourceType &&
7520 "Using decl naming constructor doesn't have type in scope spec.");
7521 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7522
7523 // Check whether the named type is a direct base class.
7524 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7525 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7526 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7527 BaseIt != BaseE; ++BaseIt) {
7528 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7529 if (CanonicalSourceType == BaseType)
7530 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007531 if (BaseIt->getType()->isDependentType())
7532 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007533 }
7534
7535 if (BaseIt == BaseE) {
7536 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007537 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007538 diag::err_using_decl_constructor_not_in_direct_base)
7539 << UD->getNameInfo().getSourceRange()
7540 << QualType(SourceType, 0) << TargetClass;
7541 return true;
7542 }
7543
Richard Smithc5a89a12012-04-02 01:30:27 +00007544 if (!CurContext->isDependentContext())
7545 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007546
7547 return false;
7548}
7549
John McCall9f54ad42009-12-10 09:41:52 +00007550/// Checks that the given using declaration is not an invalid
7551/// redeclaration. Note that this is checking only for the using decl
7552/// itself, not for any ill-formedness among the UsingShadowDecls.
7553bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007554 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007555 const CXXScopeSpec &SS,
7556 SourceLocation NameLoc,
7557 const LookupResult &Prev) {
7558 // C++03 [namespace.udecl]p8:
7559 // C++0x [namespace.udecl]p10:
7560 // A using-declaration is a declaration and can therefore be used
7561 // repeatedly where (and only where) multiple declarations are
7562 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007563 //
John McCall8a726212010-11-29 18:01:58 +00007564 // That's in non-member contexts.
7565 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007566 return false;
7567
7568 NestedNameSpecifier *Qual
7569 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7570
7571 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7572 NamedDecl *D = *I;
7573
7574 bool DTypename;
7575 NestedNameSpecifier *DQual;
7576 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007577 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007578 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007579 } else if (UnresolvedUsingValueDecl *UD
7580 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7581 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007582 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007583 } else if (UnresolvedUsingTypenameDecl *UD
7584 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7585 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007586 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007587 } else continue;
7588
7589 // using decls differ if one says 'typename' and the other doesn't.
7590 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007591 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007592
7593 // using decls differ if they name different scopes (but note that
7594 // template instantiation can cause this check to trigger when it
7595 // didn't before instantiation).
7596 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7597 Context.getCanonicalNestedNameSpecifier(DQual))
7598 continue;
7599
7600 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007601 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007602 return true;
7603 }
7604
7605 return false;
7606}
7607
John McCall604e7f12009-12-08 07:46:18 +00007608
John McCalled976492009-12-04 22:46:56 +00007609/// Checks that the given nested-name qualifier used in a using decl
7610/// in the current context is appropriately related to the current
7611/// scope. If an error is found, diagnoses it and returns true.
7612bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7613 const CXXScopeSpec &SS,
7614 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007615 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007616
John McCall604e7f12009-12-08 07:46:18 +00007617 if (!CurContext->isRecord()) {
7618 // C++03 [namespace.udecl]p3:
7619 // C++0x [namespace.udecl]p8:
7620 // A using-declaration for a class member shall be a member-declaration.
7621
7622 // If we weren't able to compute a valid scope, it must be a
7623 // dependent class scope.
7624 if (!NamedContext || NamedContext->isRecord()) {
7625 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7626 << SS.getRange();
7627 return true;
7628 }
7629
7630 // Otherwise, everything is known to be fine.
7631 return false;
7632 }
7633
7634 // The current scope is a record.
7635
7636 // If the named context is dependent, we can't decide much.
7637 if (!NamedContext) {
7638 // FIXME: in C++0x, we can diagnose if we can prove that the
7639 // nested-name-specifier does not refer to a base class, which is
7640 // still possible in some cases.
7641
7642 // Otherwise we have to conservatively report that things might be
7643 // okay.
7644 return false;
7645 }
7646
7647 if (!NamedContext->isRecord()) {
7648 // Ideally this would point at the last name in the specifier,
7649 // but we don't have that level of source info.
7650 Diag(SS.getRange().getBegin(),
7651 diag::err_using_decl_nested_name_specifier_is_not_class)
7652 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7653 return true;
7654 }
7655
Douglas Gregor6fb07292010-12-21 07:41:49 +00007656 if (!NamedContext->isDependentContext() &&
7657 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7658 return true;
7659
Richard Smith80ad52f2013-01-02 11:42:31 +00007660 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007661 // C++0x [namespace.udecl]p3:
7662 // In a using-declaration used as a member-declaration, the
7663 // nested-name-specifier shall name a base class of the class
7664 // being defined.
7665
7666 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7667 cast<CXXRecordDecl>(NamedContext))) {
7668 if (CurContext == NamedContext) {
7669 Diag(NameLoc,
7670 diag::err_using_decl_nested_name_specifier_is_current_class)
7671 << SS.getRange();
7672 return true;
7673 }
7674
7675 Diag(SS.getRange().getBegin(),
7676 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7677 << (NestedNameSpecifier*) SS.getScopeRep()
7678 << cast<CXXRecordDecl>(CurContext)
7679 << SS.getRange();
7680 return true;
7681 }
7682
7683 return false;
7684 }
7685
7686 // C++03 [namespace.udecl]p4:
7687 // A using-declaration used as a member-declaration shall refer
7688 // to a member of a base class of the class being defined [etc.].
7689
7690 // Salient point: SS doesn't have to name a base class as long as
7691 // lookup only finds members from base classes. Therefore we can
7692 // diagnose here only if we can prove that that can't happen,
7693 // i.e. if the class hierarchies provably don't intersect.
7694
7695 // TODO: it would be nice if "definitely valid" results were cached
7696 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7697 // need to be repeated.
7698
7699 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007700 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007701
7702 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7703 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7704 Data->Bases.insert(Base);
7705 return true;
7706 }
7707
7708 bool hasDependentBases(const CXXRecordDecl *Class) {
7709 return !Class->forallBases(collect, this);
7710 }
7711
7712 /// Returns true if the base is dependent or is one of the
7713 /// accumulated base classes.
7714 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7715 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7716 return !Data->Bases.count(Base);
7717 }
7718
7719 bool mightShareBases(const CXXRecordDecl *Class) {
7720 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7721 }
7722 };
7723
7724 UserData Data;
7725
7726 // Returns false if we find a dependent base.
7727 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7728 return false;
7729
7730 // Returns false if the class has a dependent base or if it or one
7731 // of its bases is present in the base set of the current context.
7732 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7733 return false;
7734
7735 Diag(SS.getRange().getBegin(),
7736 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7737 << (NestedNameSpecifier*) SS.getScopeRep()
7738 << cast<CXXRecordDecl>(CurContext)
7739 << SS.getRange();
7740
7741 return true;
John McCalled976492009-12-04 22:46:56 +00007742}
7743
Richard Smith162e1c12011-04-15 14:24:37 +00007744Decl *Sema::ActOnAliasDeclaration(Scope *S,
7745 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007746 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007747 SourceLocation UsingLoc,
7748 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007749 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007750 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007751 // Skip up to the relevant declaration scope.
7752 while (S->getFlags() & Scope::TemplateParamScope)
7753 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007754 assert((S->getFlags() & Scope::DeclScope) &&
7755 "got alias-declaration outside of declaration scope");
7756
7757 if (Type.isInvalid())
7758 return 0;
7759
7760 bool Invalid = false;
7761 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7762 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007763 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007764
7765 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7766 return 0;
7767
7768 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007769 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007770 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007771 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7772 TInfo->getTypeLoc().getBeginLoc());
7773 }
Richard Smith162e1c12011-04-15 14:24:37 +00007774
7775 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7776 LookupName(Previous, S);
7777
7778 // Warn about shadowing the name of a template parameter.
7779 if (Previous.isSingleResult() &&
7780 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007781 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007782 Previous.clear();
7783 }
7784
7785 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7786 "name in alias declaration must be an identifier");
7787 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7788 Name.StartLocation,
7789 Name.Identifier, TInfo);
7790
7791 NewTD->setAccess(AS);
7792
7793 if (Invalid)
7794 NewTD->setInvalidDecl();
7795
Richard Smith6b3d3e52013-02-20 19:22:51 +00007796 ProcessDeclAttributeList(S, NewTD, AttrList);
7797
Richard Smith3e4c6c42011-05-05 21:57:07 +00007798 CheckTypedefForVariablyModifiedType(S, NewTD);
7799 Invalid |= NewTD->isInvalidDecl();
7800
Richard Smith162e1c12011-04-15 14:24:37 +00007801 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007802
7803 NamedDecl *NewND;
7804 if (TemplateParamLists.size()) {
7805 TypeAliasTemplateDecl *OldDecl = 0;
7806 TemplateParameterList *OldTemplateParams = 0;
7807
7808 if (TemplateParamLists.size() != 1) {
7809 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007810 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7811 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007812 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007813 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007814
7815 // Only consider previous declarations in the same scope.
7816 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7817 /*ExplicitInstantiationOrSpecialization*/false);
7818 if (!Previous.empty()) {
7819 Redeclaration = true;
7820
7821 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7822 if (!OldDecl && !Invalid) {
7823 Diag(UsingLoc, diag::err_redefinition_different_kind)
7824 << Name.Identifier;
7825
7826 NamedDecl *OldD = Previous.getRepresentativeDecl();
7827 if (OldD->getLocation().isValid())
7828 Diag(OldD->getLocation(), diag::note_previous_definition);
7829
7830 Invalid = true;
7831 }
7832
7833 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7834 if (TemplateParameterListsAreEqual(TemplateParams,
7835 OldDecl->getTemplateParameters(),
7836 /*Complain=*/true,
7837 TPL_TemplateMatch))
7838 OldTemplateParams = OldDecl->getTemplateParameters();
7839 else
7840 Invalid = true;
7841
7842 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7843 if (!Invalid &&
7844 !Context.hasSameType(OldTD->getUnderlyingType(),
7845 NewTD->getUnderlyingType())) {
7846 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7847 // but we can't reasonably accept it.
7848 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7849 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7850 if (OldTD->getLocation().isValid())
7851 Diag(OldTD->getLocation(), diag::note_previous_definition);
7852 Invalid = true;
7853 }
7854 }
7855 }
7856
7857 // Merge any previous default template arguments into our parameters,
7858 // and check the parameter list.
7859 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7860 TPC_TypeAliasTemplate))
7861 return 0;
7862
7863 TypeAliasTemplateDecl *NewDecl =
7864 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7865 Name.Identifier, TemplateParams,
7866 NewTD);
7867
7868 NewDecl->setAccess(AS);
7869
7870 if (Invalid)
7871 NewDecl->setInvalidDecl();
7872 else if (OldDecl)
Rafael Espindolabc650912013-10-17 15:37:26 +00007873 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007874
7875 NewND = NewDecl;
7876 } else {
7877 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7878 NewND = NewTD;
7879 }
Richard Smith162e1c12011-04-15 14:24:37 +00007880
7881 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007882 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007883
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007884 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007885 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007886}
7887
John McCalld226f652010-08-21 09:40:31 +00007888Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007889 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007890 SourceLocation AliasLoc,
7891 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007892 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007893 SourceLocation IdentLoc,
7894 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007895
Anders Carlsson81c85c42009-03-28 23:53:49 +00007896 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007897 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7898 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007899
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007900 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007901 NamedDecl *PrevDecl
7902 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7903 ForRedeclaration);
7904 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7905 PrevDecl = 0;
7906
7907 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007908 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007909 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007910 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007911 // FIXME: At some point, we'll want to create the (redundant)
7912 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007913 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007914 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007915 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007916 }
Mike Stump1eb44332009-09-09 15:08:12 +00007917
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007918 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7919 diag::err_redefinition_different_kind;
7920 Diag(AliasLoc, DiagID) << Alias;
7921 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007922 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007923 }
7924
John McCalla24dc2e2009-11-17 02:14:36 +00007925 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007926 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007927
John McCallf36e02d2009-10-09 21:13:30 +00007928 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007929 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007930 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007931 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007932 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007933 }
Mike Stump1eb44332009-09-09 15:08:12 +00007934
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007935 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007936 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007937 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007938 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007939
John McCall3dbd3d52010-02-16 06:53:13 +00007940 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007941 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007942}
7943
Sean Hunt001cad92011-05-10 00:49:42 +00007944Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007945Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7946 CXXMethodDecl *MD) {
7947 CXXRecordDecl *ClassDecl = MD->getParent();
7948
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007949 // C++ [except.spec]p14:
7950 // An implicitly declared special member function (Clause 12) shall have an
7951 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007952 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007953 if (ClassDecl->isInvalidDecl())
7954 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007955
Sebastian Redl60618fa2011-03-12 11:50:43 +00007956 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007957 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7958 BEnd = ClassDecl->bases_end();
7959 B != BEnd; ++B) {
7960 if (B->isVirtual()) // Handled below.
7961 continue;
7962
Douglas Gregor18274032010-07-03 00:47:00 +00007963 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7964 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007965 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7966 // If this is a deleted function, add it anyway. This might be conformant
7967 // with the standard. This might not. I'm not sure. It might not matter.
7968 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007969 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007970 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007971 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007972
7973 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007974 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7975 BEnd = ClassDecl->vbases_end();
7976 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007977 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7978 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007979 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7980 // If this is a deleted function, add it anyway. This might be conformant
7981 // with the standard. This might not. I'm not sure. It might not matter.
7982 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007983 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007984 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007985 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007986
7987 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007988 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7989 FEnd = ClassDecl->field_end();
7990 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007991 if (F->hasInClassInitializer()) {
7992 if (Expr *E = F->getInClassInitializer())
7993 ExceptSpec.CalledExpr(E);
7994 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007995 // DR1351:
7996 // If the brace-or-equal-initializer of a non-static data member
7997 // invokes a defaulted default constructor of its class or of an
7998 // enclosing class in a potentially evaluated subexpression, the
7999 // program is ill-formed.
8000 //
8001 // This resolution is unworkable: the exception specification of the
8002 // default constructor can be needed in an unevaluated context, in
8003 // particular, in the operand of a noexcept-expression, and we can be
8004 // unable to compute an exception specification for an enclosed class.
8005 //
8006 // We do not allow an in-class initializer to require the evaluation
8007 // of the exception specification for any in-class initializer whose
8008 // definition is not lexically complete.
8009 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00008010 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00008011 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00008012 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8013 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8014 // If this is a deleted function, add it anyway. This might be conformant
8015 // with the standard. This might not. I'm not sure. It might not matter.
8016 // In particular, the problem is that this function never gets called. It
8017 // might just be ill-formed because this function attempts to refer to
8018 // a deleted function here.
8019 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008020 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008021 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008022 }
John McCalle23cf432010-12-14 08:05:40 +00008023
Sean Hunt001cad92011-05-10 00:49:42 +00008024 return ExceptSpec;
8025}
8026
Richard Smith07b0fdc2013-03-18 21:12:30 +00008027Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00008028Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8029 CXXRecordDecl *ClassDecl = CD->getParent();
8030
8031 // C++ [except.spec]p14:
8032 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00008033 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00008034 if (ClassDecl->isInvalidDecl())
8035 return ExceptSpec;
8036
8037 // Inherited constructor.
8038 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8039 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8040 // FIXME: Copying or moving the parameters could add extra exceptions to the
8041 // set, as could the default arguments for the inherited constructor. This
8042 // will be addressed when we implement the resolution of core issue 1351.
8043 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8044
8045 // Direct base-class constructors.
8046 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8047 BEnd = ClassDecl->bases_end();
8048 B != BEnd; ++B) {
8049 if (B->isVirtual()) // Handled below.
8050 continue;
8051
8052 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8053 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8054 if (BaseClassDecl == InheritedDecl)
8055 continue;
8056 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8057 if (Constructor)
8058 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8059 }
8060 }
8061
8062 // Virtual base-class constructors.
8063 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8064 BEnd = ClassDecl->vbases_end();
8065 B != BEnd; ++B) {
8066 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8067 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8068 if (BaseClassDecl == InheritedDecl)
8069 continue;
8070 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8071 if (Constructor)
8072 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8073 }
8074 }
8075
8076 // Field constructors.
8077 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8078 FEnd = ClassDecl->field_end();
8079 F != FEnd; ++F) {
8080 if (F->hasInClassInitializer()) {
8081 if (Expr *E = F->getInClassInitializer())
8082 ExceptSpec.CalledExpr(E);
8083 else if (!F->isInvalidDecl())
8084 Diag(CD->getLocation(),
8085 diag::err_in_class_initializer_references_def_ctor) << CD;
8086 } else if (const RecordType *RecordTy
8087 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8088 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8089 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8090 if (Constructor)
8091 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8092 }
8093 }
8094
Richard Smith07b0fdc2013-03-18 21:12:30 +00008095 return ExceptSpec;
8096}
8097
Richard Smithafb49182012-11-29 01:34:07 +00008098namespace {
8099/// RAII object to register a special member as being currently declared.
8100struct DeclaringSpecialMember {
8101 Sema &S;
8102 Sema::SpecialMemberDecl D;
8103 bool WasAlreadyBeingDeclared;
8104
8105 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8106 : S(S), D(RD, CSM) {
8107 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8108 if (WasAlreadyBeingDeclared)
8109 // This almost never happens, but if it does, ensure that our cache
8110 // doesn't contain a stale result.
8111 S.SpecialMemberCache.clear();
8112
8113 // FIXME: Register a note to be produced if we encounter an error while
8114 // declaring the special member.
8115 }
8116 ~DeclaringSpecialMember() {
8117 if (!WasAlreadyBeingDeclared)
8118 S.SpecialMembersBeingDeclared.erase(D);
8119 }
8120
8121 /// \brief Are we already trying to declare this special member?
8122 bool isAlreadyBeingDeclared() const {
8123 return WasAlreadyBeingDeclared;
8124 }
8125};
8126}
8127
Sean Hunt001cad92011-05-10 00:49:42 +00008128CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8129 CXXRecordDecl *ClassDecl) {
8130 // C++ [class.ctor]p5:
8131 // A default constructor for a class X is a constructor of class X
8132 // that can be called without an argument. If there is no
8133 // user-declared constructor for class X, a default constructor is
8134 // implicitly declared. An implicitly-declared default constructor
8135 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00008136 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00008137 "Should not build implicit default constructor!");
8138
Richard Smithafb49182012-11-29 01:34:07 +00008139 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8140 if (DSM.isAlreadyBeingDeclared())
8141 return 0;
8142
Richard Smith7756afa2012-06-10 05:43:50 +00008143 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8144 CXXDefaultConstructor,
8145 false);
8146
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008147 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00008148 CanQualType ClassType
8149 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008150 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008151 DeclarationName Name
8152 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008153 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00008154 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008155 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008156 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008157 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00008158 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00008159 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008160 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008161
8162 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008163 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008164 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008165
Richard Smithbc2a35d2012-12-08 08:32:28 +00008166 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8167 // constructors is easy to compute.
8168 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8169
8170 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008171 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008172
Douglas Gregor18274032010-07-03 00:47:00 +00008173 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00008174 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00008175
Douglas Gregor23c94db2010-07-02 17:43:08 +00008176 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00008177 PushOnScopeChains(DefaultCon, S, false);
8178 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00008179
Douglas Gregor32df23e2010-07-01 22:02:46 +00008180 return DefaultCon;
8181}
8182
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008183void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8184 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00008185 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008186 !Constructor->doesThisDeclarationHaveABody() &&
8187 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00008188 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008189
Anders Carlssonf6513ed2010-04-23 16:04:08 +00008190 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00008191 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00008192
Eli Friedman9a14db32012-10-18 20:14:08 +00008193 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008194 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00008195 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008196 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008197 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00008198 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00008199 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008200 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00008201 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008202
8203 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008204 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008205
Eli Friedman86164e82013-09-05 00:02:25 +00008206 Constructor->markUsed(Context);
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008207 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008208
8209 if (ASTMutationListener *L = getASTMutationListener()) {
8210 L->CompletedImplicitDefinition(Constructor);
8211 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008212}
8213
Richard Smith7a614d82011-06-11 17:19:42 +00008214void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Toker08235662013-10-18 05:54:19 +00008215 // Perform any delayed checks on exception specifications.
8216 CheckDelayedMemberExceptionSpecs();
Richard Trieuef8f90c2013-09-20 03:03:06 +00008217
8218 // Once all the member initializers are processed, perform checks to see if
8219 // any unintialized use is happeneing.
8220 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
8221 D->getLocation())
8222 == DiagnosticsEngine::Ignored)
8223 return;
8224
8225 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D);
8226 if (!RD) return;
8227
8228 // Holds fields that are uninitialized.
8229 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
8230
8231 // In the beginning, every field is uninitialized.
8232 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
8233 I != E; ++I) {
8234 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
8235 UninitializedFields.insert(FD);
8236 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
8237 UninitializedFields.insert(IFD->getAnonField());
8238 }
8239 }
8240
8241 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
8242 I != E; ++I) {
8243 FieldDecl *FD = dyn_cast<FieldDecl>(*I);
8244 if (!FD)
8245 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I))
8246 FD = IFD->getAnonField();
8247
8248 if (!FD)
8249 continue;
8250
8251 Expr *InitExpr = FD->getInClassInitializer();
8252 if (!InitExpr) {
8253 // Uninitialized reference types will give an error.
8254 // Record types with an initializer are default initialized.
8255 QualType FieldType = FD->getType();
8256 if (FieldType->isReferenceType() || FieldType->isRecordType())
8257 UninitializedFields.erase(FD);
8258 continue;
8259 }
8260
8261 CheckInitExprContainsUninitializedFields(
8262 *this, InitExpr, FD, UninitializedFields,
8263 UninitializedFields.count(FD)/*WarnOnSelfReference*/);
8264
8265 UninitializedFields.erase(FD);
8266 }
Richard Smith7a614d82011-06-11 17:19:42 +00008267}
8268
Richard Smith4841ca52013-04-10 05:48:59 +00008269namespace {
8270/// Information on inheriting constructors to declare.
8271class InheritingConstructorInfo {
8272public:
8273 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8274 : SemaRef(SemaRef), Derived(Derived) {
8275 // Mark the constructors that we already have in the derived class.
8276 //
8277 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8278 // unless there is a user-declared constructor with the same signature in
8279 // the class where the using-declaration appears.
8280 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8281 }
8282
8283 void inheritAll(CXXRecordDecl *RD) {
8284 visitAll(RD, &InheritingConstructorInfo::inherit);
8285 }
8286
8287private:
8288 /// Information about an inheriting constructor.
8289 struct InheritingConstructor {
8290 InheritingConstructor()
8291 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8292
8293 /// If \c true, a constructor with this signature is already declared
8294 /// in the derived class.
8295 bool DeclaredInDerived;
8296
8297 /// The constructor which is inherited.
8298 const CXXConstructorDecl *BaseCtor;
8299
8300 /// The derived constructor we declared.
8301 CXXConstructorDecl *DerivedCtor;
8302 };
8303
8304 /// Inheriting constructors with a given canonical type. There can be at
8305 /// most one such non-template constructor, and any number of templated
8306 /// constructors.
8307 struct InheritingConstructorsForType {
8308 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008309 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8310 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008311
8312 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8313 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8314 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8315 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8316 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8317 false, S.TPL_TemplateMatch))
8318 return Templates[I].second;
8319 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8320 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008321 }
Richard Smith4841ca52013-04-10 05:48:59 +00008322
8323 return NonTemplate;
8324 }
8325 };
8326
8327 /// Get or create the inheriting constructor record for a constructor.
8328 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8329 QualType CtorType) {
8330 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8331 .getEntry(SemaRef, Ctor);
8332 }
8333
8334 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8335
8336 /// Process all constructors for a class.
8337 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8338 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8339 CtorE = RD->ctor_end();
8340 CtorIt != CtorE; ++CtorIt)
8341 (this->*Callback)(*CtorIt);
8342 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8343 I(RD->decls_begin()), E(RD->decls_end());
8344 I != E; ++I) {
8345 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8346 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8347 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008348 }
8349 }
Richard Smith4841ca52013-04-10 05:48:59 +00008350
8351 /// Note that a constructor (or constructor template) was declared in Derived.
8352 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8353 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8354 }
8355
8356 /// Inherit a single constructor.
8357 void inherit(const CXXConstructorDecl *Ctor) {
8358 const FunctionProtoType *CtorType =
8359 Ctor->getType()->castAs<FunctionProtoType>();
8360 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8361 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8362
8363 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8364
8365 // Core issue (no number yet): the ellipsis is always discarded.
8366 if (EPI.Variadic) {
8367 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8368 SemaRef.Diag(Ctor->getLocation(),
8369 diag::note_using_decl_constructor_ellipsis);
8370 EPI.Variadic = false;
8371 }
8372
8373 // Declare a constructor for each number of parameters.
8374 //
8375 // C++11 [class.inhctor]p1:
8376 // The candidate set of inherited constructors from the class X named in
8377 // the using-declaration consists of [... modulo defects ...] for each
8378 // constructor or constructor template of X, the set of constructors or
8379 // constructor templates that results from omitting any ellipsis parameter
8380 // specification and successively omitting parameters with a default
8381 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008382 unsigned MinParams = minParamsToInherit(Ctor);
8383 unsigned Params = Ctor->getNumParams();
8384 if (Params >= MinParams) {
8385 do
8386 declareCtor(UsingLoc, Ctor,
8387 SemaRef.Context.getFunctionType(
8388 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8389 while (Params > MinParams &&
8390 Ctor->getParamDecl(--Params)->hasDefaultArg());
8391 }
Richard Smith4841ca52013-04-10 05:48:59 +00008392 }
8393
8394 /// Find the using-declaration which specified that we should inherit the
8395 /// constructors of \p Base.
8396 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8397 // No fancy lookup required; just look for the base constructor name
8398 // directly within the derived class.
8399 ASTContext &Context = SemaRef.Context;
8400 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8401 Context.getCanonicalType(Context.getRecordType(Base)));
8402 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8403 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8404 }
8405
8406 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8407 // C++11 [class.inhctor]p3:
8408 // [F]or each constructor template in the candidate set of inherited
8409 // constructors, a constructor template is implicitly declared
8410 if (Ctor->getDescribedFunctionTemplate())
8411 return 0;
8412
8413 // For each non-template constructor in the candidate set of inherited
8414 // constructors other than a constructor having no parameters or a
8415 // copy/move constructor having a single parameter, a constructor is
8416 // implicitly declared [...]
8417 if (Ctor->getNumParams() == 0)
8418 return 1;
8419 if (Ctor->isCopyOrMoveConstructor())
8420 return 2;
8421
8422 // Per discussion on core reflector, never inherit a constructor which
8423 // would become a default, copy, or move constructor of Derived either.
8424 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8425 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8426 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8427 }
8428
8429 /// Declare a single inheriting constructor, inheriting the specified
8430 /// constructor, with the given type.
8431 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8432 QualType DerivedType) {
8433 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8434
8435 // C++11 [class.inhctor]p3:
8436 // ... a constructor is implicitly declared with the same constructor
8437 // characteristics unless there is a user-declared constructor with
8438 // the same signature in the class where the using-declaration appears
8439 if (Entry.DeclaredInDerived)
8440 return;
8441
8442 // C++11 [class.inhctor]p7:
8443 // If two using-declarations declare inheriting constructors with the
8444 // same signature, the program is ill-formed
8445 if (Entry.DerivedCtor) {
8446 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8447 // Only diagnose this once per constructor.
8448 if (Entry.DerivedCtor->isInvalidDecl())
8449 return;
8450 Entry.DerivedCtor->setInvalidDecl();
8451
8452 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8453 SemaRef.Diag(BaseCtor->getLocation(),
8454 diag::note_using_decl_constructor_conflict_current_ctor);
8455 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8456 diag::note_using_decl_constructor_conflict_previous_ctor);
8457 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8458 diag::note_using_decl_constructor_conflict_previous_using);
8459 } else {
8460 // Core issue (no number): if the same inheriting constructor is
8461 // produced by multiple base class constructors from the same base
8462 // class, the inheriting constructor is defined as deleted.
8463 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8464 }
8465
8466 return;
8467 }
8468
8469 ASTContext &Context = SemaRef.Context;
8470 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8471 Context.getCanonicalType(Context.getRecordType(Derived)));
8472 DeclarationNameInfo NameInfo(Name, UsingLoc);
8473
8474 TemplateParameterList *TemplateParams = 0;
8475 if (const FunctionTemplateDecl *FTD =
8476 BaseCtor->getDescribedFunctionTemplate()) {
8477 TemplateParams = FTD->getTemplateParameters();
8478 // We're reusing template parameters from a different DeclContext. This
8479 // is questionable at best, but works out because the template depth in
8480 // both places is guaranteed to be 0.
8481 // FIXME: Rebuild the template parameters in the new context, and
8482 // transform the function type to refer to them.
8483 }
8484
8485 // Build type source info pointing at the using-declaration. This is
8486 // required by template instantiation.
8487 TypeSourceInfo *TInfo =
8488 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8489 FunctionProtoTypeLoc ProtoLoc =
8490 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8491
8492 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8493 Context, Derived, UsingLoc, NameInfo, DerivedType,
8494 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8495 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8496
8497 // Build an unevaluated exception specification for this constructor.
8498 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8499 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8500 EPI.ExceptionSpecType = EST_Unevaluated;
8501 EPI.ExceptionSpecDecl = DerivedCtor;
8502 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8503 FPT->getArgTypes(), EPI));
8504
8505 // Build the parameter declarations.
8506 SmallVector<ParmVarDecl *, 16> ParamDecls;
8507 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8508 TypeSourceInfo *TInfo =
8509 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8510 ParmVarDecl *PD = ParmVarDecl::Create(
8511 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8512 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8513 PD->setScopeInfo(0, I);
8514 PD->setImplicit();
8515 ParamDecls.push_back(PD);
8516 ProtoLoc.setArg(I, PD);
8517 }
8518
8519 // Set up the new constructor.
8520 DerivedCtor->setAccess(BaseCtor->getAccess());
8521 DerivedCtor->setParams(ParamDecls);
8522 DerivedCtor->setInheritedConstructor(BaseCtor);
8523 if (BaseCtor->isDeleted())
8524 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8525
8526 // If this is a constructor template, build the template declaration.
8527 if (TemplateParams) {
8528 FunctionTemplateDecl *DerivedTemplate =
8529 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8530 TemplateParams, DerivedCtor);
8531 DerivedTemplate->setAccess(BaseCtor->getAccess());
8532 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8533 Derived->addDecl(DerivedTemplate);
8534 } else {
8535 Derived->addDecl(DerivedCtor);
8536 }
8537
8538 Entry.BaseCtor = BaseCtor;
8539 Entry.DerivedCtor = DerivedCtor;
8540 }
8541
8542 Sema &SemaRef;
8543 CXXRecordDecl *Derived;
8544 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8545 MapType Map;
8546};
8547}
8548
8549void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8550 // Defer declaring the inheriting constructors until the class is
8551 // instantiated.
8552 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008553 return;
8554
Richard Smith4841ca52013-04-10 05:48:59 +00008555 // Find base classes from which we might inherit constructors.
8556 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8557 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8558 BaseE = ClassDecl->bases_end();
8559 BaseIt != BaseE; ++BaseIt)
8560 if (BaseIt->getInheritConstructors())
8561 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008562
Richard Smith4841ca52013-04-10 05:48:59 +00008563 // Go no further if we're not inheriting any constructors.
8564 if (InheritedBases.empty())
8565 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008566
Richard Smith4841ca52013-04-10 05:48:59 +00008567 // Declare the inherited constructors.
8568 InheritingConstructorInfo ICI(*this, ClassDecl);
8569 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8570 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008571}
8572
Richard Smith07b0fdc2013-03-18 21:12:30 +00008573void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8574 CXXConstructorDecl *Constructor) {
8575 CXXRecordDecl *ClassDecl = Constructor->getParent();
8576 assert(Constructor->getInheritedConstructor() &&
8577 !Constructor->doesThisDeclarationHaveABody() &&
8578 !Constructor->isDeleted());
8579
8580 SynthesizedFunctionScope Scope(*this, Constructor);
8581 DiagnosticErrorTrap Trap(Diags);
8582 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8583 Trap.hasErrorOccurred()) {
8584 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8585 << Context.getTagDeclType(ClassDecl);
8586 Constructor->setInvalidDecl();
8587 return;
8588 }
8589
8590 SourceLocation Loc = Constructor->getLocation();
8591 Constructor->setBody(new (Context) CompoundStmt(Loc));
8592
Eli Friedman86164e82013-09-05 00:02:25 +00008593 Constructor->markUsed(Context);
Richard Smith07b0fdc2013-03-18 21:12:30 +00008594 MarkVTableUsed(CurrentLocation, ClassDecl);
8595
8596 if (ASTMutationListener *L = getASTMutationListener()) {
8597 L->CompletedImplicitDefinition(Constructor);
8598 }
8599}
8600
8601
Sean Huntcb45a0f2011-05-12 22:46:25 +00008602Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008603Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8604 CXXRecordDecl *ClassDecl = MD->getParent();
8605
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008606 // C++ [except.spec]p14:
8607 // An implicitly declared special member function (Clause 12) shall have
8608 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008609 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008610 if (ClassDecl->isInvalidDecl())
8611 return ExceptSpec;
8612
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008613 // Direct base-class destructors.
8614 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8615 BEnd = ClassDecl->bases_end();
8616 B != BEnd; ++B) {
8617 if (B->isVirtual()) // Handled below.
8618 continue;
8619
8620 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008621 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008622 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008623 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008624
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008625 // Virtual base-class destructors.
8626 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8627 BEnd = ClassDecl->vbases_end();
8628 B != BEnd; ++B) {
8629 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008630 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008631 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008632 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008633
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008634 // Field destructors.
8635 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8636 FEnd = ClassDecl->field_end();
8637 F != FEnd; ++F) {
8638 if (const RecordType *RecordTy
8639 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008640 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008641 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008642 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008643
Sean Huntcb45a0f2011-05-12 22:46:25 +00008644 return ExceptSpec;
8645}
8646
8647CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8648 // C++ [class.dtor]p2:
8649 // If a class has no user-declared destructor, a destructor is
8650 // declared implicitly. An implicitly-declared destructor is an
8651 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008652 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008653
Richard Smithafb49182012-11-29 01:34:07 +00008654 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8655 if (DSM.isAlreadyBeingDeclared())
8656 return 0;
8657
Douglas Gregor4923aa22010-07-02 20:37:36 +00008658 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008659 CanQualType ClassType
8660 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008661 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008662 DeclarationName Name
8663 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008664 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008665 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008666 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8667 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008668 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008669 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008670 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008671 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008672
8673 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008674 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008675 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008676
Richard Smithbc2a35d2012-12-08 08:32:28 +00008677 AddOverriddenMethods(ClassDecl, Destructor);
8678
8679 // We don't need to use SpecialMemberIsTrivial here; triviality for
8680 // destructors is easy to compute.
8681 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8682
8683 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008684 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008685
Douglas Gregor4923aa22010-07-02 20:37:36 +00008686 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008687 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008688
Douglas Gregor4923aa22010-07-02 20:37:36 +00008689 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008690 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008691 PushOnScopeChains(Destructor, S, false);
8692 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008693
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008694 return Destructor;
8695}
8696
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008697void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008698 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008699 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008700 !Destructor->doesThisDeclarationHaveABody() &&
8701 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008702 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008703 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008704 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008705
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008706 if (Destructor->isInvalidDecl())
8707 return;
8708
Eli Friedman9a14db32012-10-18 20:14:08 +00008709 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008710
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008711 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008712 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8713 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008714
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008715 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008716 Diag(CurrentLocation, diag::note_member_synthesized_at)
8717 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8718
8719 Destructor->setInvalidDecl();
8720 return;
8721 }
8722
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008723 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008724 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman86164e82013-09-05 00:02:25 +00008725 Destructor->markUsed(Context);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008726 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008727
8728 if (ASTMutationListener *L = getASTMutationListener()) {
8729 L->CompletedImplicitDefinition(Destructor);
8730 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008731}
8732
Richard Smitha4156b82012-04-21 18:42:51 +00008733/// \brief Perform any semantic analysis which needs to be delayed until all
8734/// pending class member declarations have been parsed.
8735void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008736 // If the context is an invalid C++ class, just suppress these checks.
8737 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8738 if (Record->isInvalidDecl()) {
Alp Toker08235662013-10-18 05:54:19 +00008739 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregor10318842013-02-01 04:49:10 +00008740 DelayedDestructorExceptionSpecChecks.clear();
8741 return;
8742 }
8743 }
Richard Smitha4156b82012-04-21 18:42:51 +00008744}
8745
Richard Smithb9d0b762012-07-27 04:22:15 +00008746void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8747 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008748 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008749 "adjusting dtor exception specs was introduced in c++11");
8750
Sebastian Redl0ee33912011-05-19 05:13:44 +00008751 // C++11 [class.dtor]p3:
8752 // A declaration of a destructor that does not have an exception-
8753 // specification is implicitly considered to have the same exception-
8754 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008755 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008756 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008757 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008758 return;
8759
Chandler Carruth3f224b22011-09-20 04:55:26 +00008760 // Replace the destructor's type, building off the existing one. Fortunately,
8761 // the only thing of interest in the destructor type is its extended info.
8762 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008763 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8764 EPI.ExceptionSpecType = EST_Unevaluated;
8765 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008766 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008767
Sebastian Redl0ee33912011-05-19 05:13:44 +00008768 // FIXME: If the destructor has a body that could throw, and the newly created
8769 // spec doesn't allow exceptions, we should emit a warning, because this
8770 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008771 // However, we don't have a body or an exception specification yet, so it
8772 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008773}
8774
Pavel Labath66ea35d2013-08-30 08:52:28 +00008775namespace {
8776/// \brief An abstract base class for all helper classes used in building the
8777// copy/move operators. These classes serve as factory functions and help us
8778// avoid using the same Expr* in the AST twice.
8779class ExprBuilder {
8780 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8781 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8782
8783protected:
8784 static Expr *assertNotNull(Expr *E) {
8785 assert(E && "Expression construction must not fail.");
8786 return E;
8787 }
8788
8789public:
8790 ExprBuilder() {}
8791 virtual ~ExprBuilder() {}
8792
8793 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8794};
8795
8796class RefBuilder: public ExprBuilder {
8797 VarDecl *Var;
8798 QualType VarType;
8799
8800public:
8801 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8802 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8803 }
8804
8805 RefBuilder(VarDecl *Var, QualType VarType)
8806 : Var(Var), VarType(VarType) {}
8807};
8808
8809class ThisBuilder: public ExprBuilder {
8810public:
8811 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8812 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8813 }
8814};
8815
8816class CastBuilder: public ExprBuilder {
8817 const ExprBuilder &Builder;
8818 QualType Type;
8819 ExprValueKind Kind;
8820 const CXXCastPath &Path;
8821
8822public:
8823 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8824 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8825 CK_UncheckedDerivedToBase, Kind,
8826 &Path).take());
8827 }
8828
8829 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8830 const CXXCastPath &Path)
8831 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8832};
8833
8834class DerefBuilder: public ExprBuilder {
8835 const ExprBuilder &Builder;
8836
8837public:
8838 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8839 return assertNotNull(
8840 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8841 }
8842
8843 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8844};
8845
8846class MemberBuilder: public ExprBuilder {
8847 const ExprBuilder &Builder;
8848 QualType Type;
8849 CXXScopeSpec SS;
8850 bool IsArrow;
8851 LookupResult &MemberLookup;
8852
8853public:
8854 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8855 return assertNotNull(S.BuildMemberReferenceExpr(
8856 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8857 MemberLookup, 0).take());
8858 }
8859
8860 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8861 LookupResult &MemberLookup)
8862 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8863 MemberLookup(MemberLookup) {}
8864};
8865
8866class MoveCastBuilder: public ExprBuilder {
8867 const ExprBuilder &Builder;
8868
8869public:
8870 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8871 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8872 }
8873
8874 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8875};
8876
8877class LvalueConvBuilder: public ExprBuilder {
8878 const ExprBuilder &Builder;
8879
8880public:
8881 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8882 return assertNotNull(
8883 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8884 }
8885
8886 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8887};
8888
8889class SubscriptBuilder: public ExprBuilder {
8890 const ExprBuilder &Base;
8891 const ExprBuilder &Index;
8892
8893public:
8894 virtual Expr *build(Sema &S, SourceLocation Loc) const
8895 LLVM_OVERRIDE {
8896 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8897 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8898 }
8899
8900 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8901 : Base(Base), Index(Index) {}
8902};
8903
8904} // end anonymous namespace
8905
Richard Smith8c889532012-11-14 00:50:40 +00008906/// When generating a defaulted copy or move assignment operator, if a field
8907/// should be copied with __builtin_memcpy rather than via explicit assignments,
8908/// do so. This optimization only applies for arrays of scalars, and for arrays
8909/// of class type where the selected copy/move-assignment operator is trivial.
8910static StmtResult
8911buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008912 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00008913 // Compute the size of the memory buffer to be copied.
8914 QualType SizeType = S.Context.getSizeType();
8915 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8916 S.Context.getTypeSizeInChars(T).getQuantity());
8917
8918 // Take the address of the field references for "from" and "to". We
8919 // directly construct UnaryOperators here because semantic analysis
8920 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008921 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008922 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8923 S.Context.getPointerType(From->getType()),
8924 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00008925 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008926 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8927 S.Context.getPointerType(To->getType()),
8928 VK_RValue, OK_Ordinary, Loc);
8929
8930 const Type *E = T->getBaseElementTypeUnsafe();
8931 bool NeedsCollectableMemCpy =
8932 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8933
8934 // Create a reference to the __builtin_objc_memmove_collectable function
8935 StringRef MemCpyName = NeedsCollectableMemCpy ?
8936 "__builtin_objc_memmove_collectable" :
8937 "__builtin_memcpy";
8938 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8939 Sema::LookupOrdinaryName);
8940 S.LookupName(R, S.TUScope, true);
8941
8942 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8943 if (!MemCpy)
8944 // Something went horribly wrong earlier, and we will have complained
8945 // about it.
8946 return StmtError();
8947
8948 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8949 VK_RValue, Loc, 0);
8950 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8951
8952 Expr *CallArgs[] = {
8953 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8954 };
8955 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8956 Loc, CallArgs, Loc);
8957
8958 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8959 return S.Owned(Call.takeAs<Stmt>());
8960}
8961
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008962/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008963/// \c To.
8964///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008965/// This routine is used to copy/move the members of a class with an
8966/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008967/// copied are arrays, this routine builds for loops to copy them.
8968///
8969/// \param S The Sema object used for type-checking.
8970///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008971/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008972///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008973/// \param T The type of the expressions being copied/moved. Both expressions
8974/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008975///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008976/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008977///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008978/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008979///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008980/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008981/// Otherwise, it's a non-static member subobject.
8982///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008983/// \param Copying Whether we're copying or moving.
8984///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008985/// \param Depth Internal parameter recording the depth of the recursion.
8986///
Richard Smith8c889532012-11-14 00:50:40 +00008987/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8988/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008989static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008990buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008991 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008992 bool CopyingBaseSubobject, bool Copying,
8993 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008994 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008995 // Each subobject is assigned in the manner appropriate to its type:
8996 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008997 // - if the subobject is of class type, as if by a call to operator= with
8998 // the subobject as the object expression and the corresponding
8999 // subobject of x as a single function argument (as if by explicit
9000 // qualification; that is, ignoring any possible virtual overriding
9001 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00009002 //
9003 // C++03 [class.copy]p13:
9004 // - if the subobject is of class type, the copy assignment operator for
9005 // the class is used (as if by explicit qualification; that is,
9006 // ignoring any possible virtual overriding functions in more derived
9007 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009008 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9009 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00009010
Douglas Gregor06a9f362010-05-01 20:49:11 +00009011 // Look for operator=.
9012 DeclarationName Name
9013 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9014 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9015 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009016
Richard Smith044c8aa2012-11-13 00:54:12 +00009017 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9018 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00009019 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00009020 LookupResult::Filter F = OpLookup.makeFilter();
9021 while (F.hasNext()) {
9022 NamedDecl *D = F.next();
9023 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9024 if (Method->isCopyAssignmentOperator() ||
9025 (!Copying && Method->isMoveAssignmentOperator()))
9026 continue;
9027
9028 F.erase();
9029 }
9030 F.done();
John McCallb0207482010-03-16 06:11:48 +00009031 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009032
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009033 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00009034 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009035 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00009036 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009037 // ambiguities), we need to cast "this" to that subobject type; to
9038 // ensure that we don't go through the virtual call mechanism, we need
9039 // to qualify the operator= name with the base class (see below). However,
9040 // this means that if the base class has a protected copy assignment
9041 // operator, the protected member access check will fail. So, we
9042 // rewrite "protected" access to "public" access in this case, since we
9043 // know by construction that we're calling from a derived class.
9044 if (CopyingBaseSubobject) {
9045 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9046 L != LEnd; ++L) {
9047 if (L.getAccess() == AS_protected)
9048 L.setAccess(AS_public);
9049 }
9050 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009051
Douglas Gregor06a9f362010-05-01 20:49:11 +00009052 // Create the nested-name-specifier that will be used to qualify the
9053 // reference to operator=; this is required to suppress the virtual
9054 // call mechanism.
9055 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009056 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00009057 SS.MakeTrivial(S.Context,
9058 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009059 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00009060 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00009061
Douglas Gregor06a9f362010-05-01 20:49:11 +00009062 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00009063 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00009064 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9065 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009066 /*FirstQualifierInScope=*/0,
9067 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009068 /*TemplateArgs=*/0,
9069 /*SuppressQualifierCheck=*/true);
9070 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009071 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009072
Douglas Gregor06a9f362010-05-01 20:49:11 +00009073 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00009074
Pavel Labath66ea35d2013-08-30 08:52:28 +00009075 Expr *FromInst = From.build(S, Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00009076 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00009077 OpEqualRef.takeAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009078 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009079 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009080 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009081
Richard Smith8c889532012-11-14 00:50:40 +00009082 // If we built a call to a trivial 'operator=' while copying an array,
9083 // bail out. We'll replace the whole shebang with a memcpy.
9084 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9085 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9086 return StmtResult((Stmt*)0);
9087
Richard Smith044c8aa2012-11-13 00:54:12 +00009088 // Convert to an expression-statement, and clean up any produced
9089 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00009090 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009091 }
John McCallb0207482010-03-16 06:11:48 +00009092
Richard Smith044c8aa2012-11-13 00:54:12 +00009093 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00009094 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00009095 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009096 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009097 ExprResult Assignment = S.CreateBuiltinBinOp(
9098 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009099 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009100 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00009101 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009102 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009103
9104 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00009105 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00009106
Douglas Gregor06a9f362010-05-01 20:49:11 +00009107 // Construct a loop over the array bounds, e.g.,
9108 //
9109 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9110 //
9111 // that will copy each of the array elements.
9112 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00009113
Douglas Gregor06a9f362010-05-01 20:49:11 +00009114 // Create the iteration variable.
9115 IdentifierInfo *IterationVarName = 0;
9116 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009117 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009118 llvm::raw_svector_ostream OS(Str);
9119 OS << "__i" << Depth;
9120 IterationVarName = &S.Context.Idents.get(OS.str());
9121 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009122 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009123 IterationVarName, SizeType,
9124 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009125 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00009126
Douglas Gregor06a9f362010-05-01 20:49:11 +00009127 // Initialize the iteration variable to zero.
9128 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009129 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009130
Pavel Labath66ea35d2013-08-30 08:52:28 +00009131 // Creates a reference to the iteration variable.
9132 RefBuilder IterationVarRef(IterationVar, SizeType);
9133 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00009134
Douglas Gregor06a9f362010-05-01 20:49:11 +00009135 // Create the DeclStmt that holds the iteration variable.
9136 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009137
Douglas Gregor06a9f362010-05-01 20:49:11 +00009138 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009139 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9140 MoveCastBuilder FromIndexMove(FromIndexCopy);
9141 const ExprBuilder *FromIndex;
9142 if (Copying)
9143 FromIndex = &FromIndexCopy;
9144 else
9145 FromIndex = &FromIndexMove;
9146
9147 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009148
9149 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00009150 StmtResult Copy =
9151 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009152 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00009153 Copying, Depth + 1);
9154 // Bail out if copying fails or if we determined that we should use memcpy.
9155 if (Copy.isInvalid() || !Copy.get())
9156 return Copy;
9157
9158 // Create the comparison against the array bound.
9159 llvm::APInt Upper
9160 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9161 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00009162 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00009163 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9164 BO_NE, S.Context.BoolTy,
9165 VK_RValue, OK_Ordinary, Loc, false);
9166
9167 // Create the pre-increment of the iteration variable.
9168 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00009169 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9170 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009171
Douglas Gregor06a9f362010-05-01 20:49:11 +00009172 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00009173 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009174 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00009175 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00009176 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009177}
9178
Richard Smith8c889532012-11-14 00:50:40 +00009179static StmtResult
9180buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009181 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00009182 bool CopyingBaseSubobject, bool Copying) {
9183 // Maybe we should use a memcpy?
9184 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9185 T.isTriviallyCopyableType(S.Context))
9186 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9187
9188 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9189 CopyingBaseSubobject,
9190 Copying, 0));
9191
9192 // If we ended up picking a trivial assignment operator for an array of a
9193 // non-trivially-copyable class type, just emit a memcpy.
9194 if (!Result.isInvalid() && !Result.get())
9195 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9196
9197 return Result;
9198}
9199
Richard Smithb9d0b762012-07-27 04:22:15 +00009200Sema::ImplicitExceptionSpecification
9201Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9202 CXXRecordDecl *ClassDecl = MD->getParent();
9203
9204 ImplicitExceptionSpecification ExceptSpec(*this);
9205 if (ClassDecl->isInvalidDecl())
9206 return ExceptSpec;
9207
9208 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9209 assert(T->getNumArgs() == 1 && "not a copy assignment op");
9210 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9211
Douglas Gregorb87786f2010-07-01 17:48:08 +00009212 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00009213 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00009214 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00009215
9216 // It is unspecified whether or not an implicit copy assignment operator
9217 // attempts to deduplicate calls to assignment operators of virtual bases are
9218 // made. As such, this exception specification is effectively unspecified.
9219 // Based on a similar decision made for constness in C++0x, we're erring on
9220 // the side of assuming such calls to be made regardless of whether they
9221 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00009222 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9223 BaseEnd = ClassDecl->bases_end();
9224 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00009225 if (Base->isVirtual())
9226 continue;
9227
Douglas Gregora376d102010-07-02 21:50:04 +00009228 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00009229 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009230 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9231 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009232 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00009233 }
Sean Hunt661c67a2011-06-21 23:42:56 +00009234
9235 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9236 BaseEnd = ClassDecl->vbases_end();
9237 Base != BaseEnd; ++Base) {
9238 CXXRecordDecl *BaseClassDecl
9239 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9240 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9241 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009242 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00009243 }
9244
Douglas Gregorb87786f2010-07-01 17:48:08 +00009245 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9246 FieldEnd = ClassDecl->field_end();
9247 Field != FieldEnd;
9248 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009249 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00009250 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9251 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009252 LookupCopyingAssignment(FieldClassDecl,
9253 ArgQuals | FieldType.getCVRQualifiers(),
9254 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009255 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009256 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00009257 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009258
Richard Smithb9d0b762012-07-27 04:22:15 +00009259 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00009260}
9261
9262CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9263 // Note: The following rules are largely analoguous to the copy
9264 // constructor rules. Note that virtual bases are not taken into account
9265 // for determining the argument type of the operator. Note also that
9266 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00009267 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00009268
Richard Smithafb49182012-11-29 01:34:07 +00009269 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9270 if (DSM.isAlreadyBeingDeclared())
9271 return 0;
9272
Sean Hunt30de05c2011-05-14 05:23:20 +00009273 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9274 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00009275 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9276 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00009277 ArgType = ArgType.withConst();
9278 ArgType = Context.getLValueReferenceType(ArgType);
9279
Richard Smitha8942d72013-05-07 03:19:20 +00009280 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9281 CXXCopyAssignment,
9282 Const);
9283
Douglas Gregord3c35902010-07-01 16:36:15 +00009284 // An implicitly-declared copy assignment operator is an inline public
9285 // member of its class.
9286 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009287 SourceLocation ClassLoc = ClassDecl->getLocation();
9288 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009289 CXXMethodDecl *CopyAssignment =
9290 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9291 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9292 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00009293 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00009294 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00009295 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00009296
9297 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009298 FunctionProtoType::ExtProtoInfo EPI =
9299 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009300 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009301
Douglas Gregord3c35902010-07-01 16:36:15 +00009302 // Add the parameter to the operator.
9303 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009304 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00009305 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009306 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009307 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00009308
Richard Smithbc2a35d2012-12-08 08:32:28 +00009309 AddOverriddenMethods(ClassDecl, CopyAssignment);
9310
9311 CopyAssignment->setTrivial(
9312 ClassDecl->needsOverloadResolutionForCopyAssignment()
9313 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9314 : ClassDecl->hasTrivialCopyAssignment());
9315
Richard Smitha8942d72013-05-07 03:19:20 +00009316 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00009317 // .... If the class definition does not explicitly declare a copy
9318 // assignment operator, there is no user-declared move constructor, and
9319 // there is no user-declared move assignment operator, a copy assignment
9320 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009321 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009322 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009323
Richard Smithbc2a35d2012-12-08 08:32:28 +00009324 // Note that we have added this copy-assignment operator.
9325 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9326
9327 if (Scope *S = getScopeForContext(ClassDecl))
9328 PushOnScopeChains(CopyAssignment, S, false);
9329 ClassDecl->addDecl(CopyAssignment);
9330
Douglas Gregord3c35902010-07-01 16:36:15 +00009331 return CopyAssignment;
9332}
9333
Richard Smith36155c12013-06-13 03:23:42 +00009334/// Diagnose an implicit copy operation for a class which is odr-used, but
9335/// which is deprecated because the class has a user-declared copy constructor,
9336/// copy assignment operator, or destructor.
9337static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9338 SourceLocation UseLoc) {
9339 assert(CopyOp->isImplicit());
9340
9341 CXXRecordDecl *RD = CopyOp->getParent();
9342 CXXMethodDecl *UserDeclaredOperation = 0;
9343
9344 // In Microsoft mode, assignment operations don't affect constructors and
9345 // vice versa.
9346 if (RD->hasUserDeclaredDestructor()) {
9347 UserDeclaredOperation = RD->getDestructor();
9348 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9349 RD->hasUserDeclaredCopyConstructor() &&
9350 !S.getLangOpts().MicrosoftMode) {
9351 // Find any user-declared copy constructor.
9352 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9353 E = RD->ctor_end(); I != E; ++I) {
9354 if (I->isCopyConstructor()) {
9355 UserDeclaredOperation = *I;
9356 break;
9357 }
9358 }
9359 assert(UserDeclaredOperation);
9360 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9361 RD->hasUserDeclaredCopyAssignment() &&
9362 !S.getLangOpts().MicrosoftMode) {
9363 // Find any user-declared move assignment operator.
9364 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9365 E = RD->method_end(); I != E; ++I) {
9366 if (I->isCopyAssignmentOperator()) {
9367 UserDeclaredOperation = *I;
9368 break;
9369 }
9370 }
9371 assert(UserDeclaredOperation);
9372 }
9373
9374 if (UserDeclaredOperation) {
9375 S.Diag(UserDeclaredOperation->getLocation(),
9376 diag::warn_deprecated_copy_operation)
9377 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9378 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9379 S.Diag(UseLoc, diag::note_member_synthesized_at)
9380 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9381 : Sema::CXXCopyAssignment)
9382 << RD;
9383 }
9384}
9385
Douglas Gregor06a9f362010-05-01 20:49:11 +00009386void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9387 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00009388 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009389 CopyAssignOperator->isOverloadedOperator() &&
9390 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009391 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9392 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009393 "DefineImplicitCopyAssignment called for wrong function");
9394
9395 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9396
9397 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9398 CopyAssignOperator->setInvalidDecl();
9399 return;
9400 }
Richard Smith36155c12013-06-13 03:23:42 +00009401
9402 // C++11 [class.copy]p18:
9403 // The [definition of an implicitly declared copy assignment operator] is
9404 // deprecated if the class has a user-declared copy constructor or a
9405 // user-declared destructor.
9406 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9407 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9408
Eli Friedman86164e82013-09-05 00:02:25 +00009409 CopyAssignOperator->markUsed(Context);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009410
Eli Friedman9a14db32012-10-18 20:14:08 +00009411 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009412 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009413
9414 // C++0x [class.copy]p30:
9415 // The implicitly-defined or explicitly-defaulted copy assignment operator
9416 // for a non-union class X performs memberwise copy assignment of its
9417 // subobjects. The direct base classes of X are assigned first, in the
9418 // order of their declaration in the base-specifier-list, and then the
9419 // immediate non-static data members of X are assigned, in the order in
9420 // which they were declared in the class definition.
9421
9422 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009423 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009424
9425 // The parameter for the "other" object, which we are copying from.
9426 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9427 Qualifiers OtherQuals = Other->getType().getQualifiers();
9428 QualType OtherRefType = Other->getType();
9429 if (const LValueReferenceType *OtherRef
9430 = OtherRefType->getAs<LValueReferenceType>()) {
9431 OtherRefType = OtherRef->getPointeeType();
9432 OtherQuals = OtherRefType.getQualifiers();
9433 }
9434
9435 // Our location for everything implicitly-generated.
9436 SourceLocation Loc = CopyAssignOperator->getLocation();
9437
Pavel Labath66ea35d2013-08-30 08:52:28 +00009438 // Builds a DeclRefExpr for the "other" object.
9439 RefBuilder OtherRef(Other, OtherRefType);
9440
9441 // Builds the "this" pointer.
9442 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009443
9444 // Assign base classes.
9445 bool Invalid = false;
9446 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9447 E = ClassDecl->bases_end(); Base != E; ++Base) {
9448 // Form the assignment:
9449 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9450 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009451 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009452 Invalid = true;
9453 continue;
9454 }
9455
John McCallf871d0c2010-08-07 06:22:56 +00009456 CXXCastPath BasePath;
9457 BasePath.push_back(Base);
9458
Douglas Gregor06a9f362010-05-01 20:49:11 +00009459 // Construct the "from" expression, which is an implicit cast to the
9460 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009461 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9462 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009463
9464 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009465 DerefBuilder DerefThis(This);
9466 CastBuilder To(DerefThis,
9467 Context.getCVRQualifiedType(
9468 BaseType, CopyAssignOperator->getTypeQualifiers()),
9469 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009470
9471 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009472 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009473 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009474 /*CopyingBaseSubobject=*/true,
9475 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009476 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009477 Diag(CurrentLocation, diag::note_member_synthesized_at)
9478 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9479 CopyAssignOperator->setInvalidDecl();
9480 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009481 }
9482
9483 // Success! Record the copy.
9484 Statements.push_back(Copy.takeAs<Expr>());
9485 }
9486
Douglas Gregor06a9f362010-05-01 20:49:11 +00009487 // Assign non-static members.
9488 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9489 FieldEnd = ClassDecl->field_end();
9490 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009491 if (Field->isUnnamedBitfield())
9492 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009493
9494 if (Field->isInvalidDecl()) {
9495 Invalid = true;
9496 continue;
9497 }
9498
Douglas Gregor06a9f362010-05-01 20:49:11 +00009499 // Check for members of reference type; we can't copy those.
9500 if (Field->getType()->isReferenceType()) {
9501 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9502 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9503 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009504 Diag(CurrentLocation, diag::note_member_synthesized_at)
9505 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009506 Invalid = true;
9507 continue;
9508 }
9509
9510 // Check for members of const-qualified, non-class type.
9511 QualType BaseType = Context.getBaseElementType(Field->getType());
9512 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9513 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9514 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9515 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009516 Diag(CurrentLocation, diag::note_member_synthesized_at)
9517 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009518 Invalid = true;
9519 continue;
9520 }
John McCallb77115d2011-06-17 00:18:42 +00009521
9522 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009523 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9524 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009525
9526 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009527 if (FieldType->isIncompleteArrayType()) {
9528 assert(ClassDecl->hasFlexibleArrayMember() &&
9529 "Incomplete array type is not valid");
9530 continue;
9531 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009532
9533 // Build references to the field in the object we're copying from and to.
9534 CXXScopeSpec SS; // Intentionally empty
9535 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9536 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009537 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009538 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009539
9540 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9541
9542 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009543
Douglas Gregor06a9f362010-05-01 20:49:11 +00009544 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009545 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009546 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009547 /*CopyingBaseSubobject=*/false,
9548 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009549 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009550 Diag(CurrentLocation, diag::note_member_synthesized_at)
9551 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9552 CopyAssignOperator->setInvalidDecl();
9553 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009554 }
9555
9556 // Success! Record the copy.
9557 Statements.push_back(Copy.takeAs<Stmt>());
9558 }
9559
9560 if (!Invalid) {
9561 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009562 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009563
John McCall60d7b3a2010-08-24 06:29:42 +00009564 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009565 if (Return.isInvalid())
9566 Invalid = true;
9567 else {
9568 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009569
9570 if (Trap.hasErrorOccurred()) {
9571 Diag(CurrentLocation, diag::note_member_synthesized_at)
9572 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9573 Invalid = true;
9574 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009575 }
9576 }
9577
9578 if (Invalid) {
9579 CopyAssignOperator->setInvalidDecl();
9580 return;
9581 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009582
9583 StmtResult Body;
9584 {
9585 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009586 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009587 /*isStmtExpr=*/false);
9588 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9589 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009590 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009591
9592 if (ASTMutationListener *L = getASTMutationListener()) {
9593 L->CompletedImplicitDefinition(CopyAssignOperator);
9594 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009595}
9596
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009597Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009598Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9599 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009600
Richard Smithb9d0b762012-07-27 04:22:15 +00009601 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009602 if (ClassDecl->isInvalidDecl())
9603 return ExceptSpec;
9604
9605 // C++0x [except.spec]p14:
9606 // An implicitly declared special member function (Clause 12) shall have an
9607 // exception-specification. [...]
9608
9609 // It is unspecified whether or not an implicit move assignment operator
9610 // attempts to deduplicate calls to assignment operators of virtual bases are
9611 // made. As such, this exception specification is effectively unspecified.
9612 // Based on a similar decision made for constness in C++0x, we're erring on
9613 // the side of assuming such calls to be made regardless of whether they
9614 // actually happen.
9615 // Note that a move constructor is not implicitly declared when there are
9616 // virtual bases, but it can still be user-declared and explicitly defaulted.
9617 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9618 BaseEnd = ClassDecl->bases_end();
9619 Base != BaseEnd; ++Base) {
9620 if (Base->isVirtual())
9621 continue;
9622
9623 CXXRecordDecl *BaseClassDecl
9624 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9625 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009626 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009627 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009628 }
9629
9630 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9631 BaseEnd = ClassDecl->vbases_end();
9632 Base != BaseEnd; ++Base) {
9633 CXXRecordDecl *BaseClassDecl
9634 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9635 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009636 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009637 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009638 }
9639
9640 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9641 FieldEnd = ClassDecl->field_end();
9642 Field != FieldEnd;
9643 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009644 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009645 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009646 if (CXXMethodDecl *MoveAssign =
9647 LookupMovingAssignment(FieldClassDecl,
9648 FieldType.getCVRQualifiers(),
9649 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009650 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009651 }
9652 }
9653
9654 return ExceptSpec;
9655}
9656
Richard Smith1c931be2012-04-02 18:40:40 +00009657/// Determine whether the class type has any direct or indirect virtual base
9658/// classes which have a non-trivial move assignment operator.
9659static bool
9660hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9661 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9662 BaseEnd = ClassDecl->vbases_end();
9663 Base != BaseEnd; ++Base) {
9664 CXXRecordDecl *BaseClass =
9665 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9666
9667 // Try to declare the move assignment. If it would be deleted, then the
9668 // class does not have a non-trivial move assignment.
9669 if (BaseClass->needsImplicitMoveAssignment())
9670 S.DeclareImplicitMoveAssignment(BaseClass);
9671
Richard Smith426391c2012-11-16 00:53:38 +00009672 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009673 return true;
9674 }
9675
9676 return false;
9677}
9678
9679/// Determine whether the given type either has a move constructor or is
9680/// trivially copyable.
9681static bool
9682hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9683 Type = S.Context.getBaseElementType(Type);
9684
9685 // FIXME: Technically, non-trivially-copyable non-class types, such as
9686 // reference types, are supposed to return false here, but that appears
9687 // to be a standard defect.
9688 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009689 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009690 return true;
9691
9692 if (Type.isTriviallyCopyableType(S.Context))
9693 return true;
9694
9695 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009696 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9697 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009698 if (ClassDecl->needsImplicitMoveConstructor())
9699 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009700 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009701 }
9702
Richard Smithe5411b72012-12-01 02:35:44 +00009703 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9704 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009705 if (ClassDecl->needsImplicitMoveAssignment())
9706 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009707 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009708}
9709
9710/// Determine whether all non-static data members and direct or virtual bases
9711/// of class \p ClassDecl have either a move operation, or are trivially
9712/// copyable.
9713static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9714 bool IsConstructor) {
9715 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9716 BaseEnd = ClassDecl->bases_end();
9717 Base != BaseEnd; ++Base) {
9718 if (Base->isVirtual())
9719 continue;
9720
9721 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9722 return false;
9723 }
9724
9725 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9726 BaseEnd = ClassDecl->vbases_end();
9727 Base != BaseEnd; ++Base) {
9728 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9729 return false;
9730 }
9731
9732 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9733 FieldEnd = ClassDecl->field_end();
9734 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009735 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009736 return false;
9737 }
9738
9739 return true;
9740}
9741
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009742CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009743 // C++11 [class.copy]p20:
9744 // If the definition of a class X does not explicitly declare a move
9745 // assignment operator, one will be implicitly declared as defaulted
9746 // if and only if:
9747 //
9748 // - [first 4 bullets]
9749 assert(ClassDecl->needsImplicitMoveAssignment());
9750
Richard Smithafb49182012-11-29 01:34:07 +00009751 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9752 if (DSM.isAlreadyBeingDeclared())
9753 return 0;
9754
Richard Smith1c931be2012-04-02 18:40:40 +00009755 // [Checked after we build the declaration]
9756 // - the move assignment operator would not be implicitly defined as
9757 // deleted,
9758
9759 // [DR1402]:
9760 // - X has no direct or indirect virtual base class with a non-trivial
9761 // move assignment operator, and
9762 // - each of X's non-static data members and direct or virtual base classes
9763 // has a type that either has a move assignment operator or is trivially
9764 // copyable.
9765 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9766 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9767 ClassDecl->setFailedImplicitMoveAssignment();
9768 return 0;
9769 }
9770
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009771 // Note: The following rules are largely analoguous to the move
9772 // constructor rules.
9773
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009774 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9775 QualType RetType = Context.getLValueReferenceType(ArgType);
9776 ArgType = Context.getRValueReferenceType(ArgType);
9777
Richard Smitha8942d72013-05-07 03:19:20 +00009778 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9779 CXXMoveAssignment,
9780 false);
9781
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009782 // An implicitly-declared move assignment operator is an inline public
9783 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009784 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9785 SourceLocation ClassLoc = ClassDecl->getLocation();
9786 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009787 CXXMethodDecl *MoveAssignment =
9788 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9789 /*TInfo=*/0, /*StorageClass=*/SC_None,
9790 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009791 MoveAssignment->setAccess(AS_public);
9792 MoveAssignment->setDefaulted();
9793 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009794
Richard Smithb9d0b762012-07-27 04:22:15 +00009795 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009796 FunctionProtoType::ExtProtoInfo EPI =
9797 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009798 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009799
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009800 // Add the parameter to the operator.
9801 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9802 ClassLoc, ClassLoc, /*Id=*/0,
9803 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009804 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009805 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009806
Richard Smithbc2a35d2012-12-08 08:32:28 +00009807 AddOverriddenMethods(ClassDecl, MoveAssignment);
9808
9809 MoveAssignment->setTrivial(
9810 ClassDecl->needsOverloadResolutionForMoveAssignment()
9811 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9812 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009813
9814 // C++0x [class.copy]p9:
9815 // If the definition of a class X does not explicitly declare a move
9816 // assignment operator, one will be implicitly declared as defaulted if and
9817 // only if:
9818 // [...]
9819 // - the move assignment operator would not be implicitly defined as
9820 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009821 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009822 // Cache this result so that we don't try to generate this over and over
9823 // on every lookup, leaking memory and wasting time.
9824 ClassDecl->setFailedImplicitMoveAssignment();
9825 return 0;
9826 }
9827
Richard Smithbc2a35d2012-12-08 08:32:28 +00009828 // Note that we have added this copy-assignment operator.
9829 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9830
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009831 if (Scope *S = getScopeForContext(ClassDecl))
9832 PushOnScopeChains(MoveAssignment, S, false);
9833 ClassDecl->addDecl(MoveAssignment);
9834
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009835 return MoveAssignment;
9836}
9837
9838void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9839 CXXMethodDecl *MoveAssignOperator) {
9840 assert((MoveAssignOperator->isDefaulted() &&
9841 MoveAssignOperator->isOverloadedOperator() &&
9842 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009843 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9844 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009845 "DefineImplicitMoveAssignment called for wrong function");
9846
9847 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9848
9849 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9850 MoveAssignOperator->setInvalidDecl();
9851 return;
9852 }
9853
Eli Friedman86164e82013-09-05 00:02:25 +00009854 MoveAssignOperator->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009855
Eli Friedman9a14db32012-10-18 20:14:08 +00009856 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009857 DiagnosticErrorTrap Trap(Diags);
9858
9859 // C++0x [class.copy]p28:
9860 // The implicitly-defined or move assignment operator for a non-union class
9861 // X performs memberwise move assignment of its subobjects. The direct base
9862 // classes of X are assigned first, in the order of their declaration in the
9863 // base-specifier-list, and then the immediate non-static data members of X
9864 // are assigned, in the order in which they were declared in the class
9865 // definition.
9866
9867 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009868 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009869
9870 // The parameter for the "other" object, which we are move from.
9871 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9872 QualType OtherRefType = Other->getType()->
9873 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009874 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009875 "Bad argument type of defaulted move assignment");
9876
9877 // Our location for everything implicitly-generated.
9878 SourceLocation Loc = MoveAssignOperator->getLocation();
9879
Pavel Labath66ea35d2013-08-30 08:52:28 +00009880 // Builds a reference to the "other" object.
9881 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009882 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009883 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009884
Pavel Labath66ea35d2013-08-30 08:52:28 +00009885 // Builds the "this" pointer.
9886 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +00009887
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009888 // Assign base classes.
9889 bool Invalid = false;
9890 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9891 E = ClassDecl->bases_end(); Base != E; ++Base) {
9892 // Form the assignment:
9893 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9894 QualType BaseType = Base->getType().getUnqualifiedType();
9895 if (!BaseType->isRecordType()) {
9896 Invalid = true;
9897 continue;
9898 }
9899
9900 CXXCastPath BasePath;
9901 BasePath.push_back(Base);
9902
9903 // Construct the "from" expression, which is an implicit cast to the
9904 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009905 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009906
9907 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009908 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009909
9910 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009911 CastBuilder To(DerefThis,
9912 Context.getCVRQualifiedType(
9913 BaseType, MoveAssignOperator->getTypeQualifiers()),
9914 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009915
9916 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009917 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009918 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009919 /*CopyingBaseSubobject=*/true,
9920 /*Copying=*/false);
9921 if (Move.isInvalid()) {
9922 Diag(CurrentLocation, diag::note_member_synthesized_at)
9923 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9924 MoveAssignOperator->setInvalidDecl();
9925 return;
9926 }
9927
9928 // Success! Record the move.
9929 Statements.push_back(Move.takeAs<Expr>());
9930 }
9931
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009932 // Assign non-static members.
9933 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9934 FieldEnd = ClassDecl->field_end();
9935 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009936 if (Field->isUnnamedBitfield())
9937 continue;
9938
Eli Friedman8150da32013-06-07 01:48:56 +00009939 if (Field->isInvalidDecl()) {
9940 Invalid = true;
9941 continue;
9942 }
9943
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009944 // Check for members of reference type; we can't move those.
9945 if (Field->getType()->isReferenceType()) {
9946 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9947 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9948 Diag(Field->getLocation(), diag::note_declared_at);
9949 Diag(CurrentLocation, diag::note_member_synthesized_at)
9950 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9951 Invalid = true;
9952 continue;
9953 }
9954
9955 // Check for members of const-qualified, non-class type.
9956 QualType BaseType = Context.getBaseElementType(Field->getType());
9957 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9958 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9959 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9960 Diag(Field->getLocation(), diag::note_declared_at);
9961 Diag(CurrentLocation, diag::note_member_synthesized_at)
9962 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9963 Invalid = true;
9964 continue;
9965 }
9966
9967 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009968 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9969 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009970
9971 QualType FieldType = Field->getType().getNonReferenceType();
9972 if (FieldType->isIncompleteArrayType()) {
9973 assert(ClassDecl->hasFlexibleArrayMember() &&
9974 "Incomplete array type is not valid");
9975 continue;
9976 }
9977
9978 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009979 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9980 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009981 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009982 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009983 MemberBuilder From(MoveOther, OtherRefType,
9984 /*IsArrow=*/false, MemberLookup);
9985 MemberBuilder To(This, getCurrentThisType(),
9986 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009987
Pavel Labath66ea35d2013-08-30 08:52:28 +00009988 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009989 "Member reference with rvalue base must be rvalue except for reference "
9990 "members, which aren't allowed for move assignment.");
9991
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009992 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009993 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009994 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009995 /*CopyingBaseSubobject=*/false,
9996 /*Copying=*/false);
9997 if (Move.isInvalid()) {
9998 Diag(CurrentLocation, diag::note_member_synthesized_at)
9999 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10000 MoveAssignOperator->setInvalidDecl();
10001 return;
10002 }
Richard Smithe7ce7092012-11-12 23:33:00 +000010003
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010004 // Success! Record the copy.
10005 Statements.push_back(Move.takeAs<Stmt>());
10006 }
10007
10008 if (!Invalid) {
10009 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +000010010 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010011
10012 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
10013 if (Return.isInvalid())
10014 Invalid = true;
10015 else {
10016 Statements.push_back(Return.takeAs<Stmt>());
10017
10018 if (Trap.hasErrorOccurred()) {
10019 Diag(CurrentLocation, diag::note_member_synthesized_at)
10020 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10021 Invalid = true;
10022 }
10023 }
10024 }
10025
10026 if (Invalid) {
10027 MoveAssignOperator->setInvalidDecl();
10028 return;
10029 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010030
10031 StmtResult Body;
10032 {
10033 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010034 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010035 /*isStmtExpr=*/false);
10036 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10037 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010038 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
10039
10040 if (ASTMutationListener *L = getASTMutationListener()) {
10041 L->CompletedImplicitDefinition(MoveAssignOperator);
10042 }
10043}
10044
Richard Smithb9d0b762012-07-27 04:22:15 +000010045Sema::ImplicitExceptionSpecification
10046Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10047 CXXRecordDecl *ClassDecl = MD->getParent();
10048
10049 ImplicitExceptionSpecification ExceptSpec(*this);
10050 if (ClassDecl->isInvalidDecl())
10051 return ExceptSpec;
10052
10053 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10054 assert(T->getNumArgs() >= 1 && "not a copy ctor");
10055 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
10056
Douglas Gregor0d405db2010-07-01 20:59:04 +000010057 // C++ [except.spec]p14:
10058 // An implicitly declared special member function (Clause 12) shall have an
10059 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +000010060 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
10061 BaseEnd = ClassDecl->bases_end();
10062 Base != BaseEnd;
10063 ++Base) {
10064 // Virtual bases are handled below.
10065 if (Base->isVirtual())
10066 continue;
10067
Douglas Gregor22584312010-07-02 23:41:54 +000010068 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +000010069 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010070 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010071 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +000010072 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010073 }
10074 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
10075 BaseEnd = ClassDecl->vbases_end();
10076 Base != BaseEnd;
10077 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +000010078 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +000010079 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010080 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010081 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +000010082 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010083 }
10084 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
10085 FieldEnd = ClassDecl->field_end();
10086 Field != FieldEnd;
10087 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +000010088 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +000010089 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10090 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +000010091 LookupCopyingConstructor(FieldClassDecl,
10092 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +000010093 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010094 }
10095 }
Sebastian Redl60618fa2011-03-12 11:50:43 +000010096
Richard Smithb9d0b762012-07-27 04:22:15 +000010097 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +000010098}
10099
10100CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10101 CXXRecordDecl *ClassDecl) {
10102 // C++ [class.copy]p4:
10103 // If the class definition does not explicitly declare a copy
10104 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +000010105 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +000010106
Richard Smithafb49182012-11-29 01:34:07 +000010107 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10108 if (DSM.isAlreadyBeingDeclared())
10109 return 0;
10110
Sean Hunt49634cf2011-05-13 06:10:58 +000010111 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10112 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +000010113 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +000010114 if (Const)
10115 ArgType = ArgType.withConst();
10116 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +000010117
Richard Smith7756afa2012-06-10 05:43:50 +000010118 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10119 CXXCopyConstructor,
10120 Const);
10121
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010122 DeclarationName Name
10123 = Context.DeclarationNames.getCXXConstructorName(
10124 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010125 SourceLocation ClassLoc = ClassDecl->getLocation();
10126 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +000010127
10128 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010129 // member of its class.
10130 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010131 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010132 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010133 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010134 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +000010135 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010136
Richard Smithb9d0b762012-07-27 04:22:15 +000010137 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010138 FunctionProtoType::ExtProtoInfo EPI =
10139 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010140 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010141 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010142
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010143 // Add the parameter to the constructor.
10144 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010145 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010146 /*IdentifierInfo=*/0,
10147 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +000010148 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010149 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +000010150
Richard Smithbc2a35d2012-12-08 08:32:28 +000010151 CopyConstructor->setTrivial(
10152 ClassDecl->needsOverloadResolutionForCopyConstructor()
10153 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10154 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +000010155
Nico Weberafcc96a2012-01-23 03:19:29 +000010156 // C++11 [class.copy]p8:
10157 // ... If the class definition does not explicitly declare a copy
10158 // constructor, there is no user-declared move constructor, and there is no
10159 // user-declared move assignment operator, a copy constructor is implicitly
10160 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +000010161 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +000010162 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +000010163
Richard Smithbc2a35d2012-12-08 08:32:28 +000010164 // Note that we have declared this constructor.
10165 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10166
10167 if (Scope *S = getScopeForContext(ClassDecl))
10168 PushOnScopeChains(CopyConstructor, S, false);
10169 ClassDecl->addDecl(CopyConstructor);
10170
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010171 return CopyConstructor;
10172}
10173
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010174void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +000010175 CXXConstructorDecl *CopyConstructor) {
10176 assert((CopyConstructor->isDefaulted() &&
10177 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010178 !CopyConstructor->doesThisDeclarationHaveABody() &&
10179 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010180 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +000010181
Anders Carlsson63010a72010-04-23 16:24:12 +000010182 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010183 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010184
Richard Smith36155c12013-06-13 03:23:42 +000010185 // C++11 [class.copy]p7:
Benjamin Kramere5753592013-09-09 14:48:42 +000010186 // The [definition of an implicitly declared copy constructor] is
Richard Smith36155c12013-06-13 03:23:42 +000010187 // deprecated if the class has a user-declared copy assignment operator
10188 // or a user-declared destructor.
10189 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10190 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10191
Eli Friedman9a14db32012-10-18 20:14:08 +000010192 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +000010193 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010194
David Blaikie93c86172013-01-17 05:26:25 +000010195 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +000010196 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +000010197 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010198 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +000010199 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010200 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010201 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010202 CopyConstructor->setBody(ActOnCompoundStmt(
10203 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10204 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +000010205 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010206
Eli Friedman86164e82013-09-05 00:02:25 +000010207 CopyConstructor->markUsed(Context);
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010208 if (ASTMutationListener *L = getASTMutationListener()) {
10209 L->CompletedImplicitDefinition(CopyConstructor);
10210 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010211}
10212
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010213Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010214Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10215 CXXRecordDecl *ClassDecl = MD->getParent();
10216
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010217 // C++ [except.spec]p14:
10218 // An implicitly declared special member function (Clause 12) shall have an
10219 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +000010220 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010221 if (ClassDecl->isInvalidDecl())
10222 return ExceptSpec;
10223
10224 // Direct base-class constructors.
10225 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10226 BEnd = ClassDecl->bases_end();
10227 B != BEnd; ++B) {
10228 if (B->isVirtual()) // Handled below.
10229 continue;
10230
10231 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10232 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010233 CXXConstructorDecl *Constructor =
10234 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010235 // If this is a deleted function, add it anyway. This might be conformant
10236 // with the standard. This might not. I'm not sure. It might not matter.
10237 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010238 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010239 }
10240 }
10241
10242 // Virtual base-class constructors.
10243 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10244 BEnd = ClassDecl->vbases_end();
10245 B != BEnd; ++B) {
10246 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10247 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010248 CXXConstructorDecl *Constructor =
10249 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010250 // If this is a deleted function, add it anyway. This might be conformant
10251 // with the standard. This might not. I'm not sure. It might not matter.
10252 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010253 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010254 }
10255 }
10256
10257 // Field constructors.
10258 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10259 FEnd = ClassDecl->field_end();
10260 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010261 QualType FieldType = Context.getBaseElementType(F->getType());
10262 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10263 CXXConstructorDecl *Constructor =
10264 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010265 // If this is a deleted function, add it anyway. This might be conformant
10266 // with the standard. This might not. I'm not sure. It might not matter.
10267 // In particular, the problem is that this function never gets called. It
10268 // might just be ill-formed because this function attempts to refer to
10269 // a deleted function here.
10270 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010271 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010272 }
10273 }
10274
10275 return ExceptSpec;
10276}
10277
10278CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10279 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010280 // C++11 [class.copy]p9:
10281 // If the definition of a class X does not explicitly declare a move
10282 // constructor, one will be implicitly declared as defaulted if and only if:
10283 //
10284 // - [first 4 bullets]
10285 assert(ClassDecl->needsImplicitMoveConstructor());
10286
Richard Smithafb49182012-11-29 01:34:07 +000010287 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10288 if (DSM.isAlreadyBeingDeclared())
10289 return 0;
10290
Richard Smith1c931be2012-04-02 18:40:40 +000010291 // [Checked after we build the declaration]
10292 // - the move assignment operator would not be implicitly defined as
10293 // deleted,
10294
10295 // [DR1402]:
10296 // - each of X's non-static data members and direct or virtual base classes
10297 // has a type that either has a move constructor or is trivially copyable.
10298 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
10299 ClassDecl->setFailedImplicitMoveConstructor();
10300 return 0;
10301 }
10302
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010303 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10304 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010305
Richard Smith7756afa2012-06-10 05:43:50 +000010306 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10307 CXXMoveConstructor,
10308 false);
10309
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010310 DeclarationName Name
10311 = Context.DeclarationNames.getCXXConstructorName(
10312 Context.getCanonicalType(ClassType));
10313 SourceLocation ClassLoc = ClassDecl->getLocation();
10314 DeclarationNameInfo NameInfo(Name, ClassLoc);
10315
Richard Smitha8942d72013-05-07 03:19:20 +000010316 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010317 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010318 // member of its class.
10319 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010320 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010321 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010322 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010323 MoveConstructor->setAccess(AS_public);
10324 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010325
Richard Smithb9d0b762012-07-27 04:22:15 +000010326 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010327 FunctionProtoType::ExtProtoInfo EPI =
10328 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010329 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010330 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010331
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010332 // Add the parameter to the constructor.
10333 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10334 ClassLoc, ClassLoc,
10335 /*IdentifierInfo=*/0,
10336 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010337 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010338 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010339
Richard Smithbc2a35d2012-12-08 08:32:28 +000010340 MoveConstructor->setTrivial(
10341 ClassDecl->needsOverloadResolutionForMoveConstructor()
10342 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10343 : ClassDecl->hasTrivialMoveConstructor());
10344
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010345 // C++0x [class.copy]p9:
10346 // If the definition of a class X does not explicitly declare a move
10347 // constructor, one will be implicitly declared as defaulted if and only if:
10348 // [...]
10349 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +000010350 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010351 // Cache this result so that we don't try to generate this over and over
10352 // on every lookup, leaking memory and wasting time.
10353 ClassDecl->setFailedImplicitMoveConstructor();
10354 return 0;
10355 }
10356
10357 // Note that we have declared this constructor.
10358 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10359
10360 if (Scope *S = getScopeForContext(ClassDecl))
10361 PushOnScopeChains(MoveConstructor, S, false);
10362 ClassDecl->addDecl(MoveConstructor);
10363
10364 return MoveConstructor;
10365}
10366
10367void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10368 CXXConstructorDecl *MoveConstructor) {
10369 assert((MoveConstructor->isDefaulted() &&
10370 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010371 !MoveConstructor->doesThisDeclarationHaveABody() &&
10372 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010373 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10374
10375 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10376 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10377
Eli Friedman9a14db32012-10-18 20:14:08 +000010378 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010379 DiagnosticErrorTrap Trap(Diags);
10380
David Blaikie93c86172013-01-17 05:26:25 +000010381 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010382 Trap.hasErrorOccurred()) {
10383 Diag(CurrentLocation, diag::note_member_synthesized_at)
10384 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10385 MoveConstructor->setInvalidDecl();
10386 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010387 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010388 MoveConstructor->setBody(ActOnCompoundStmt(
10389 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10390 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010391 }
10392
Eli Friedman86164e82013-09-05 00:02:25 +000010393 MoveConstructor->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010394
10395 if (ASTMutationListener *L = getASTMutationListener()) {
10396 L->CompletedImplicitDefinition(MoveConstructor);
10397 }
10398}
10399
Douglas Gregore4e68d42012-02-15 19:33:52 +000010400bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010401 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010402}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010403
10404void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Valid6992ab2013-09-29 08:45:24 +000010405 SourceLocation CurrentLocation,
10406 CXXConversionDecl *Conv) {
10407 CXXRecordDecl *Lambda = Conv->getParent();
10408 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10409 // If we are defining a specialization of a conversion to function-ptr
10410 // cache the deduced template arguments for this specialization
10411 // so that we can use them to retrieve the corresponding call-operator
10412 // and static-invoker.
10413 const TemplateArgumentList *DeducedTemplateArgs = 0;
10414
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010415
Faisal Valid6992ab2013-09-29 08:45:24 +000010416 // Retrieve the corresponding call-operator specialization.
10417 if (Lambda->isGenericLambda()) {
10418 assert(Conv->isFunctionTemplateSpecialization());
10419 FunctionTemplateDecl *CallOpTemplate =
10420 CallOp->getDescribedFunctionTemplate();
10421 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10422 void *InsertPos = 0;
10423 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10424 DeducedTemplateArgs->data(),
10425 DeducedTemplateArgs->size(),
10426 InsertPos);
10427 assert(CallOpSpec &&
10428 "Conversion operator must have a corresponding call operator");
10429 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10430 }
10431 // Mark the call operator referenced (and add to pending instantiations
10432 // if necessary).
10433 // For both the conversion and static-invoker template specializations
10434 // we construct their body's in this function, so no need to add them
10435 // to the PendingInstantiations.
10436 MarkFunctionReferenced(CurrentLocation, CallOp);
10437
Eli Friedman9a14db32012-10-18 20:14:08 +000010438 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010439 DiagnosticErrorTrap Trap(Diags);
Faisal Valid6992ab2013-09-29 08:45:24 +000010440
10441 // Retreive the static invoker...
10442 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10443 // ... and get the corresponding specialization for a generic lambda.
10444 if (Lambda->isGenericLambda()) {
10445 assert(DeducedTemplateArgs &&
10446 "Must have deduced template arguments from Conversion Operator");
10447 FunctionTemplateDecl *InvokeTemplate =
10448 Invoker->getDescribedFunctionTemplate();
10449 void *InsertPos = 0;
10450 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10451 DeducedTemplateArgs->data(),
10452 DeducedTemplateArgs->size(),
10453 InsertPos);
10454 assert(InvokeSpec &&
10455 "Must have a corresponding static invoker specialization");
10456 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10457 }
10458 // Construct the body of the conversion function { return __invoke; }.
10459 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10460 VK_LValue, Conv->getLocation()).take();
10461 assert(FunctionRef && "Can't refer to __invoke function?");
10462 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10463 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10464 Conv->getLocation(),
10465 Conv->getLocation()));
10466
10467 Conv->markUsed(Context);
10468 Conv->setReferenced();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010469
Faisal Valid6992ab2013-09-29 08:45:24 +000010470 // Fill in the __invoke function with a dummy implementation. IR generation
10471 // will fill in the actual details.
10472 Invoker->markUsed(Context);
10473 Invoker->setReferenced();
10474 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10475
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010476 if (ASTMutationListener *L = getASTMutationListener()) {
10477 L->CompletedImplicitDefinition(Conv);
Faisal Valid6992ab2013-09-29 08:45:24 +000010478 L->CompletedImplicitDefinition(Invoker);
10479 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010480}
10481
Faisal Valid6992ab2013-09-29 08:45:24 +000010482
10483
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010484void Sema::DefineImplicitLambdaToBlockPointerConversion(
10485 SourceLocation CurrentLocation,
10486 CXXConversionDecl *Conv)
10487{
Faisal Vali56fe35b2013-09-29 17:08:32 +000010488 assert(!Conv->getParent()->isGenericLambda());
Faisal Valid6992ab2013-09-29 08:45:24 +000010489
Eli Friedman86164e82013-09-05 00:02:25 +000010490 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010491
Eli Friedman9a14db32012-10-18 20:14:08 +000010492 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010493 DiagnosticErrorTrap Trap(Diags);
10494
Douglas Gregorac1303e2012-02-22 05:02:47 +000010495 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010496 Expr *This = ActOnCXXThis(CurrentLocation).take();
10497 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010498
Eli Friedman23f02672012-03-01 04:01:32 +000010499 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10500 Conv->getLocation(),
10501 Conv, DerefThis);
10502
10503 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10504 // behavior. Note that only the general conversion function does this
10505 // (since it's unusable otherwise); in the case where we inline the
10506 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010507 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010508 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10509 CK_CopyAndAutoreleaseBlockObject,
10510 BuildBlock.get(), 0, VK_RValue);
10511
10512 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010513 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010514 Conv->setInvalidDecl();
10515 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010516 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010517
Douglas Gregorac1303e2012-02-22 05:02:47 +000010518 // Create the return statement that returns the block from the conversion
10519 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010520 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010521 if (Return.isInvalid()) {
10522 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10523 Conv->setInvalidDecl();
10524 return;
10525 }
10526
10527 // Set the body of the conversion function.
10528 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010529 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010530 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010531 Conv->getLocation()));
10532
Douglas Gregorac1303e2012-02-22 05:02:47 +000010533 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010534 if (ASTMutationListener *L = getASTMutationListener()) {
10535 L->CompletedImplicitDefinition(Conv);
10536 }
10537}
10538
Douglas Gregorf52757d2012-03-10 06:53:13 +000010539/// \brief Determine whether the given list arguments contains exactly one
10540/// "real" (non-default) argument.
10541static bool hasOneRealArgument(MultiExprArg Args) {
10542 switch (Args.size()) {
10543 case 0:
10544 return false;
10545
10546 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010547 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010548 return false;
10549
10550 // fall through
10551 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010552 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010553 }
10554
10555 return false;
10556}
10557
John McCall60d7b3a2010-08-24 06:29:42 +000010558ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010559Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010560 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010561 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010562 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010563 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010564 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010565 unsigned ConstructKind,
10566 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010567 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010568
Douglas Gregor2f599792010-04-02 18:24:57 +000010569 // C++0x [class.copy]p34:
10570 // When certain criteria are met, an implementation is allowed to
10571 // omit the copy/move construction of a class object, even if the
10572 // copy/move constructor and/or destructor for the object have
10573 // side effects. [...]
10574 // - when a temporary class object that has not been bound to a
10575 // reference (12.2) would be copied/moved to a class object
10576 // with the same cv-unqualified type, the copy/move operation
10577 // can be omitted by constructing the temporary object
10578 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010579 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010580 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010581 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010582 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010583 }
Mike Stump1eb44332009-09-09 15:08:12 +000010584
10585 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010586 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010587 IsListInitialization, RequiresZeroInit,
10588 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010589}
10590
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010591/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10592/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010593ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010594Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10595 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010596 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010597 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010598 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010599 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010600 unsigned ConstructKind,
10601 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010602 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010603 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010604 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010605 HadMultipleCandidates,
10606 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010607 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10608 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010609}
10610
John McCall68c6c9a2010-02-02 09:10:11 +000010611void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010612 if (VD->isInvalidDecl()) return;
10613
John McCall68c6c9a2010-02-02 09:10:11 +000010614 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010615 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010616 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010617 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010618
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010619 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010620 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010621 CheckDestructorAccess(VD->getLocation(), Destructor,
10622 PDiag(diag::err_access_dtor_var)
10623 << VD->getDeclName()
10624 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010625 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010626
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010627 if (!VD->hasGlobalStorage()) return;
10628
10629 // Emit warning for non-trivial dtor in global scope (a real global,
10630 // class-static, function-static).
10631 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10632
10633 // TODO: this should be re-enabled for static locals by !CXAAtExit
10634 if (!VD->isStaticLocal())
10635 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010636}
10637
Douglas Gregor39da0b82009-09-09 23:08:42 +000010638/// \brief Given a constructor and the set of arguments provided for the
10639/// constructor, convert the arguments and add any required default arguments
10640/// to form a proper call to this constructor.
10641///
10642/// \returns true if an error occurred, false otherwise.
10643bool
10644Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10645 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010646 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010647 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010648 bool AllowExplicit,
10649 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010650 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10651 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010652 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010653
10654 const FunctionProtoType *Proto
10655 = Constructor->getType()->getAs<FunctionProtoType>();
10656 assert(Proto && "Constructor without a prototype?");
10657 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010658
10659 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010660 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010661 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010662 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010663 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010664
10665 VariadicCallType CallType =
10666 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010667 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010668 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010669 Proto, 0,
10670 llvm::makeArrayRef(Args, NumArgs),
10671 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010672 CallType, AllowExplicit,
10673 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010674 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010675
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010676 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010677
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010678 CheckConstructorCall(Constructor,
10679 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10680 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010681 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010682
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010683 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010684}
10685
Anders Carlsson20d45d22009-12-12 00:32:00 +000010686static inline bool
10687CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10688 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010689 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010690 if (isa<NamespaceDecl>(DC)) {
10691 return SemaRef.Diag(FnDecl->getLocation(),
10692 diag::err_operator_new_delete_declared_in_namespace)
10693 << FnDecl->getDeclName();
10694 }
10695
10696 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010697 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010698 return SemaRef.Diag(FnDecl->getLocation(),
10699 diag::err_operator_new_delete_declared_static)
10700 << FnDecl->getDeclName();
10701 }
10702
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010703 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010704}
10705
Anders Carlsson156c78e2009-12-13 17:53:43 +000010706static inline bool
10707CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10708 CanQualType ExpectedResultType,
10709 CanQualType ExpectedFirstParamType,
10710 unsigned DependentParamTypeDiag,
10711 unsigned InvalidParamTypeDiag) {
10712 QualType ResultType =
10713 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10714
10715 // Check that the result type is not dependent.
10716 if (ResultType->isDependentType())
10717 return SemaRef.Diag(FnDecl->getLocation(),
10718 diag::err_operator_new_delete_dependent_result_type)
10719 << FnDecl->getDeclName() << ExpectedResultType;
10720
10721 // Check that the result type is what we expect.
10722 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10723 return SemaRef.Diag(FnDecl->getLocation(),
10724 diag::err_operator_new_delete_invalid_result_type)
10725 << FnDecl->getDeclName() << ExpectedResultType;
10726
10727 // A function template must have at least 2 parameters.
10728 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10729 return SemaRef.Diag(FnDecl->getLocation(),
10730 diag::err_operator_new_delete_template_too_few_parameters)
10731 << FnDecl->getDeclName();
10732
10733 // The function decl must have at least 1 parameter.
10734 if (FnDecl->getNumParams() == 0)
10735 return SemaRef.Diag(FnDecl->getLocation(),
10736 diag::err_operator_new_delete_too_few_parameters)
10737 << FnDecl->getDeclName();
10738
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010739 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010740 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10741 if (FirstParamType->isDependentType())
10742 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10743 << FnDecl->getDeclName() << ExpectedFirstParamType;
10744
10745 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010746 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010747 ExpectedFirstParamType)
10748 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10749 << FnDecl->getDeclName() << ExpectedFirstParamType;
10750
10751 return false;
10752}
10753
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010754static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010755CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010756 // C++ [basic.stc.dynamic.allocation]p1:
10757 // A program is ill-formed if an allocation function is declared in a
10758 // namespace scope other than global scope or declared static in global
10759 // scope.
10760 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10761 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010762
10763 CanQualType SizeTy =
10764 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10765
10766 // C++ [basic.stc.dynamic.allocation]p1:
10767 // The return type shall be void*. The first parameter shall have type
10768 // std::size_t.
10769 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10770 SizeTy,
10771 diag::err_operator_new_dependent_param_type,
10772 diag::err_operator_new_param_type))
10773 return true;
10774
10775 // C++ [basic.stc.dynamic.allocation]p1:
10776 // The first parameter shall not have an associated default argument.
10777 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010778 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010779 diag::err_operator_new_default_arg)
10780 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10781
10782 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010783}
10784
10785static bool
Richard Smith444d3842012-10-20 08:26:51 +000010786CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010787 // C++ [basic.stc.dynamic.deallocation]p1:
10788 // A program is ill-formed if deallocation functions are declared in a
10789 // namespace scope other than global scope or declared static in global
10790 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010791 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10792 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010793
10794 // C++ [basic.stc.dynamic.deallocation]p2:
10795 // Each deallocation function shall return void and its first parameter
10796 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010797 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10798 SemaRef.Context.VoidPtrTy,
10799 diag::err_operator_delete_dependent_param_type,
10800 diag::err_operator_delete_param_type))
10801 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010802
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010803 return false;
10804}
10805
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010806/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10807/// of this overloaded operator is well-formed. If so, returns false;
10808/// otherwise, emits appropriate diagnostics and returns true.
10809bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010810 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010811 "Expected an overloaded operator declaration");
10812
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010813 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10814
Mike Stump1eb44332009-09-09 15:08:12 +000010815 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010816 // The allocation and deallocation functions, operator new,
10817 // operator new[], operator delete and operator delete[], are
10818 // described completely in 3.7.3. The attributes and restrictions
10819 // found in the rest of this subclause do not apply to them unless
10820 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010821 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010822 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010823
Anders Carlssona3ccda52009-12-12 00:26:23 +000010824 if (Op == OO_New || Op == OO_Array_New)
10825 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010826
10827 // C++ [over.oper]p6:
10828 // An operator function shall either be a non-static member
10829 // function or be a non-member function and have at least one
10830 // parameter whose type is a class, a reference to a class, an
10831 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010832 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10833 if (MethodDecl->isStatic())
10834 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010835 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010836 } else {
10837 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010838 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10839 ParamEnd = FnDecl->param_end();
10840 Param != ParamEnd; ++Param) {
10841 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010842 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10843 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010844 ClassOrEnumParam = true;
10845 break;
10846 }
10847 }
10848
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010849 if (!ClassOrEnumParam)
10850 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010851 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010852 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010853 }
10854
10855 // C++ [over.oper]p8:
10856 // An operator function cannot have default arguments (8.3.6),
10857 // except where explicitly stated below.
10858 //
Mike Stump1eb44332009-09-09 15:08:12 +000010859 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010860 // (C++ [over.call]p1).
10861 if (Op != OO_Call) {
10862 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10863 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010864 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010865 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010866 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010867 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010868 }
10869 }
10870
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010871 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10872 { false, false, false }
10873#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10874 , { Unary, Binary, MemberOnly }
10875#include "clang/Basic/OperatorKinds.def"
10876 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010877
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010878 bool CanBeUnaryOperator = OperatorUses[Op][0];
10879 bool CanBeBinaryOperator = OperatorUses[Op][1];
10880 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010881
10882 // C++ [over.oper]p8:
10883 // [...] Operator functions cannot have more or fewer parameters
10884 // than the number required for the corresponding operator, as
10885 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010886 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010887 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010888 if (Op != OO_Call &&
10889 ((NumParams == 1 && !CanBeUnaryOperator) ||
10890 (NumParams == 2 && !CanBeBinaryOperator) ||
10891 (NumParams < 1) || (NumParams > 2))) {
10892 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010893 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010894 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010895 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010896 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010897 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010898 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010899 assert(CanBeBinaryOperator &&
10900 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010901 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010902 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010903
Chris Lattner416e46f2008-11-21 07:57:12 +000010904 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010905 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010906 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010907
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010908 // Overloaded operators other than operator() cannot be variadic.
10909 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010910 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010911 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010912 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010913 }
10914
10915 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010916 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10917 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010918 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010919 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010920 }
10921
10922 // C++ [over.inc]p1:
10923 // The user-defined function called operator++ implements the
10924 // prefix and postfix ++ operator. If this function is a member
10925 // function with no parameters, or a non-member function with one
10926 // parameter of class or enumeration type, it defines the prefix
10927 // increment operator ++ for objects of that type. If the function
10928 // is a member function with one parameter (which shall be of type
10929 // int) or a non-member function with two parameters (the second
10930 // of which shall be of type int), it defines the postfix
10931 // increment operator ++ for objects of that type.
10932 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10933 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10934 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010935 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010936 ParamIsInt = BT->getKind() == BuiltinType::Int;
10937
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010938 if (!ParamIsInt)
10939 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010940 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010941 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010942 }
10943
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010944 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010945}
Chris Lattner5a003a42008-12-17 07:09:26 +000010946
Sean Hunta6c058d2010-01-13 09:01:02 +000010947/// CheckLiteralOperatorDeclaration - Check whether the declaration
10948/// of this literal operator function is well-formed. If so, returns
10949/// false; otherwise, emits appropriate diagnostics and returns true.
10950bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010951 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010952 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10953 << FnDecl->getDeclName();
10954 return true;
10955 }
10956
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010957 if (FnDecl->isExternC()) {
10958 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10959 return true;
10960 }
10961
Sean Hunta6c058d2010-01-13 09:01:02 +000010962 bool Valid = false;
10963
Richard Smith36f5cfe2012-03-09 08:00:36 +000010964 // This might be the definition of a literal operator template.
10965 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10966 // This might be a specialization of a literal operator template.
10967 if (!TpDecl)
10968 TpDecl = FnDecl->getPrimaryTemplate();
10969
Richard Smithb328e292013-10-07 19:57:58 +000010970 // template <char...> type operator "" name() and
10971 // template <class T, T...> type operator "" name() are the only valid
10972 // template signatures, and the only valid signatures with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010973 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010974 if (FnDecl->param_size() == 0) {
Richard Smithb328e292013-10-07 19:57:58 +000010975 // Must have one or two template parameters
Sean Hunt216c2782010-04-07 23:11:06 +000010976 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10977 if (Params->size() == 1) {
10978 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010979 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010980
Sean Hunt216c2782010-04-07 23:11:06 +000010981 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010982 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10983 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10984 Valid = true;
Richard Smithb328e292013-10-07 19:57:58 +000010985 } else if (Params->size() == 2) {
10986 TemplateTypeParmDecl *PmType =
10987 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10988 NonTypeTemplateParmDecl *PmArgs =
10989 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10990
10991 // The second template parameter must be a parameter pack with the
10992 // first template parameter as its type.
10993 if (PmType && PmArgs &&
10994 !PmType->isTemplateParameterPack() &&
10995 PmArgs->isTemplateParameterPack()) {
10996 const TemplateTypeParmType *TArgs =
10997 PmArgs->getType()->getAs<TemplateTypeParmType>();
10998 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10999 TArgs->getIndex() == PmType->getIndex()) {
11000 Valid = true;
11001 if (ActiveTemplateInstantiations.empty())
11002 Diag(FnDecl->getLocation(),
11003 diag::ext_string_literal_operator_template);
11004 }
11005 }
Sean Hunt216c2782010-04-07 23:11:06 +000011006 }
11007 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011008 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000011009 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000011010 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11011
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011012 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000011013
Sean Hunt30019c02010-04-07 22:57:35 +000011014 // unsigned long long int, long double, and any character type are allowed
11015 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000011016 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11017 Context.hasSameType(T, Context.LongDoubleTy) ||
11018 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000011019 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000011020 Context.hasSameType(T, Context.Char16Ty) ||
11021 Context.hasSameType(T, Context.Char32Ty)) {
11022 if (++Param == FnDecl->param_end())
11023 Valid = true;
11024 goto FinishedParams;
11025 }
11026
Sean Hunt30019c02010-04-07 22:57:35 +000011027 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000011028 const PointerType *PT = T->getAs<PointerType>();
11029 if (!PT)
11030 goto FinishedParams;
11031 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011032 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000011033 goto FinishedParams;
11034 T = T.getUnqualifiedType();
11035
11036 // Move on to the second parameter;
11037 ++Param;
11038
11039 // If there is no second parameter, the first must be a const char *
11040 if (Param == FnDecl->param_end()) {
11041 if (Context.hasSameType(T, Context.CharTy))
11042 Valid = true;
11043 goto FinishedParams;
11044 }
11045
11046 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11047 // are allowed as the first parameter to a two-parameter function
11048 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000011049 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000011050 Context.hasSameType(T, Context.Char16Ty) ||
11051 Context.hasSameType(T, Context.Char32Ty)))
11052 goto FinishedParams;
11053
11054 // The second and final parameter must be an std::size_t
11055 T = (*Param)->getType().getUnqualifiedType();
11056 if (Context.hasSameType(T, Context.getSizeType()) &&
11057 ++Param == FnDecl->param_end())
11058 Valid = true;
11059 }
11060
11061 // FIXME: This diagnostic is absolutely terrible.
11062FinishedParams:
11063 if (!Valid) {
11064 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11065 << FnDecl->getDeclName();
11066 return true;
11067 }
11068
Richard Smitha9e88b22012-03-09 08:16:22 +000011069 // A parameter-declaration-clause containing a default argument is not
11070 // equivalent to any of the permitted forms.
11071 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
11072 ParamEnd = FnDecl->param_end();
11073 Param != ParamEnd; ++Param) {
11074 if ((*Param)->hasDefaultArg()) {
11075 Diag((*Param)->getDefaultArgRange().getBegin(),
11076 diag::err_literal_operator_default_argument)
11077 << (*Param)->getDefaultArgRange();
11078 break;
11079 }
11080 }
11081
Richard Smith2fb4ae32012-03-08 02:39:21 +000011082 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000011083 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11084 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000011085 // C++11 [usrlit.suffix]p1:
11086 // Literal suffix identifiers that do not start with an underscore
11087 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000011088 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11089 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000011090 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000011091
Sean Hunta6c058d2010-01-13 09:01:02 +000011092 return false;
11093}
11094
Douglas Gregor074149e2009-01-05 19:45:36 +000011095/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11096/// linkage specification, including the language and (if present)
11097/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
11098/// the location of the language string literal, which is provided
11099/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
11100/// the '{' brace. Otherwise, this linkage specification does not
11101/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000011102Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11103 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011104 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000011105 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000011106 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000011107 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011108 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000011109 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011110 Language = LinkageSpecDecl::lang_cxx;
11111 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000011112 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000011113 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011114 }
Mike Stump1eb44332009-09-09 15:08:12 +000011115
Chris Lattnercc98eac2008-12-17 07:13:27 +000011116 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000011117
Douglas Gregor074149e2009-01-05 19:45:36 +000011118 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000011119 ExternLoc, LangLoc, Language,
11120 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011121 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000011122 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000011123 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011124}
11125
Abramo Bagnara35f9a192010-07-30 16:47:02 +000011126/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000011127/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11128/// valid, it's the position of the closing '}' brace in a linkage
11129/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000011130Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011131 Decl *LinkageSpec,
11132 SourceLocation RBraceLoc) {
11133 if (LinkageSpec) {
11134 if (RBraceLoc.isValid()) {
11135 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11136 LSDecl->setRBraceLoc(RBraceLoc);
11137 }
Douglas Gregor074149e2009-01-05 19:45:36 +000011138 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011139 }
Douglas Gregor074149e2009-01-05 19:45:36 +000011140 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000011141}
11142
Michael Han684aa732013-02-22 17:15:32 +000011143Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11144 AttributeList *AttrList,
11145 SourceLocation SemiLoc) {
11146 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11147 // Attribute declarations appertain to empty declaration so we handle
11148 // them here.
11149 if (AttrList)
11150 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000011151
Michael Han684aa732013-02-22 17:15:32 +000011152 CurContext->addDecl(ED);
11153 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000011154}
11155
Douglas Gregord308e622009-05-18 20:51:54 +000011156/// \brief Perform semantic analysis for the variable declaration that
11157/// occurs within a C++ catch clause, returning the newly-created
11158/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011159VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000011160 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011161 SourceLocation StartLoc,
11162 SourceLocation Loc,
11163 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000011164 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000011165 QualType ExDeclType = TInfo->getType();
11166
Sebastian Redl4b07b292008-12-22 19:15:10 +000011167 // Arrays and functions decay.
11168 if (ExDeclType->isArrayType())
11169 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11170 else if (ExDeclType->isFunctionType())
11171 ExDeclType = Context.getPointerType(ExDeclType);
11172
11173 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11174 // The exception-declaration shall not denote a pointer or reference to an
11175 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011176 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000011177 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000011178 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011179 Invalid = true;
11180 }
Douglas Gregord308e622009-05-18 20:51:54 +000011181
Sebastian Redl4b07b292008-12-22 19:15:10 +000011182 QualType BaseType = ExDeclType;
11183 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000011184 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000011185 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011186 BaseType = Ptr->getPointeeType();
11187 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011188 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000011189 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011190 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011191 BaseType = Ref->getPointeeType();
11192 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011193 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011194 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011195 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000011196 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000011197 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011198
Mike Stump1eb44332009-09-09 15:08:12 +000011199 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000011200 RequireNonAbstractType(Loc, ExDeclType,
11201 diag::err_abstract_type_in_decl,
11202 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000011203 Invalid = true;
11204
John McCall5a180392010-07-24 00:37:23 +000011205 // Only the non-fragile NeXT runtime currently supports C++ catches
11206 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000011207 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000011208 QualType T = ExDeclType;
11209 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11210 T = RT->getPointeeType();
11211
11212 if (T->isObjCObjectType()) {
11213 Diag(Loc, diag::err_objc_object_catch);
11214 Invalid = true;
11215 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000011216 // FIXME: should this be a test for macosx-fragile specifically?
11217 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000011218 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000011219 }
11220 }
11221
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011222 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000011223 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000011224 ExDecl->setExceptionVariable(true);
11225
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011226 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011227 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011228 Invalid = true;
11229
Douglas Gregorc41b8782011-07-06 18:14:43 +000011230 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000011231 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000011232 // Insulate this from anything else we might currently be parsing.
11233 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11234
Douglas Gregor6d182892010-03-05 23:38:39 +000011235 // C++ [except.handle]p16:
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011236 // The object declared in an exception-declaration or, if the
11237 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6d182892010-03-05 23:38:39 +000011238 // copy-initialized (8.5) from the exception object. [...]
11239 // The object is destroyed when the handler exits, after the destruction
11240 // of any automatic objects initialized within the handler.
11241 //
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011242 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6d182892010-03-05 23:38:39 +000011243 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000011244 QualType initType = ExDeclType;
11245
11246 InitializedEntity entity =
11247 InitializedEntity::InitializeVariable(ExDecl);
11248 InitializationKind initKind =
11249 InitializationKind::CreateCopy(Loc, SourceLocation());
11250
11251 Expr *opaqueValue =
11252 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011253 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11254 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000011255 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000011256 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000011257 else {
11258 // If the constructor used was non-trivial, set this as the
11259 // "initializer".
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011260 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCalle996ffd2011-02-16 08:02:54 +000011261 if (!construct->getConstructor()->isTrivial()) {
11262 Expr *init = MaybeCreateExprWithCleanups(construct);
11263 ExDecl->setInit(init);
11264 }
11265
11266 // And make sure it's destructable.
11267 FinalizeVarWithDestructor(ExDecl, recordType);
11268 }
Douglas Gregor6d182892010-03-05 23:38:39 +000011269 }
11270 }
11271
Douglas Gregord308e622009-05-18 20:51:54 +000011272 if (Invalid)
11273 ExDecl->setInvalidDecl();
11274
11275 return ExDecl;
11276}
11277
11278/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11279/// handler.
John McCalld226f652010-08-21 09:40:31 +000011280Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000011281 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000011282 bool Invalid = D.isInvalidType();
11283
11284 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000011285 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11286 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000011287 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11288 D.getIdentifierLoc());
11289 Invalid = true;
11290 }
11291
Sebastian Redl4b07b292008-12-22 19:15:10 +000011292 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000011293 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000011294 LookupOrdinaryName,
11295 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011296 // The scope should be freshly made just for us. There is just no way
11297 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000011298 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000011299 if (PrevDecl->isTemplateParameter()) {
11300 // Maybe we will complain about the shadowed template parameter.
11301 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000011302 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011303 }
11304 }
11305
Chris Lattnereaaebc72009-04-25 08:06:05 +000011306 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011307 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11308 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000011309 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011310 }
11311
Douglas Gregor83cb9422010-09-09 17:09:21 +000011312 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000011313 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011314 D.getIdentifierLoc(),
11315 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000011316 if (Invalid)
11317 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000011318
Sebastian Redl4b07b292008-12-22 19:15:10 +000011319 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011320 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000011321 PushOnScopeChains(ExDecl, S);
11322 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011323 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000011324
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011325 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000011326 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011327}
Anders Carlssonfb311762009-03-14 00:25:26 +000011328
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011329Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000011330 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000011331 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011332 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000011333 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000011334
Richard Smithe3f470a2012-07-11 22:37:56 +000011335 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11336 return 0;
11337
11338 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11339 AssertMessage, RParenLoc, false);
11340}
11341
11342Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11343 Expr *AssertExpr,
11344 StringLiteral *AssertMessage,
11345 SourceLocation RParenLoc,
11346 bool Failed) {
11347 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11348 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000011349 // In a static_assert-declaration, the constant-expression shall be a
11350 // constant expression that can be contextually converted to bool.
11351 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11352 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011353 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000011354
Richard Smithdaaefc52011-12-14 23:32:26 +000011355 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000011356 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011357 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000011358 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011359 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000011360
Richard Smithe3f470a2012-07-11 22:37:56 +000011361 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011362 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000011363 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000011364 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011365 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000011366 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000011367 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000011368 }
Anders Carlssonc3082412009-03-14 00:33:21 +000011369 }
Mike Stump1eb44332009-09-09 15:08:12 +000011370
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011371 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000011372 AssertExpr, AssertMessage, RParenLoc,
11373 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000011374
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011375 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000011376 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000011377}
Sebastian Redl50de12f2009-03-24 22:27:57 +000011378
Douglas Gregor1d869352010-04-07 16:53:43 +000011379/// \brief Perform semantic analysis of the given friend type declaration.
11380///
11381/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000011382FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000011383 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011384 TypeSourceInfo *TSInfo) {
11385 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11386
11387 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000011388 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000011389
Richard Smith6b130222011-10-18 21:39:00 +000011390 // C++03 [class.friend]p2:
11391 // An elaborated-type-specifier shall be used in a friend declaration
11392 // for a class.*
11393 //
11394 // * The class-key of the elaborated-type-specifier is required.
11395 if (!ActiveTemplateInstantiations.empty()) {
11396 // Do not complain about the form of friend template types during
11397 // template instantiation; we will already have complained when the
11398 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011399 } else {
11400 if (!T->isElaboratedTypeSpecifier()) {
11401 // If we evaluated the type to a record type, suggest putting
11402 // a tag in front.
11403 if (const RecordType *RT = T->getAs<RecordType>()) {
11404 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000011405
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011406 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000011407
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011408 Diag(TypeRange.getBegin(),
11409 getLangOpts().CPlusPlus11 ?
11410 diag::warn_cxx98_compat_unelaborated_friend_type :
11411 diag::ext_unelaborated_friend_type)
11412 << (unsigned) RD->getTagKind()
11413 << T
11414 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11415 InsertionText);
11416 } else {
11417 Diag(FriendLoc,
11418 getLangOpts().CPlusPlus11 ?
11419 diag::warn_cxx98_compat_nonclass_type_friend :
11420 diag::ext_nonclass_type_friend)
11421 << T
11422 << TypeRange;
11423 }
11424 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000011425 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000011426 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011427 diag::warn_cxx98_compat_enum_friend :
11428 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000011429 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000011430 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000011431 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011432
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011433 // C++11 [class.friend]p3:
11434 // A friend declaration that does not declare a function shall have one
11435 // of the following forms:
11436 // friend elaborated-type-specifier ;
11437 // friend simple-type-specifier ;
11438 // friend typename-specifier ;
11439 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11440 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11441 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011442
Douglas Gregor06245bf2010-04-07 17:57:12 +000011443 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011444 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011445 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011446 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011447}
11448
John McCall9a34edb2010-10-19 01:40:49 +000011449/// Handle a friend tag declaration where the scope specifier was
11450/// templated.
11451Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11452 unsigned TagSpec, SourceLocation TagLoc,
11453 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011454 IdentifierInfo *Name,
11455 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011456 AttributeList *Attr,
11457 MultiTemplateParamsArg TempParamLists) {
11458 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11459
11460 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011461 bool Invalid = false;
11462
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011463 if (TemplateParameterList *TemplateParams =
11464 MatchTemplateParametersToScopeSpecifier(
11465 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11466 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011467 if (TemplateParams->size() > 0) {
11468 // This is a declaration of a class template.
11469 if (Invalid)
11470 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011471
Eric Christopher4110e132011-07-21 05:34:24 +000011472 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11473 SS, Name, NameLoc, Attr,
11474 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011475 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011476 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011477 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011478 } else {
11479 // The "template<>" header is extraneous.
11480 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11481 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11482 isExplicitSpecialization = true;
11483 }
11484 }
11485
11486 if (Invalid) return 0;
11487
John McCall9a34edb2010-10-19 01:40:49 +000011488 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011489 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011490 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011491 isAllExplicitSpecializations = false;
11492 break;
11493 }
11494 }
11495
11496 // FIXME: don't ignore attributes.
11497
11498 // If it's explicit specializations all the way down, just forget
11499 // about the template header and build an appropriate non-templated
11500 // friend. TODO: for source fidelity, remember the headers.
11501 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011502 if (SS.isEmpty()) {
11503 bool Owned = false;
11504 bool IsDependent = false;
11505 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11506 Attr, AS_public,
11507 /*ModulePrivateLoc=*/SourceLocation(),
11508 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011509 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011510 /*ScopedEnumUsesClassTag=*/false,
11511 /*UnderlyingType=*/TypeResult());
11512 }
11513
Douglas Gregor2494dd02011-03-01 01:34:45 +000011514 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011515 ElaboratedTypeKeyword Keyword
11516 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011517 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011518 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011519 if (T.isNull())
11520 return 0;
11521
11522 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11523 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011524 DependentNameTypeLoc TL =
11525 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011526 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011527 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011528 TL.setNameLoc(NameLoc);
11529 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011530 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011531 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011532 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011533 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011534 }
11535
11536 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011537 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011538 Friend->setAccess(AS_public);
11539 CurContext->addDecl(Friend);
11540 return Friend;
11541 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011542
11543 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11544
11545
John McCall9a34edb2010-10-19 01:40:49 +000011546
11547 // Handle the case of a templated-scope friend class. e.g.
11548 // template <class T> class A<T>::B;
11549 // FIXME: we don't support these right now.
11550 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11551 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11552 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011553 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011554 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011555 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011556 TL.setNameLoc(NameLoc);
11557
11558 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011559 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011560 Friend->setAccess(AS_public);
11561 Friend->setUnsupportedFriend(true);
11562 CurContext->addDecl(Friend);
11563 return Friend;
11564}
11565
11566
John McCalldd4a3b02009-09-16 22:47:08 +000011567/// Handle a friend type declaration. This works in tandem with
11568/// ActOnTag.
11569///
11570/// Notes on friend class templates:
11571///
11572/// We generally treat friend class declarations as if they were
11573/// declaring a class. So, for example, the elaborated type specifier
11574/// in a friend declaration is required to obey the restrictions of a
11575/// class-head (i.e. no typedefs in the scope chain), template
11576/// parameters are required to match up with simple template-ids, &c.
11577/// However, unlike when declaring a template specialization, it's
11578/// okay to refer to a template specialization without an empty
11579/// template parameter declaration, e.g.
11580/// friend class A<T>::B<unsigned>;
11581/// We permit this as a special case; if there are any template
11582/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011583/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011584Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011585 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011586 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011587
11588 assert(DS.isFriendSpecified());
11589 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11590
John McCalldd4a3b02009-09-16 22:47:08 +000011591 // Try to convert the decl specifier to a type. This works for
11592 // friend templates because ActOnTag never produces a ClassTemplateDecl
11593 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011594 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011595 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11596 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011597 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011598 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011599
Douglas Gregor6ccab972010-12-16 01:14:37 +000011600 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11601 return 0;
11602
John McCalldd4a3b02009-09-16 22:47:08 +000011603 // This is definitely an error in C++98. It's probably meant to
11604 // be forbidden in C++0x, too, but the specification is just
11605 // poorly written.
11606 //
11607 // The problem is with declarations like the following:
11608 // template <T> friend A<T>::foo;
11609 // where deciding whether a class C is a friend or not now hinges
11610 // on whether there exists an instantiation of A that causes
11611 // 'foo' to equal C. There are restrictions on class-heads
11612 // (which we declare (by fiat) elaborated friend declarations to
11613 // be) that makes this tractable.
11614 //
11615 // FIXME: handle "template <> friend class A<T>;", which
11616 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011617 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011618 Diag(Loc, diag::err_tagless_friend_type_template)
11619 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011620 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011621 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011622
John McCall02cace72009-08-28 07:59:38 +000011623 // C++98 [class.friend]p1: A friend of a class is a function
11624 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011625 // This is fixed in DR77, which just barely didn't make the C++03
11626 // deadline. It's also a very silly restriction that seriously
11627 // affects inner classes and which nobody else seems to implement;
11628 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011629 //
11630 // But note that we could warn about it: it's always useless to
11631 // friend one of your own members (it's not, however, worthless to
11632 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011633
John McCalldd4a3b02009-09-16 22:47:08 +000011634 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011635 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011636 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011637 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011638 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011639 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011640 DS.getFriendSpecLoc());
11641 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011642 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011643
11644 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011645 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011646
John McCalldd4a3b02009-09-16 22:47:08 +000011647 D->setAccess(AS_public);
11648 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011649
John McCalld226f652010-08-21 09:40:31 +000011650 return D;
John McCall02cace72009-08-28 07:59:38 +000011651}
11652
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011653NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11654 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011655 const DeclSpec &DS = D.getDeclSpec();
11656
11657 assert(DS.isFriendSpecified());
11658 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11659
11660 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011661 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011662
11663 // C++ [class.friend]p1
11664 // A friend of a class is a function or class....
11665 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011666 // It *doesn't* see through dependent types, which is correct
11667 // according to [temp.arg.type]p3:
11668 // If a declaration acquires a function type through a
11669 // type dependent on a template-parameter and this causes
11670 // a declaration that does not use the syntactic form of a
11671 // function declarator to have a function type, the program
11672 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011673 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011674 Diag(Loc, diag::err_unexpected_friend);
11675
11676 // It might be worthwhile to try to recover by creating an
11677 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011678 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011679 }
11680
11681 // C++ [namespace.memdef]p3
11682 // - If a friend declaration in a non-local class first declares a
11683 // class or function, the friend class or function is a member
11684 // of the innermost enclosing namespace.
11685 // - The name of the friend is not found by simple name lookup
11686 // until a matching declaration is provided in that namespace
11687 // scope (either before or after the class declaration granting
11688 // friendship).
11689 // - If a friend function is called, its name may be found by the
11690 // name lookup that considers functions from namespaces and
11691 // classes associated with the types of the function arguments.
11692 // - When looking for a prior declaration of a class or a function
11693 // declared as a friend, scopes outside the innermost enclosing
11694 // namespace scope are not considered.
11695
John McCall337ec3d2010-10-12 23:13:28 +000011696 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011697 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11698 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011699 assert(Name);
11700
Douglas Gregor6ccab972010-12-16 01:14:37 +000011701 // Check for unexpanded parameter packs.
11702 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11703 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11704 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11705 return 0;
11706
John McCall67d1a672009-08-06 02:15:43 +000011707 // The context we found the declaration in, or in which we should
11708 // create the declaration.
11709 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011710 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011711 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011712 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011713
Richard Smith4e9686b2013-08-09 04:35:01 +000011714 // There are five cases here.
11715 // - There's no scope specifier and we're in a local class. Only look
11716 // for functions declared in the immediately-enclosing block scope.
11717 // We recover from invalid scope qualifiers as if they just weren't there.
11718 FunctionDecl *FunctionContainingLocalClass = 0;
11719 if ((SS.isInvalid() || !SS.isSet()) &&
11720 (FunctionContainingLocalClass =
11721 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11722 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000011723 // If a friend declaration appears in a local class and the name
11724 // specified is an unqualified name, a prior declaration is
11725 // looked up without considering scopes that are outside the
11726 // innermost enclosing non-class scope. For a friend function
11727 // declaration, if there is no prior declaration, the program is
11728 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000011729
11730 // Find the innermost enclosing non-class scope. This is the block
11731 // scope containing the local class definition (or for a nested class,
11732 // the outer local class).
11733 DCScope = S->getFnParent();
11734
11735 // Look up the function name in the scope.
11736 Previous.clear(LookupLocalFriendName);
11737 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11738
11739 if (!Previous.empty()) {
11740 // All possible previous declarations must have the same context:
11741 // either they were declared at block scope or they are members of
11742 // one of the enclosing local classes.
11743 DC = Previous.getRepresentativeDecl()->getDeclContext();
11744 } else {
11745 // This is ill-formed, but provide the context that we would have
11746 // declared the function in, if we were permitted to, for error recovery.
11747 DC = FunctionContainingLocalClass;
11748 }
Richard Smitha41c97a2013-09-20 01:15:31 +000011749 adjustContextForLocalExternDecl(DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011750
11751 // C++ [class.friend]p6:
11752 // A function can be defined in a friend declaration of a class if and
11753 // only if the class is a non-local class (9.8), the function name is
11754 // unqualified, and the function has namespace scope.
11755 if (D.isFunctionDefinition()) {
11756 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11757 }
11758
11759 // - There's no scope specifier, in which case we just go to the
11760 // appropriate scope and look for a function or function template
11761 // there as appropriate.
11762 } else if (SS.isInvalid() || !SS.isSet()) {
11763 // C++11 [namespace.memdef]p3:
11764 // If the name in a friend declaration is neither qualified nor
11765 // a template-id and the declaration is a function or an
11766 // elaborated-type-specifier, the lookup to determine whether
11767 // the entity has been previously declared shall not consider
11768 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000011769 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011770
John McCall29ae6e52010-10-13 05:45:15 +000011771 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011772 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011773
Rafael Espindola11dc6342013-04-25 20:12:36 +000011774 // Skip class contexts. If someone can cite chapter and verse
11775 // for this behavior, that would be nice --- it's what GCC and
11776 // EDG do, and it seems like a reasonable intent, but the spec
11777 // really only says that checks for unqualified existing
11778 // declarations should stop at the nearest enclosing namespace,
11779 // not that they should only consider the nearest enclosing
11780 // namespace.
11781 while (DC->isRecord())
11782 DC = DC->getParent();
11783
11784 DeclContext *LookupDC = DC;
11785 while (LookupDC->isTransparentContext())
11786 LookupDC = LookupDC->getParent();
11787
11788 while (true) {
11789 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011790
Rafael Espindola11dc6342013-04-25 20:12:36 +000011791 if (!Previous.empty()) {
11792 DC = LookupDC;
11793 break;
John McCall8a407372010-10-14 22:22:28 +000011794 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011795
11796 if (isTemplateId) {
11797 if (isa<TranslationUnitDecl>(LookupDC)) break;
11798 } else {
11799 if (LookupDC->isFileContext()) break;
11800 }
11801 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011802 }
11803
John McCall380aaa42010-10-13 06:22:15 +000011804 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011805
John McCall337ec3d2010-10-12 23:13:28 +000011806 // - There's a non-dependent scope specifier, in which case we
11807 // compute it and do a previous lookup there for a function
11808 // or function template.
11809 } else if (!SS.getScopeRep()->isDependent()) {
11810 DC = computeDeclContext(SS);
11811 if (!DC) return 0;
11812
11813 if (RequireCompleteDeclContext(SS, DC)) return 0;
11814
11815 LookupQualifiedName(Previous, DC);
11816
11817 // Ignore things found implicitly in the wrong scope.
11818 // TODO: better diagnostics for this case. Suggesting the right
11819 // qualified scope would be nice...
11820 LookupResult::Filter F = Previous.makeFilter();
11821 while (F.hasNext()) {
11822 NamedDecl *D = F.next();
11823 if (!DC->InEnclosingNamespaceSetOf(
11824 D->getDeclContext()->getRedeclContext()))
11825 F.erase();
11826 }
11827 F.done();
11828
11829 if (Previous.empty()) {
11830 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011831 Diag(Loc, diag::err_qualified_friend_not_found)
11832 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011833 return 0;
11834 }
11835
11836 // C++ [class.friend]p1: A friend of a class is a function or
11837 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011838 if (DC->Equals(CurContext))
11839 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011840 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011841 diag::warn_cxx98_compat_friend_is_member :
11842 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011843
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011844 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011845 // C++ [class.friend]p6:
11846 // A function can be defined in a friend declaration of a class if and
11847 // only if the class is a non-local class (9.8), the function name is
11848 // unqualified, and the function has namespace scope.
11849 SemaDiagnosticBuilder DB
11850 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11851
11852 DB << SS.getScopeRep();
11853 if (DC->isFileContext())
11854 DB << FixItHint::CreateRemoval(SS.getRange());
11855 SS.clear();
11856 }
John McCall337ec3d2010-10-12 23:13:28 +000011857
11858 // - There's a scope specifier that does not match any template
11859 // parameter lists, in which case we use some arbitrary context,
11860 // create a method or method template, and wait for instantiation.
11861 // - There's a scope specifier that does match some template
11862 // parameter lists, which we don't handle right now.
11863 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011864 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011865 // C++ [class.friend]p6:
11866 // A function can be defined in a friend declaration of a class if and
11867 // only if the class is a non-local class (9.8), the function name is
11868 // unqualified, and the function has namespace scope.
11869 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11870 << SS.getScopeRep();
11871 }
11872
John McCall337ec3d2010-10-12 23:13:28 +000011873 DC = CurContext;
11874 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011875 }
Douglas Gregor883af832011-10-10 01:11:59 +000011876
John McCall29ae6e52010-10-13 05:45:15 +000011877 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011878 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011879 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11880 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11881 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011882 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011883 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11884 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011885 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011886 }
John McCall67d1a672009-08-06 02:15:43 +000011887 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011888
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011889 // FIXME: This is an egregious hack to cope with cases where the scope stack
11890 // does not contain the declaration context, i.e., in an out-of-line
11891 // definition of a class.
11892 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11893 if (!DCScope) {
11894 FakeDCScope.setEntity(DC);
11895 DCScope = &FakeDCScope;
11896 }
Richard Smith4e9686b2013-08-09 04:35:01 +000011897
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011898 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011899 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011900 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011901 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011902
Douglas Gregor182ddf02009-09-28 00:08:27 +000011903 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011904
Richard Smith4e9686b2013-08-09 04:35:01 +000011905 // If we performed typo correction, we might have added a scope specifier
11906 // and changed the decl context.
11907 DC = ND->getDeclContext();
11908
John McCallab88d972009-08-31 22:39:49 +000011909 // Add the function declaration to the appropriate lookup tables,
11910 // adjusting the redeclarations list as necessary. We don't
11911 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011912 //
John McCallab88d972009-08-31 22:39:49 +000011913 // Also update the scope-based lookup if the target context's
11914 // lookup context is in lexical scope.
11915 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011916 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011917 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011918 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011919 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011920 }
John McCall02cace72009-08-28 07:59:38 +000011921
11922 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011923 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011924 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011925 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011926 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011927
John McCall1f2e1a92012-08-10 03:15:35 +000011928 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011929 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011930 } else {
11931 if (DC->isRecord()) CheckFriendAccess(ND);
11932
John McCall6102ca12010-10-16 06:59:13 +000011933 FunctionDecl *FD;
11934 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11935 FD = FTD->getTemplatedDecl();
11936 else
11937 FD = cast<FunctionDecl>(ND);
11938
David Majnemerf6a144f2013-06-25 23:09:30 +000011939 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11940 // default argument expression, that declaration shall be a definition
11941 // and shall be the only declaration of the function or function
11942 // template in the translation unit.
11943 if (functionDeclHasDefaultArgument(FD)) {
11944 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11945 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11946 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11947 } else if (!D.isFunctionDefinition())
11948 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11949 }
11950
John McCall6102ca12010-10-16 06:59:13 +000011951 // Mark templated-scope function declarations as unsupported.
11952 if (FD->getNumTemplateParameterLists())
11953 FrD->setUnsupportedFriend(true);
11954 }
John McCall337ec3d2010-10-12 23:13:28 +000011955
John McCalld226f652010-08-21 09:40:31 +000011956 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011957}
11958
John McCalld226f652010-08-21 09:40:31 +000011959void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11960 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011961
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011962 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011963 if (!Fn) {
11964 Diag(DelLoc, diag::err_deleted_non_function);
11965 return;
11966 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011967
Douglas Gregoref96ee02012-01-14 16:38:05 +000011968 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011969 // Don't consider the implicit declaration we generate for explicit
11970 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011971 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11972 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011973 Diag(DelLoc, diag::err_deleted_decl_not_first);
11974 Diag(Prev->getLocation(), diag::note_previous_declaration);
11975 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011976 // If the declaration wasn't the first, we delete the function anyway for
11977 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011978 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011979 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011980
11981 if (Fn->isDeleted())
11982 return;
11983
11984 // See if we're deleting a function which is already known to override a
11985 // non-deleted virtual function.
11986 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11987 bool IssuedDiagnostic = false;
11988 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11989 E = MD->end_overridden_methods();
11990 I != E; ++I) {
11991 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11992 if (!IssuedDiagnostic) {
11993 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11994 IssuedDiagnostic = true;
11995 }
11996 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11997 }
11998 }
11999 }
12000
Sean Hunt10620eb2011-05-06 20:44:56 +000012001 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000012002}
Sebastian Redl13e88542009-04-27 21:33:24 +000012003
Sean Hunte4246a62011-05-12 06:15:49 +000012004void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000012005 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000012006
12007 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000012008 if (MD->getParent()->isDependentType()) {
12009 MD->setDefaulted();
12010 MD->setExplicitlyDefaulted();
12011 return;
12012 }
12013
Sean Hunte4246a62011-05-12 06:15:49 +000012014 CXXSpecialMember Member = getSpecialMember(MD);
12015 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000012016 if (!MD->isInvalidDecl())
12017 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000012018 return;
12019 }
12020
12021 MD->setDefaulted();
12022 MD->setExplicitlyDefaulted();
12023
Sean Huntcd10dec2011-05-23 23:14:04 +000012024 // If this definition appears within the record, do the checking when
12025 // the record is complete.
12026 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000012027 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000012028 // Find the uninstantiated declaration that actually had the '= default'
12029 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000012030 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000012031
Richard Smith12fef492013-03-27 00:22:47 +000012032 // If the method was defaulted on its first declaration, we will have
12033 // already performed the checking in CheckCompletedCXXClass. Such a
12034 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000012035 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000012036 return;
12037
Richard Smithb9d0b762012-07-27 04:22:15 +000012038 CheckExplicitlyDefaultedSpecialMember(MD);
12039
Richard Smith1d28caf2012-12-11 01:14:52 +000012040 // The exception specification is needed because we are defining the
12041 // function.
12042 ResolveExceptionSpec(DefaultLoc,
12043 MD->getType()->castAs<FunctionProtoType>());
12044
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012045 if (MD->isInvalidDecl())
12046 return;
12047
Sean Hunte4246a62011-05-12 06:15:49 +000012048 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012049 case CXXDefaultConstructor:
12050 DefineImplicitDefaultConstructor(DefaultLoc,
12051 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000012052 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012053 case CXXCopyConstructor:
12054 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000012055 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012056 case CXXCopyAssignment:
12057 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000012058 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012059 case CXXDestructor:
12060 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000012061 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012062 case CXXMoveConstructor:
12063 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000012064 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012065 case CXXMoveAssignment:
12066 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012067 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012068 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000012069 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000012070 }
12071 } else {
12072 Diag(DefaultLoc, diag::err_default_special_members);
12073 }
12074}
12075
Sebastian Redl13e88542009-04-27 21:33:24 +000012076static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000012077 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000012078 Stmt *SubStmt = *CI;
12079 if (!SubStmt)
12080 continue;
12081 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000012082 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000012083 diag::err_return_in_constructor_handler);
12084 if (!isa<Expr>(SubStmt))
12085 SearchForReturnInStmt(Self, SubStmt);
12086 }
12087}
12088
12089void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12090 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12091 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12092 SearchForReturnInStmt(*this, Handler);
12093 }
12094}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012095
David Blaikie299adab2013-01-18 23:03:15 +000012096bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000012097 const CXXMethodDecl *Old) {
12098 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12099 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12100
12101 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12102
12103 // If the calling conventions match, everything is fine
12104 if (NewCC == OldCC)
12105 return false;
12106
Reid Kleckneref072032013-08-27 23:08:25 +000012107 Diag(New->getLocation(),
12108 diag::err_conflicting_overriding_cc_attributes)
12109 << New->getDeclName() << New->getType() << Old->getType();
12110 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12111 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000012112}
12113
Mike Stump1eb44332009-09-09 15:08:12 +000012114bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012115 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000012116 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
12117 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012118
Chandler Carruth73857792010-02-15 11:53:20 +000012119 if (Context.hasSameType(NewTy, OldTy) ||
12120 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012121 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000012122
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012123 // Check if the return types are covariant
12124 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000012125
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012126 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012127 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12128 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012129 NewClassTy = NewPT->getPointeeType();
12130 OldClassTy = OldPT->getPointeeType();
12131 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012132 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12133 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12134 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12135 NewClassTy = NewRT->getPointeeType();
12136 OldClassTy = OldRT->getPointeeType();
12137 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012138 }
12139 }
Mike Stump1eb44332009-09-09 15:08:12 +000012140
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012141 // The return types aren't either both pointers or references to a class type.
12142 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000012143 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012144 diag::err_different_return_type_for_overriding_virtual_function)
12145 << New->getDeclName() << NewTy << OldTy;
12146 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000012147
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012148 return true;
12149 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012150
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012151 // C++ [class.virtual]p6:
12152 // If the return type of D::f differs from the return type of B::f, the
12153 // class type in the return type of D::f shall be complete at the point of
12154 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000012155 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12156 if (!RT->isBeingDefined() &&
12157 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000012158 diag::err_covariant_return_incomplete,
12159 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012160 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000012161 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012162
Douglas Gregora4923eb2009-11-16 21:35:15 +000012163 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012164 // Check if the new class derives from the old class.
12165 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12166 Diag(New->getLocation(),
12167 diag::err_covariant_return_not_derived)
12168 << New->getDeclName() << NewTy << OldTy;
12169 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12170 return true;
12171 }
Mike Stump1eb44332009-09-09 15:08:12 +000012172
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012173 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000012174 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000012175 diag::err_covariant_return_inaccessible_base,
12176 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12177 // FIXME: Should this point to the return type?
12178 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000012179 // FIXME: this note won't trigger for delayed access control
12180 // diagnostics, and it's impossible to get an undelayed error
12181 // here from access control during the original parse because
12182 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012183 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12184 return true;
12185 }
12186 }
Mike Stump1eb44332009-09-09 15:08:12 +000012187
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012188 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012189 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012190 Diag(New->getLocation(),
12191 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012192 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012193 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12194 return true;
12195 };
Mike Stump1eb44332009-09-09 15:08:12 +000012196
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012197
12198 // The new class type must have the same or less qualifiers as the old type.
12199 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12200 Diag(New->getLocation(),
12201 diag::err_covariant_return_type_class_type_more_qualified)
12202 << New->getDeclName() << NewTy << OldTy;
12203 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12204 return true;
12205 };
Mike Stump1eb44332009-09-09 15:08:12 +000012206
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012207 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012208}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012209
Douglas Gregor4ba31362009-12-01 17:24:26 +000012210/// \brief Mark the given method pure.
12211///
12212/// \param Method the method to be marked pure.
12213///
12214/// \param InitRange the source range that covers the "0" initializer.
12215bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000012216 SourceLocation EndLoc = InitRange.getEnd();
12217 if (EndLoc.isValid())
12218 Method->setRangeEnd(EndLoc);
12219
Douglas Gregor4ba31362009-12-01 17:24:26 +000012220 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12221 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000012222 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000012223 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000012224
12225 if (!Method->isInvalidDecl())
12226 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12227 << Method->getDeclName() << InitRange;
12228 return true;
12229}
12230
Douglas Gregor552e2992012-02-21 02:22:07 +000012231/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012232static bool isStaticDataMember(const Decl *D) {
12233 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12234 return Var->isStaticDataMember();
12235
12236 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000012237}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012238
John McCall731ad842009-12-19 09:28:58 +000012239/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12240/// an initializer for the out-of-line declaration 'Dcl'. The scope
12241/// is a fresh scope pushed for just this purpose.
12242///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012243/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12244/// static data member of class X, names should be looked up in the scope of
12245/// class X.
John McCalld226f652010-08-21 09:40:31 +000012246void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012247 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012248 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012249
John McCall731ad842009-12-19 09:28:58 +000012250 // We should only get called for declarations with scope specifiers, like:
12251 // int foo::bar;
12252 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012253 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000012254
12255 // If we are parsing the initializer for a static data member, push a
12256 // new expression evaluation context that is associated with this static
12257 // data member.
12258 if (isStaticDataMember(D))
12259 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012260}
12261
12262/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000012263/// initializer for the out-of-line declaration 'D'.
12264void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012265 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012266 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012267
Douglas Gregor552e2992012-02-21 02:22:07 +000012268 if (isStaticDataMember(D))
12269 PopExpressionEvaluationContext();
12270
John McCall731ad842009-12-19 09:28:58 +000012271 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012272 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012273}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012274
12275/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12276/// C++ if/switch/while/for statement.
12277/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000012278DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012279 // C++ 6.4p2:
12280 // The declarator shall not specify a function or an array.
12281 // The type-specifier-seq shall not contain typedef and shall not declare a
12282 // new class or enumeration.
12283 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12284 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012285
12286 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000012287 if (!Dcl)
12288 return true;
12289
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012290 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12291 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012292 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000012293 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012294 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012295
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012296 return Dcl;
12297}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012298
Douglas Gregordfe65432011-07-28 19:11:31 +000012299void Sema::LoadExternalVTableUses() {
12300 if (!ExternalSource)
12301 return;
12302
12303 SmallVector<ExternalVTableUse, 4> VTables;
12304 ExternalSource->ReadUsedVTables(VTables);
12305 SmallVector<VTableUse, 4> NewUses;
12306 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12307 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12308 = VTablesUsed.find(VTables[I].Record);
12309 // Even if a definition wasn't required before, it may be required now.
12310 if (Pos != VTablesUsed.end()) {
12311 if (!Pos->second && VTables[I].DefinitionRequired)
12312 Pos->second = true;
12313 continue;
12314 }
12315
12316 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12317 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12318 }
12319
12320 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12321}
12322
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012323void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12324 bool DefinitionRequired) {
12325 // Ignore any vtable uses in unevaluated operands or for classes that do
12326 // not have a vtable.
12327 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000012328 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000012329 return;
12330
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012331 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000012332 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012333 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12334 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12335 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12336 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000012337 // If we already had an entry, check to see if we are promoting this vtable
12338 // to required a definition. If so, we need to reappend to the VTableUses
12339 // list, since we may have already processed the first entry.
12340 if (DefinitionRequired && !Pos.first->second) {
12341 Pos.first->second = true;
12342 } else {
12343 // Otherwise, we can early exit.
12344 return;
12345 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012346 }
12347
12348 // Local classes need to have their virtual members marked
12349 // immediately. For all other classes, we mark their virtual members
12350 // at the end of the translation unit.
12351 if (Class->isLocalClass())
12352 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000012353 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012354 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000012355}
12356
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012357bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000012358 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012359 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000012360 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000012361
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012362 // Note: The VTableUses vector could grow as a result of marking
12363 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000012364 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012365 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000012366 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012367 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000012368 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012369 if (!Class)
12370 continue;
12371
12372 SourceLocation Loc = VTableUses[I].second;
12373
Richard Smithb9d0b762012-07-27 04:22:15 +000012374 bool DefineVTable = true;
12375
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012376 // If this class has a key function, but that key function is
12377 // defined in another translation unit, we don't need to emit the
12378 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000012379 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000012380 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000012381 // The key function is in another translation unit.
12382 DefineVTable = false;
12383 TemplateSpecializationKind TSK =
12384 KeyFunction->getTemplateSpecializationKind();
12385 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12386 TSK != TSK_ImplicitInstantiation &&
12387 "Instantiations don't have key functions");
12388 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012389 } else if (!KeyFunction) {
12390 // If we have a class with no key function that is the subject
12391 // of an explicit instantiation declaration, suppress the
12392 // vtable; it will live with the explicit instantiation
12393 // definition.
12394 bool IsExplicitInstantiationDeclaration
12395 = Class->getTemplateSpecializationKind()
12396 == TSK_ExplicitInstantiationDeclaration;
12397 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12398 REnd = Class->redecls_end();
12399 R != REnd; ++R) {
12400 TemplateSpecializationKind TSK
12401 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12402 if (TSK == TSK_ExplicitInstantiationDeclaration)
12403 IsExplicitInstantiationDeclaration = true;
12404 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12405 IsExplicitInstantiationDeclaration = false;
12406 break;
12407 }
12408 }
12409
12410 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000012411 DefineVTable = false;
12412 }
12413
12414 // The exception specifications for all virtual members may be needed even
12415 // if we are not providing an authoritative form of the vtable in this TU.
12416 // We may choose to emit it available_externally anyway.
12417 if (!DefineVTable) {
12418 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12419 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012420 }
12421
12422 // Mark all of the virtual members of this class as referenced, so
12423 // that we can build a vtable. Then, tell the AST consumer that a
12424 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012425 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012426 MarkVirtualMembersReferenced(Loc, Class);
12427 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12428 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12429
12430 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012431 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012432 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000012433 const FunctionDecl *KeyFunctionDef = 0;
12434 if (!KeyFunction ||
12435 (KeyFunction->hasBody(KeyFunctionDef) &&
12436 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012437 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12438 TSK_ExplicitInstantiationDefinition
12439 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12440 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012441 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012442 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012443 VTableUses.clear();
12444
Douglas Gregor78844032011-04-22 22:25:37 +000012445 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012446}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012447
Richard Smithb9d0b762012-07-27 04:22:15 +000012448void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12449 const CXXRecordDecl *RD) {
12450 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12451 E = RD->method_end(); I != E; ++I)
12452 if ((*I)->isVirtual() && !(*I)->isPure())
12453 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12454}
12455
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012456void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12457 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012458 // Mark all functions which will appear in RD's vtable as used.
12459 CXXFinalOverriderMap FinalOverriders;
12460 RD->getFinalOverriders(FinalOverriders);
12461 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12462 E = FinalOverriders.end();
12463 I != E; ++I) {
12464 for (OverridingMethods::const_iterator OI = I->second.begin(),
12465 OE = I->second.end();
12466 OI != OE; ++OI) {
12467 assert(OI->second.size() > 0 && "no final overrider");
12468 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012469
Richard Smithff817f72012-07-07 06:59:51 +000012470 // C++ [basic.def.odr]p2:
12471 // [...] A virtual member function is used if it is not pure. [...]
12472 if (!Overrider->isPure())
12473 MarkFunctionReferenced(Loc, Overrider);
12474 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012475 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012476
12477 // Only classes that have virtual bases need a VTT.
12478 if (RD->getNumVBases() == 0)
12479 return;
12480
12481 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12482 e = RD->bases_end(); i != e; ++i) {
12483 const CXXRecordDecl *Base =
12484 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012485 if (Base->getNumVBases() == 0)
12486 continue;
12487 MarkVirtualMembersReferenced(Loc, Base);
12488 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012489}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012490
12491/// SetIvarInitializers - This routine builds initialization ASTs for the
12492/// Objective-C implementation whose ivars need be initialized.
12493void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012494 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012495 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012496 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012497 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012498 CollectIvarsToConstructOrDestruct(OID, ivars);
12499 if (ivars.empty())
12500 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012501 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012502 for (unsigned i = 0; i < ivars.size(); i++) {
12503 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012504 if (Field->isInvalidDecl())
12505 continue;
12506
Sean Huntcbb67482011-01-08 20:30:50 +000012507 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012508 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12509 InitializationKind InitKind =
12510 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012511
12512 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12513 ExprResult MemberInit =
12514 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012515 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012516 // Note, MemberInit could actually come back empty if no initialization
12517 // is required (e.g., because it would call a trivial default constructor)
12518 if (!MemberInit.get() || MemberInit.isInvalid())
12519 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012520
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012521 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012522 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12523 SourceLocation(),
12524 MemberInit.takeAs<Expr>(),
12525 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012526 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012527
12528 // Be sure that the destructor is accessible and is marked as referenced.
12529 if (const RecordType *RecordTy
12530 = Context.getBaseElementType(Field->getType())
12531 ->getAs<RecordType>()) {
12532 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012533 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012534 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012535 CheckDestructorAccess(Field->getLocation(), Destructor,
12536 PDiag(diag::err_access_dtor_ivar)
12537 << Context.getBaseElementType(Field->getType()));
12538 }
12539 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012540 }
12541 ObjCImplementation->setIvarInitializers(Context,
12542 AllToInit.data(), AllToInit.size());
12543 }
12544}
Sean Huntfe57eef2011-05-04 05:57:24 +000012545
Sean Huntebcbe1d2011-05-04 23:29:54 +000012546static
12547void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12548 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12549 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12550 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12551 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012552 if (Ctor->isInvalidDecl())
12553 return;
12554
Richard Smitha8eaf002012-08-23 06:16:52 +000012555 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12556
12557 // Target may not be determinable yet, for instance if this is a dependent
12558 // call in an uninstantiated template.
12559 if (Target) {
12560 const FunctionDecl *FNTarget = 0;
12561 (void)Target->hasBody(FNTarget);
12562 Target = const_cast<CXXConstructorDecl*>(
12563 cast_or_null<CXXConstructorDecl>(FNTarget));
12564 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012565
12566 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12567 // Avoid dereferencing a null pointer here.
12568 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12569
12570 if (!Current.insert(Canonical))
12571 return;
12572
12573 // We know that beyond here, we aren't chaining into a cycle.
12574 if (!Target || !Target->isDelegatingConstructor() ||
12575 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012576 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012577 Current.clear();
12578 // We've hit a cycle.
12579 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12580 Current.count(TCanonical)) {
12581 // If we haven't diagnosed this cycle yet, do so now.
12582 if (!Invalid.count(TCanonical)) {
12583 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012584 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012585 << Ctor;
12586
Richard Smitha8eaf002012-08-23 06:16:52 +000012587 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012588 if (TCanonical != Canonical)
12589 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12590
12591 CXXConstructorDecl *C = Target;
12592 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012593 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012594 (void)C->getTargetConstructor()->hasBody(FNTarget);
12595 assert(FNTarget && "Ctor cycle through bodiless function");
12596
Richard Smitha8eaf002012-08-23 06:16:52 +000012597 C = const_cast<CXXConstructorDecl*>(
12598 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012599 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12600 }
12601 }
12602
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012603 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012604 Current.clear();
12605 } else {
12606 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12607 }
12608}
12609
12610
Sean Huntfe57eef2011-05-04 05:57:24 +000012611void Sema::CheckDelegatingCtorCycles() {
12612 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12613
Douglas Gregor0129b562011-07-27 21:57:17 +000012614 for (DelegatingCtorDeclsType::iterator
12615 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012616 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012617 I != E; ++I)
12618 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012619
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012620 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12621 CE = Invalid.end();
12622 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012623 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012624}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012625
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012626namespace {
12627 /// \brief AST visitor that finds references to the 'this' expression.
12628 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12629 Sema &S;
12630
12631 public:
12632 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12633
12634 bool VisitCXXThisExpr(CXXThisExpr *E) {
12635 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12636 << E->isImplicit();
12637 return false;
12638 }
12639 };
12640}
12641
12642bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12643 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12644 if (!TSInfo)
12645 return false;
12646
12647 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012648 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012649 if (!ProtoTL)
12650 return false;
12651
12652 // C++11 [expr.prim.general]p3:
12653 // [The expression this] shall not appear before the optional
12654 // cv-qualifier-seq and it shall not appear within the declaration of a
12655 // static member function (although its type and value category are defined
12656 // within a static member function as they are within a non-static member
12657 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012658 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012659 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012660 FindCXXThisExpr Finder(*this);
12661
12662 // If the return type came after the cv-qualifier-seq, check it now.
12663 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012664 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012665 return true;
12666
12667 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012668 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12669 return true;
12670
12671 return checkThisInStaticMemberFunctionAttributes(Method);
12672}
12673
12674bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12675 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12676 if (!TSInfo)
12677 return false;
12678
12679 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012680 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012681 if (!ProtoTL)
12682 return false;
12683
David Blaikie39e6ab42013-02-18 22:06:02 +000012684 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012685 FindCXXThisExpr Finder(*this);
12686
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012687 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012688 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012689 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012690 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012691 case EST_DynamicNone:
12692 case EST_MSAny:
12693 case EST_None:
12694 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012695
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012696 case EST_ComputedNoexcept:
12697 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12698 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012699
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012700 case EST_Dynamic:
12701 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012702 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012703 E != EEnd; ++E) {
12704 if (!Finder.TraverseType(*E))
12705 return true;
12706 }
12707 break;
12708 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012709
12710 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012711}
12712
12713bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12714 FindCXXThisExpr Finder(*this);
12715
12716 // Check attributes.
12717 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12718 A != AEnd; ++A) {
12719 // FIXME: This should be emitted by tblgen.
12720 Expr *Arg = 0;
12721 ArrayRef<Expr *> Args;
12722 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12723 Arg = G->getArg();
12724 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12725 Arg = G->getArg();
12726 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12727 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12728 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12729 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12730 else if (ExclusiveLockFunctionAttr *ELF
12731 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12732 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12733 else if (SharedLockFunctionAttr *SLF
12734 = dyn_cast<SharedLockFunctionAttr>(*A))
12735 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12736 else if (ExclusiveTrylockFunctionAttr *ETLF
12737 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12738 Arg = ETLF->getSuccessValue();
12739 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12740 } else if (SharedTrylockFunctionAttr *STLF
12741 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12742 Arg = STLF->getSuccessValue();
12743 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12744 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12745 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12746 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12747 Arg = LR->getArg();
12748 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12749 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12750 else if (ExclusiveLocksRequiredAttr *ELR
12751 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12752 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12753 else if (SharedLocksRequiredAttr *SLR
12754 = dyn_cast<SharedLocksRequiredAttr>(*A))
12755 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12756
12757 if (Arg && !Finder.TraverseStmt(Arg))
12758 return true;
12759
12760 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12761 if (!Finder.TraverseStmt(Args[I]))
12762 return true;
12763 }
12764 }
12765
12766 return false;
12767}
12768
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012769void
12770Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12771 ArrayRef<ParsedType> DynamicExceptions,
12772 ArrayRef<SourceRange> DynamicExceptionRanges,
12773 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012774 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012775 FunctionProtoType::ExtProtoInfo &EPI) {
12776 Exceptions.clear();
12777 EPI.ExceptionSpecType = EST;
12778 if (EST == EST_Dynamic) {
12779 Exceptions.reserve(DynamicExceptions.size());
12780 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12781 // FIXME: Preserve type source info.
12782 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12783
12784 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12785 collectUnexpandedParameterPacks(ET, Unexpanded);
12786 if (!Unexpanded.empty()) {
12787 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12788 UPPC_ExceptionType,
12789 Unexpanded);
12790 continue;
12791 }
12792
12793 // Check that the type is valid for an exception spec, and
12794 // drop it if not.
12795 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12796 Exceptions.push_back(ET);
12797 }
12798 EPI.NumExceptions = Exceptions.size();
12799 EPI.Exceptions = Exceptions.data();
12800 return;
12801 }
12802
12803 if (EST == EST_ComputedNoexcept) {
12804 // If an error occurred, there's no expression here.
12805 if (NoexceptExpr) {
12806 assert((NoexceptExpr->isTypeDependent() ||
12807 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12808 Context.BoolTy) &&
12809 "Parser should have made sure that the expression is boolean");
12810 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12811 EPI.ExceptionSpecType = EST_BasicNoexcept;
12812 return;
12813 }
12814
12815 if (!NoexceptExpr->isValueDependent())
12816 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012817 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012818 /*AllowFold*/ false).take();
12819 EPI.NoexceptExpr = NoexceptExpr;
12820 }
12821 return;
12822 }
12823}
12824
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012825/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12826Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12827 // Implicitly declared functions (e.g. copy constructors) are
12828 // __host__ __device__
12829 if (D->isImplicit())
12830 return CFT_HostDevice;
12831
12832 if (D->hasAttr<CUDAGlobalAttr>())
12833 return CFT_Global;
12834
12835 if (D->hasAttr<CUDADeviceAttr>()) {
12836 if (D->hasAttr<CUDAHostAttr>())
12837 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012838 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012839 }
12840
12841 return CFT_Host;
12842}
12843
12844bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12845 CUDAFunctionTarget CalleeTarget) {
12846 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12847 // Callable from the device only."
12848 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12849 return true;
12850
12851 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12852 // Callable from the host only."
12853 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12854 // Callable from the host only."
12855 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12856 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12857 return true;
12858
12859 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12860 return true;
12861
12862 return false;
12863}
John McCall76da55d2013-04-16 07:28:30 +000012864
12865/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12866///
12867MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12868 SourceLocation DeclStart,
12869 Declarator &D, Expr *BitWidth,
12870 InClassInitStyle InitStyle,
12871 AccessSpecifier AS,
12872 AttributeList *MSPropertyAttr) {
12873 IdentifierInfo *II = D.getIdentifier();
12874 if (!II) {
12875 Diag(DeclStart, diag::err_anonymous_property);
12876 return NULL;
12877 }
12878 SourceLocation Loc = D.getIdentifierLoc();
12879
12880 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12881 QualType T = TInfo->getType();
12882 if (getLangOpts().CPlusPlus) {
12883 CheckExtraCXXDefaultArguments(D);
12884
12885 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12886 UPPC_DataMemberType)) {
12887 D.setInvalidType();
12888 T = Context.IntTy;
12889 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12890 }
12891 }
12892
12893 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12894
12895 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12896 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12897 diag::err_invalid_thread)
12898 << DeclSpec::getSpecifierName(TSCS);
12899
12900 // Check to see if this name was declared as a member previously
12901 NamedDecl *PrevDecl = 0;
12902 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12903 LookupName(Previous, S);
12904 switch (Previous.getResultKind()) {
12905 case LookupResult::Found:
12906 case LookupResult::FoundUnresolvedValue:
12907 PrevDecl = Previous.getAsSingle<NamedDecl>();
12908 break;
12909
12910 case LookupResult::FoundOverloaded:
12911 PrevDecl = Previous.getRepresentativeDecl();
12912 break;
12913
12914 case LookupResult::NotFound:
12915 case LookupResult::NotFoundInCurrentInstantiation:
12916 case LookupResult::Ambiguous:
12917 break;
12918 }
12919
12920 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12921 // Maybe we will complain about the shadowed template parameter.
12922 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12923 // Just pretend that we didn't see the previous declaration.
12924 PrevDecl = 0;
12925 }
12926
12927 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12928 PrevDecl = 0;
12929
12930 SourceLocation TSSL = D.getLocStart();
12931 MSPropertyDecl *NewPD;
12932 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12933 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12934 II, T, TInfo, TSSL,
12935 Data.GetterId, Data.SetterId);
12936 ProcessDeclAttributes(TUScope, NewPD, D);
12937 NewPD->setAccess(AS);
12938
12939 if (NewPD->isInvalidDecl())
12940 Record->setInvalidDecl();
12941
12942 if (D.getDeclSpec().isModulePrivateSpecified())
12943 NewPD->setModulePrivate();
12944
12945 if (NewPD->isInvalidDecl() && PrevDecl) {
12946 // Don't introduce NewFD into scope; there's already something
12947 // with the same name in the same scope.
12948 } else if (II) {
12949 PushOnScopeChains(NewPD, S);
12950 } else
12951 Record->addDecl(NewPD);
12952
12953 return NewPD;
12954}