blob: 65705f5a559d2213b98e50e9cd06e91e7d650c6f [file] [log] [blame]
Chris Lattner199abbc2008-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 McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000030#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000031#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-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 Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000042#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000043#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner58258242008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattnerb0d38442008-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 Kramer337e3a52009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000061
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 public:
Mike Stump11289f42009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000065
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 };
Chris Lattner58258242008-04-10 02:22:51 +000072
Chris Lattnerb0d38442008-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 McCall8322c3a2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000079 }
80
Chris Lattnerb0d38442008-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 Gregor5251f1b2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-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 Dunbar62ee6412012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107
Douglas Gregor8e12c382008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110
Douglas Gregor97a9c812008-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 Dunbar62ee6412012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000119 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000120
John McCall7353c862013-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 Gregorf0d49512012-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 Lattner58258242008-04-10 02:22:51 +0000148}
149
Richard Smithb7151b92013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Alexis Hunt6d5b96c2011-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 Smithd3b5c9082012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith938f40b2011-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
Alexis Hunt6d5b96c2011-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 Smithf623c962012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-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.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000215 for (const auto &E : Proto->exceptions())
216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
217 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000218}
219
Richard Smith938f40b2011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithf623c962012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssonc80a1272009-08-25 02:29:20 +0000249bool
John McCallb268a282010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssonc80a1272009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000271 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000273
Richard Smithc406cb72013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Anders Carlssonc80a1272009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000279
Douglas Gregor758cb672010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000292 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000293}
294
Chris Lattner58258242008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000298void
John McCall48871652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000302 return;
Mike Stump11289f42009-09-09 15:08:12 +0000303
John McCall48871652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner199abbc2008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlssonf1c26952009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump11289f42009-09-09 15:08:12 +0000327
John McCallb268a282010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000329}
330
Douglas Gregor58354032008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump11289f42009-09-09 15:08:12 +0000340
John McCall48871652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000342 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000343 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000344}
345
Douglas Gregor4d87df52008-12-16 21:30:33 +0000346/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000348void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000349 if (!param)
350 return;
Mike Stump11289f42009-09-09 15:08:12 +0000351
John McCall48871652010-08-21 09:40:31 +0000352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000353 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000354 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000355}
356
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000357/// CheckExtraCXXDefaultArguments - Check for any extra default
358/// arguments in the declarator, which is not a function declaration
359/// or definition and therefore is not permitted to have default
360/// arguments. This routine should be invoked for every declarator
361/// that is not a function declaration or definition.
362void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
363 // C++ [dcl.fct.default]p3
364 // A default argument expression shall be specified only in the
365 // parameter-declaration-clause of a function declaration or in a
366 // template-parameter (14.1). It shall not be specified for a
367 // parameter pack. If it is specified in a
368 // parameter-declaration-clause, it shall not occur within a
369 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000370 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000371 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000372 DeclaratorChunk &chunk = D.getTypeObject(i);
373 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000374 if (MightBeFunction) {
375 // This is a function declaration. It can have default arguments, but
376 // keep looking in case its return type is a function type with default
377 // arguments.
378 MightBeFunction = false;
379 continue;
380 }
Alp Tokerc5350722014-02-26 22:27:52 +0000381 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
382 ++argIdx) {
383 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000384 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000385 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000386 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000387 << SourceRange((*Toks)[1].getLocation(),
388 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000389 delete Toks;
Alp Tokerc5350722014-02-26 22:27:52 +0000390 chunk.Fun.Params[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000391 } else if (Param->getDefaultArg()) {
392 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
393 << Param->getDefaultArg()->getSourceRange();
394 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000395 }
396 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000397 } else if (chunk.Kind != DeclaratorChunk::Paren) {
398 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000399 }
400 }
401}
402
David Majnemer502b0ed2013-06-25 23:09:30 +0000403static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
404 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
405 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
406 if (!PVD->hasDefaultArg())
407 return false;
408 if (!PVD->hasInheritedDefaultArg())
409 return true;
410 }
411 return false;
412}
413
Craig Toppere4794282012-09-21 04:33:26 +0000414/// MergeCXXFunctionDecl - Merge two declarations of the same C++
415/// function, once we already know that they have the same
416/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
417/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000418bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
419 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000420 bool Invalid = false;
421
Chris Lattner199abbc2008-04-08 05:04:30 +0000422 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000423 // For non-template functions, default arguments can be added in
424 // later declarations of a function in the same
425 // scope. Declarations in different scopes have completely
426 // distinct sets of default arguments. That is, declarations in
427 // inner scopes do not acquire default arguments from
428 // declarations in outer scopes, and vice versa. In a given
429 // function declaration, all parameters subsequent to a
430 // parameter with a default argument shall have default
431 // arguments supplied in this or previous declarations. A
432 // default argument shall not be redefined by a later
433 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000434 //
435 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000436 // Except for member functions of class templates, the default arguments
437 // in a member function definition that appears outside of the class
438 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000439 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000440 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
441 ParmVarDecl *OldParam = Old->getParamDecl(p);
442 ParmVarDecl *NewParam = New->getParamDecl(p);
443
James Molloye9430032012-03-13 08:55:35 +0000444 bool OldParamHasDfl = OldParam->hasDefaultArg();
445 bool NewParamHasDfl = NewParam->hasDefaultArg();
446
447 NamedDecl *ND = Old;
Richard Smith541b38b2013-09-20 01:15:31 +0000448
449 // The declaration context corresponding to the scope is the semantic
450 // parent, unless this is a local function declaration, in which case
451 // it is that surrounding function.
452 DeclContext *ScopeDC = New->getLexicalDeclContext();
453 if (!ScopeDC->isFunctionOrMethod())
454 ScopeDC = New->getDeclContext();
455 if (S && !isDeclInScope(ND, ScopeDC, S) &&
456 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000457 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000458 // the same scope and this is not an out-of-line definition of
459 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000460 OldParamHasDfl = false;
461
462 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000463
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000464 unsigned DiagDefaultParamID =
465 diag::err_param_default_argument_redefinition;
466
467 // MSVC accepts that default parameters be redefined for member functions
468 // of template class. The new default parameter's value is ignored.
469 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000470 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000471 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
472 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000473 // Merge the old default argument into the new parameter.
474 NewParam->setHasInheritedDefaultArg();
475 if (OldParam->hasUninstantiatedDefaultArg())
476 NewParam->setUninstantiatedDefaultArg(
477 OldParam->getUninstantiatedDefaultArg());
478 else
479 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000480 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000481 Invalid = false;
482 }
483 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000484
Francois Pichet8cb243a2011-04-10 04:58:30 +0000485 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
486 // hint here. Alternatively, we could walk the type-source information
487 // for NewParam to find the last source location in the type... but it
488 // isn't worth the effort right now. This is the kind of test case that
489 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000490 // int f(int);
491 // void g(int (*fp)(int) = f);
492 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000493 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000494 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000495
496 // Look for the function declaration where the default argument was
497 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000498 for (FunctionDecl *Older = Old->getPreviousDecl();
499 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000500 if (!Older->getParamDecl(p)->hasDefaultArg())
501 break;
502
503 OldParam = Older->getParamDecl(p);
504 }
505
506 Diag(OldParam->getLocation(), diag::note_previous_definition)
507 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000508 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000509 // Merge the old default argument into the new parameter.
510 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000511 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000512 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000513 if (OldParam->hasUninstantiatedDefaultArg())
514 NewParam->setUninstantiatedDefaultArg(
515 OldParam->getUninstantiatedDefaultArg());
516 else
John McCalle61b02b2010-05-04 01:53:42 +0000517 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000518 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000519 if (New->getDescribedFunctionTemplate()) {
520 // Paragraph 4, quoted above, only applies to non-template functions.
521 Diag(NewParam->getLocation(),
522 diag::err_param_default_argument_template_redecl)
523 << NewParam->getDefaultArgRange();
524 Diag(Old->getLocation(), diag::note_template_prev_declaration)
525 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000526 } else if (New->getTemplateSpecializationKind()
527 != TSK_ImplicitInstantiation &&
528 New->getTemplateSpecializationKind() != TSK_Undeclared) {
529 // C++ [temp.expr.spec]p21:
530 // Default function arguments shall not be specified in a declaration
531 // or a definition for one of the following explicit specializations:
532 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000533 // - the explicit specialization of a member function template;
534 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000535 // template where the class template specialization to which the
536 // member function specialization belongs is implicitly
537 // instantiated.
538 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
539 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
540 << New->getDeclName()
541 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000542 } else if (New->getDeclContext()->isDependentContext()) {
543 // C++ [dcl.fct.default]p6 (DR217):
544 // Default arguments for a member function of a class template shall
545 // be specified on the initial declaration of the member function
546 // within the class template.
547 //
548 // Reading the tea leaves a bit in DR217 and its reference to DR205
549 // leads me to the conclusion that one cannot add default function
550 // arguments for an out-of-line definition of a member function of a
551 // dependent type.
552 int WhichKind = 2;
553 if (CXXRecordDecl *Record
554 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
555 if (Record->getDescribedClassTemplate())
556 WhichKind = 0;
557 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
558 WhichKind = 1;
559 else
560 WhichKind = 2;
561 }
562
563 Diag(NewParam->getLocation(),
564 diag::err_param_default_argument_member_template_redecl)
565 << WhichKind
566 << NewParam->getDefaultArgRange();
567 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000568 }
569 }
570
Richard Smith58c3cc12012-11-28 03:45:24 +0000571 // DR1344: If a default argument is added outside a class definition and that
572 // default argument makes the function a special member function, the program
573 // is ill-formed. This can only happen for constructors.
574 if (isa<CXXConstructorDecl>(New) &&
575 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
576 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
577 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
578 if (NewSM != OldSM) {
579 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
580 assert(NewParam->hasDefaultArg());
581 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
582 << NewParam->getDefaultArgRange() << NewSM;
583 Diag(Old->getLocation(), diag::note_previous_declaration);
584 }
585 }
586
David Majnemeree4f4022014-03-30 06:44:54 +0000587 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000588 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000589 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000590 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000591 if (New->isConstexpr() != Old->isConstexpr()) {
592 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
593 << New << New->isConstexpr();
594 Diag(Old->getLocation(), diag::note_previous_declaration);
595 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000596 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
597 // C++11 [dcl.fcn.spec]p4:
598 // If the definition of a function appears in a translation unit before its
599 // first declaration as inline, the program is ill-formed.
600 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
601 Diag(Def->getLocation(), diag::note_previous_definition);
602 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000603 }
604
David Majnemer502b0ed2013-06-25 23:09:30 +0000605 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000606 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000607 // the only declaration of the function or function template in the
608 // translation unit.
609 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
610 functionDeclHasDefaultArgument(Old)) {
611 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
612 Diag(Old->getLocation(), diag::note_previous_declaration);
613 Invalid = true;
614 }
615
Douglas Gregorf40863c2010-02-12 07:32:17 +0000616 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000617 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000618
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000619 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000620}
621
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000622/// \brief Merge the exception specifications of two variable declarations.
623///
624/// This is called when there's a redeclaration of a VarDecl. The function
625/// checks if the redeclaration might have an exception specification and
626/// validates compatibility and merges the specs if necessary.
627void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
628 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000629 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000630 return;
631
632 assert(Context.hasSameType(New->getType(), Old->getType()) &&
633 "Should only be called if types are otherwise the same.");
634
635 QualType NewType = New->getType();
636 QualType OldType = Old->getType();
637
638 // We're only interested in pointers and references to functions, as well
639 // as pointers to member functions.
640 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
641 NewType = R->getPointeeType();
642 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
643 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
644 NewType = P->getPointeeType();
645 OldType = OldType->getAs<PointerType>()->getPointeeType();
646 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
647 NewType = M->getPointeeType();
648 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
649 }
650
651 if (!NewType->isFunctionProtoType())
652 return;
653
654 // There's lots of special cases for functions. For function pointers, system
655 // libraries are hopefully not as broken so that we don't need these
656 // workarounds.
657 if (CheckEquivalentExceptionSpec(
658 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
659 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
660 New->setInvalidDecl();
661 }
662}
663
Chris Lattner199abbc2008-04-08 05:04:30 +0000664/// CheckCXXDefaultArguments - Verify that the default arguments for a
665/// function declaration are well-formed according to C++
666/// [dcl.fct.default].
667void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
668 unsigned NumParams = FD->getNumParams();
669 unsigned p;
670
671 // Find first parameter with a default argument
672 for (p = 0; p < NumParams; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000674 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000675 break;
676 }
677
678 // C++ [dcl.fct.default]p4:
679 // In a given function declaration, all parameters
680 // subsequent to a parameter with a default argument shall
681 // have default arguments supplied in this or previous
682 // declarations. A default argument shall not be redefined
683 // by a later declaration (not even to the same value).
684 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000685 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000686 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000687 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000688 if (Param->isInvalidDecl())
689 /* We already complained about this parameter. */;
690 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000691 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000692 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000693 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000694 else
Mike Stump11289f42009-09-09 15:08:12 +0000695 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000696 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner199abbc2008-04-08 05:04:30 +0000698 LastMissingDefaultArg = p;
699 }
700 }
701
702 if (LastMissingDefaultArg > 0) {
703 // Some default arguments were missing. Clear out all of the
704 // default arguments up to (and including) the last missing
705 // default argument, so that we leave the function parameters
706 // in a semantically valid state.
707 for (p = 0; p <= LastMissingDefaultArg; ++p) {
708 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000709 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000710 Param->setDefaultArg(0);
711 }
712 }
713 }
714}
Douglas Gregor556877c2008-04-13 21:30:24 +0000715
Richard Smitheb3c10c2011-10-01 02:31:28 +0000716// CheckConstexprParameterTypes - Check whether a function's parameter types
717// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000718// diagnostic and return false.
719static bool CheckConstexprParameterTypes(Sema &SemaRef,
720 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000721 unsigned ArgIndex = 0;
722 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000723 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
724 e = FT->param_type_end();
725 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000726 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
727 SourceLocation ParamLoc = PD->getLocation();
728 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000729 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000730 diag::err_constexpr_non_literal_param,
731 ArgIndex+1, PD->getSourceRange(),
732 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000733 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000734 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000735 return true;
736}
737
738/// \brief Get diagnostic %select index for tag kind for
739/// record diagnostic message.
740/// WARNING: Indexes apply to particular diagnostics only!
741///
742/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000743static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000744 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000745 case TTK_Struct: return 0;
746 case TTK_Interface: return 1;
747 case TTK_Class: return 2;
748 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000749 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000750}
751
752// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
753// the requirements of a constexpr function definition or a constexpr
754// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000755// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000756//
Richard Smith3607ffe2012-02-13 03:54:03 +0000757// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
758bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000759 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
760 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000761 // C++11 [dcl.constexpr]p4:
762 // The definition of a constexpr constructor shall satisfy the following
763 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000764 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000765 const CXXRecordDecl *RD = MD->getParent();
766 if (RD->getNumVBases()) {
767 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
768 << isa<CXXConstructorDecl>(NewFD)
769 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000770 for (const auto &I : RD->vbases())
771 Diag(I.getLocStart(),
772 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000773 return false;
774 }
Richard Smith7971b692012-01-13 04:54:00 +0000775 }
776
777 if (!isa<CXXConstructorDecl>(NewFD)) {
778 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000779 // The definition of a constexpr function shall satisfy the following
780 // constraints:
781 // - it shall not be virtual;
782 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
783 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000784 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000785
Richard Smith3607ffe2012-02-13 03:54:03 +0000786 // If it's not obvious why this function is virtual, find an overridden
787 // function which uses the 'virtual' keyword.
788 const CXXMethodDecl *WrittenVirtual = Method;
789 while (!WrittenVirtual->isVirtualAsWritten())
790 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
791 if (WrittenVirtual != Method)
792 Diag(WrittenVirtual->getLocation(),
793 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000794 return false;
795 }
796
797 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000798 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000799 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000800 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000801 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000802 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000803 }
804
Richard Smith7971b692012-01-13 04:54:00 +0000805 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000806 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000807 return false;
808
Richard Smitheb3c10c2011-10-01 02:31:28 +0000809 return true;
810}
811
812/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000813/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000814///
Richard Smithd9f663b2013-04-22 15:31:51 +0000815/// \return true if the body is OK (maybe only as an extension), false if we
816/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000817static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000818 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
819 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000820 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
821 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000822 for (const auto *DclIt : DS->decls()) {
823 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000824 case Decl::StaticAssert:
825 case Decl::Using:
826 case Decl::UsingShadow:
827 case Decl::UsingDirective:
828 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000829 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000830 // - static_assert-declarations
831 // - using-declarations,
832 // - using-directives,
833 continue;
834
835 case Decl::Typedef:
836 case Decl::TypeAlias: {
837 // - typedef declarations and alias-declarations that do not define
838 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000839 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000840 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
841 // Don't allow variably-modified types in constexpr functions.
842 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
843 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
844 << TL.getSourceRange() << TL.getType()
845 << isa<CXXConstructorDecl>(Dcl);
846 return false;
847 }
848 continue;
849 }
850
851 case Decl::Enum:
852 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000853 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000854 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000855 SemaRef.Diag(DS->getLocStart(),
856 SemaRef.getLangOpts().CPlusPlus1y
857 ? diag::warn_cxx11_compat_constexpr_type_definition
858 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000859 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000860 continue;
861
Richard Smithd9f663b2013-04-22 15:31:51 +0000862 case Decl::EnumConstant:
863 case Decl::IndirectField:
864 case Decl::ParmVar:
865 // These can only appear with other declarations which are banned in
866 // C++11 and permitted in C++1y, so ignore them.
867 continue;
868
869 case Decl::Var: {
870 // C++1y [dcl.constexpr]p3 allows anything except:
871 // a definition of a variable of non-literal type or of static or
872 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000873 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000874 if (VD->isThisDeclarationADefinition()) {
875 if (VD->isStaticLocal()) {
876 SemaRef.Diag(VD->getLocation(),
877 diag::err_constexpr_local_var_static)
878 << isa<CXXConstructorDecl>(Dcl)
879 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
880 return false;
881 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000882 if (!VD->getType()->isDependentType() &&
883 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000884 VD->getLocation(), VD->getType(),
885 diag::err_constexpr_local_var_non_literal_type,
886 isa<CXXConstructorDecl>(Dcl)))
887 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000888 if (!VD->getType()->isDependentType() &&
889 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000890 SemaRef.Diag(VD->getLocation(),
891 diag::err_constexpr_local_var_no_init)
892 << isa<CXXConstructorDecl>(Dcl);
893 return false;
894 }
895 }
896 SemaRef.Diag(VD->getLocation(),
897 SemaRef.getLangOpts().CPlusPlus1y
898 ? diag::warn_cxx11_compat_constexpr_local_var
899 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000900 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000901 continue;
902 }
903
904 case Decl::NamespaceAlias:
905 case Decl::Function:
906 // These are disallowed in C++11 and permitted in C++1y. Allow them
907 // everywhere as an extension.
908 if (!Cxx1yLoc.isValid())
909 Cxx1yLoc = DS->getLocStart();
910 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000911
912 default:
913 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
914 << isa<CXXConstructorDecl>(Dcl);
915 return false;
916 }
917 }
918
919 return true;
920}
921
922/// Check that the given field is initialized within a constexpr constructor.
923///
924/// \param Dcl The constexpr constructor being checked.
925/// \param Field The field being checked. This may be a member of an anonymous
926/// struct or union nested within the class being checked.
927/// \param Inits All declarations, including anonymous struct/union members and
928/// indirect members, for which any initialization was provided.
929/// \param Diagnosed Set to true if an error is produced.
930static void CheckConstexprCtorInitializer(Sema &SemaRef,
931 const FunctionDecl *Dcl,
932 FieldDecl *Field,
933 llvm::SmallSet<Decl*, 16> &Inits,
934 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000935 if (Field->isInvalidDecl())
936 return;
937
Douglas Gregor556e5862011-10-10 17:22:13 +0000938 if (Field->isUnnamedBitfield())
939 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000940
Richard Smithab44d5b2013-12-10 08:25:00 +0000941 // Anonymous unions with no variant members and empty anonymous structs do not
942 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
943 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000944 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000945 (Field->getType()->isUnionType()
946 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
947 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000948 return;
949
Richard Smitheb3c10c2011-10-01 02:31:28 +0000950 if (!Inits.count(Field)) {
951 if (!Diagnosed) {
952 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
953 Diagnosed = true;
954 }
955 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
956 } else if (Field->isAnonymousStructOrUnion()) {
957 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000958 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000959 // If an anonymous union contains an anonymous struct of which any member
960 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000961 if (!RD->isUnion() || Inits.count(I))
962 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000963 }
964}
965
Richard Smithd9f663b2013-04-22 15:31:51 +0000966/// Check the provided statement is allowed in a constexpr function
967/// definition.
968static bool
969CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000970 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000971 SourceLocation &Cxx1yLoc) {
972 // - its function-body shall be [...] a compound-statement that contains only
973 switch (S->getStmtClass()) {
974 case Stmt::NullStmtClass:
975 // - null statements,
976 return true;
977
978 case Stmt::DeclStmtClass:
979 // - static_assert-declarations
980 // - using-declarations,
981 // - using-directives,
982 // - typedef declarations and alias-declarations that do not define
983 // classes or enumerations,
984 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
985 return false;
986 return true;
987
988 case Stmt::ReturnStmtClass:
989 // - and exactly one return statement;
990 if (isa<CXXConstructorDecl>(Dcl)) {
991 // C++1y allows return statements in constexpr constructors.
992 if (!Cxx1yLoc.isValid())
993 Cxx1yLoc = S->getLocStart();
994 return true;
995 }
996
997 ReturnStmts.push_back(S->getLocStart());
998 return true;
999
1000 case Stmt::CompoundStmtClass: {
1001 // C++1y allows compound-statements.
1002 if (!Cxx1yLoc.isValid())
1003 Cxx1yLoc = S->getLocStart();
1004
1005 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001006 for (auto *BodyIt : CompStmt->body()) {
1007 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001008 Cxx1yLoc))
1009 return false;
1010 }
1011 return true;
1012 }
1013
1014 case Stmt::AttributedStmtClass:
1015 if (!Cxx1yLoc.isValid())
1016 Cxx1yLoc = S->getLocStart();
1017 return true;
1018
1019 case Stmt::IfStmtClass: {
1020 // C++1y allows if-statements.
1021 if (!Cxx1yLoc.isValid())
1022 Cxx1yLoc = S->getLocStart();
1023
1024 IfStmt *If = cast<IfStmt>(S);
1025 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1026 Cxx1yLoc))
1027 return false;
1028 if (If->getElse() &&
1029 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1030 Cxx1yLoc))
1031 return false;
1032 return true;
1033 }
1034
1035 case Stmt::WhileStmtClass:
1036 case Stmt::DoStmtClass:
1037 case Stmt::ForStmtClass:
1038 case Stmt::CXXForRangeStmtClass:
1039 case Stmt::ContinueStmtClass:
1040 // C++1y allows all of these. We don't allow them as extensions in C++11,
1041 // because they don't make sense without variable mutation.
1042 if (!SemaRef.getLangOpts().CPlusPlus1y)
1043 break;
1044 if (!Cxx1yLoc.isValid())
1045 Cxx1yLoc = S->getLocStart();
1046 for (Stmt::child_range Children = S->children(); Children; ++Children)
1047 if (*Children &&
1048 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1049 Cxx1yLoc))
1050 return false;
1051 return true;
1052
1053 case Stmt::SwitchStmtClass:
1054 case Stmt::CaseStmtClass:
1055 case Stmt::DefaultStmtClass:
1056 case Stmt::BreakStmtClass:
1057 // C++1y allows switch-statements, and since they don't need variable
1058 // mutation, we can reasonably allow them in C++11 as an extension.
1059 if (!Cxx1yLoc.isValid())
1060 Cxx1yLoc = S->getLocStart();
1061 for (Stmt::child_range Children = S->children(); Children; ++Children)
1062 if (*Children &&
1063 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1064 Cxx1yLoc))
1065 return false;
1066 return true;
1067
1068 default:
1069 if (!isa<Expr>(S))
1070 break;
1071
1072 // C++1y allows expression-statements.
1073 if (!Cxx1yLoc.isValid())
1074 Cxx1yLoc = S->getLocStart();
1075 return true;
1076 }
1077
1078 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1079 << isa<CXXConstructorDecl>(Dcl);
1080 return false;
1081}
1082
Richard Smitheb3c10c2011-10-01 02:31:28 +00001083/// Check the body for the given constexpr function declaration only contains
1084/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1085///
1086/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001087bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001088 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001089 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001090 // The definition of a constexpr function shall satisfy the following
1091 // constraints: [...]
1092 // - its function-body shall be = delete, = default, or a
1093 // compound-statement
1094 //
Richard Smith74388b42012-02-04 00:33:54 +00001095 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001096 // In the definition of a constexpr constructor, [...]
1097 // - its function-body shall not be a function-try-block;
1098 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1099 << isa<CXXConstructorDecl>(Dcl);
1100 return false;
1101 }
1102
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001103 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001104
1105 // - its function-body shall be [...] a compound-statement that contains only
1106 // [... list of cases ...]
1107 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1108 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001109 for (auto *BodyIt : CompBody->body()) {
1110 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001111 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001112 }
1113
Richard Smithd9f663b2013-04-22 15:31:51 +00001114 if (Cxx1yLoc.isValid())
1115 Diag(Cxx1yLoc,
1116 getLangOpts().CPlusPlus1y
1117 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1118 : diag::ext_constexpr_body_invalid_stmt)
1119 << isa<CXXConstructorDecl>(Dcl);
1120
Richard Smitheb3c10c2011-10-01 02:31:28 +00001121 if (const CXXConstructorDecl *Constructor
1122 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1123 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001124 // DR1359:
1125 // - every non-variant non-static data member and base class sub-object
1126 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001127 // DR1460:
1128 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001129 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001130 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001131 if (Constructor->getNumCtorInitializers() == 0 &&
1132 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001133 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1134 return false;
1135 }
Richard Smithf368fb42011-10-10 16:38:04 +00001136 } else if (!Constructor->isDependentContext() &&
1137 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001138 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1139
1140 // Skip detailed checking if we have enough initializers, and we would
1141 // allow at most one initializer per member.
1142 bool AnyAnonStructUnionMembers = false;
1143 unsigned Fields = 0;
1144 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1145 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001146 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001147 AnyAnonStructUnionMembers = true;
1148 break;
1149 }
1150 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001151 // DR1460:
1152 // - if the class is a union-like class, but is not a union, for each of
1153 // its anonymous union members having variant members, exactly one of
1154 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001155 if (AnyAnonStructUnionMembers ||
1156 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1157 // Check initialization of non-static data members. Base classes are
1158 // always initialized so do not need to be checked. Dependent bases
1159 // might not have initializers in the member initializer list.
1160 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001161 for (const auto *I: Constructor->inits()) {
1162 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001163 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001164 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001165 Inits.insert(ID->chain_begin(), ID->chain_end());
1166 }
1167
1168 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001169 for (auto *I : RD->fields())
1170 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001171 if (Diagnosed)
1172 return false;
1173 }
1174 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001175 } else {
1176 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001177 // C++1y doesn't require constexpr functions to contain a 'return'
1178 // statement. We still do, unless the return type is void, because
1179 // otherwise if there's no return statement, the function cannot
1180 // be used in a core constant expression.
Alp Toker314cc812014-01-25 16:55:45 +00001181 bool OK = getLangOpts().CPlusPlus1y && Dcl->getReturnType()->isVoidType();
Richard Smithd9f663b2013-04-22 15:31:51 +00001182 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001183 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1184 : diag::err_constexpr_body_no_return);
1185 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001186 }
1187 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001188 Diag(ReturnStmts.back(),
1189 getLangOpts().CPlusPlus1y
1190 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1191 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001192 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1193 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001194 }
1195 }
1196
Richard Smith74388b42012-02-04 00:33:54 +00001197 // C++11 [dcl.constexpr]p5:
1198 // if no function argument values exist such that the function invocation
1199 // substitution would produce a constant expression, the program is
1200 // ill-formed; no diagnostic required.
1201 // C++11 [dcl.constexpr]p3:
1202 // - every constructor call and implicit conversion used in initializing the
1203 // return value shall be one of those allowed in a constant expression.
1204 // C++11 [dcl.constexpr]p4:
1205 // - every constructor involved in initializing non-static data members and
1206 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001207 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001208 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001209 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001210 << isa<CXXConstructorDecl>(Dcl);
1211 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1212 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001213 // Don't return false here: we allow this for compatibility in
1214 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001215 }
1216
Richard Smitheb3c10c2011-10-01 02:31:28 +00001217 return true;
1218}
1219
Douglas Gregor61956c42008-10-31 09:07:45 +00001220/// isCurrentClassName - Determine whether the identifier II is the
1221/// name of the class type currently being defined. In the case of
1222/// nested classes, this will only return true if II is the name of
1223/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001224bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1225 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001226 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001227
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001228 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001229 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001230 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001231 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1232 } else
1233 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1234
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001235 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001236 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001237 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001238}
1239
Richard Smithfb8b7b92013-10-15 00:00:26 +00001240/// \brief Determine whether the identifier II is a typo for the name of
1241/// the class type currently being defined. If so, update it to the identifier
1242/// that should have been used.
1243bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1244 assert(getLangOpts().CPlusPlus && "No class names in C!");
1245
1246 if (!getLangOpts().SpellChecking)
1247 return false;
1248
1249 CXXRecordDecl *CurDecl;
1250 if (SS && SS->isSet() && !SS->isInvalid()) {
1251 DeclContext *DC = computeDeclContext(*SS, true);
1252 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1253 } else
1254 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1255
1256 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1257 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1258 < II->getLength()) {
1259 II = CurDecl->getIdentifier();
1260 return true;
1261 }
1262
1263 return false;
1264}
1265
Douglas Gregordc974572012-11-10 07:24:09 +00001266/// \brief Determine whether the given class is a base class of the given
1267/// class, including looking at dependent bases.
1268static bool findCircularInheritance(const CXXRecordDecl *Class,
1269 const CXXRecordDecl *Current) {
1270 SmallVector<const CXXRecordDecl*, 8> Queue;
1271
1272 Class = Class->getCanonicalDecl();
1273 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001274 for (const auto &I : Current->bases()) {
1275 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001276 if (!Base)
1277 continue;
1278
1279 Base = Base->getDefinition();
1280 if (!Base)
1281 continue;
1282
1283 if (Base->getCanonicalDecl() == Class)
1284 return true;
1285
1286 Queue.push_back(Base);
1287 }
1288
1289 if (Queue.empty())
1290 return false;
1291
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001292 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001293 }
1294
1295 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001296}
1297
Mike Stump11289f42009-09-09 15:08:12 +00001298/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001299///
1300/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1301/// and returns NULL otherwise.
1302CXXBaseSpecifier *
1303Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1304 SourceRange SpecifierRange,
1305 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001306 TypeSourceInfo *TInfo,
1307 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001308 QualType BaseType = TInfo->getType();
1309
Douglas Gregor463421d2009-03-03 04:44:36 +00001310 // C++ [class.union]p1:
1311 // A union shall not have base classes.
1312 if (Class->isUnion()) {
1313 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1314 << SpecifierRange;
1315 return 0;
1316 }
1317
Douglas Gregor752a5952011-01-03 22:36:02 +00001318 if (EllipsisLoc.isValid() &&
1319 !TInfo->getType()->containsUnexpandedParameterPack()) {
1320 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1321 << TInfo->getTypeLoc().getSourceRange();
1322 EllipsisLoc = SourceLocation();
1323 }
Douglas Gregor62004702012-11-10 01:18:17 +00001324
1325 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1326
1327 if (BaseType->isDependentType()) {
1328 // Make sure that we don't have circular inheritance among our dependent
1329 // bases. For non-dependent bases, the check for completeness below handles
1330 // this.
1331 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1332 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1333 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001334 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001335 Diag(BaseLoc, diag::err_circular_inheritance)
1336 << BaseType << Context.getTypeDeclType(Class);
1337
1338 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1339 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1340 << BaseType;
1341
1342 return 0;
1343 }
1344 }
1345
Mike Stump11289f42009-09-09 15:08:12 +00001346 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001347 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001348 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001349 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001350
1351 // Base specifiers must be record types.
1352 if (!BaseType->isRecordType()) {
1353 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1354 return 0;
1355 }
1356
1357 // C++ [class.union]p1:
1358 // A union shall not be used as a base class.
1359 if (BaseType->isUnionType()) {
1360 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1361 return 0;
1362 }
1363
1364 // C++ [class.derived]p2:
1365 // The class-name in a base-specifier shall not be an incompletely
1366 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001367 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001368 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001369 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001370 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001371 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001372
Eli Friedmanc96d4962009-08-15 21:55:26 +00001373 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001374 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001375 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001376 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001377 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001378 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001379 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001380
David Majnemer9b1754d2013-11-02 12:00:36 +00001381 // A class which contains a flexible array member is not suitable for use as a
1382 // base class:
1383 // - If the layout determines that a base comes before another base,
1384 // the flexible array member would index into the subsequent base.
1385 // - If the layout determines that base comes before the derived class,
1386 // the flexible array member would index into the derived class.
1387 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1388 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1389 << CXXBaseDecl->getDeclName();
1390 return 0;
1391 }
1392
Anders Carlsson65c76d32011-03-25 14:55:14 +00001393 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001394 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001395 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001396 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001397 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001398 << CXXBaseDecl->getDeclName()
1399 << FA->isSpelledAsSealed();
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001400 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1401 << CXXBaseDecl->getDeclName();
1402 return 0;
1403 }
1404
John McCall3696dcb2010-08-17 07:23:57 +00001405 if (BaseDecl->isInvalidDecl())
1406 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001407
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001408 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001409 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001410 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001411 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001412}
1413
Douglas Gregor556877c2008-04-13 21:30:24 +00001414/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1415/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001416/// example:
1417/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001418/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001419BaseResult
John McCall48871652010-08-21 09:40:31 +00001420Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001421 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001422 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001423 ParsedType basetype, SourceLocation BaseLoc,
1424 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001425 if (!classdecl)
1426 return true;
1427
Douglas Gregorc40290e2009-03-09 23:48:35 +00001428 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001429 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001430 if (!Class)
1431 return true;
1432
Richard Smith4c96e992013-02-19 23:47:15 +00001433 // We do not support any C++11 attributes on base-specifiers yet.
1434 // Diagnose any attributes we see.
1435 if (!Attributes.empty()) {
1436 for (AttributeList *Attr = Attributes.getList(); Attr;
1437 Attr = Attr->getNext()) {
1438 if (Attr->isInvalid() ||
1439 Attr->getKind() == AttributeList::IgnoredAttribute)
1440 continue;
1441 Diag(Attr->getLoc(),
1442 Attr->getKind() == AttributeList::UnknownAttribute
1443 ? diag::warn_unknown_attribute_ignored
1444 : diag::err_base_specifier_attribute)
1445 << Attr->getName();
1446 }
1447 }
1448
Nick Lewycky19b9f952010-07-26 16:56:01 +00001449 TypeSourceInfo *TInfo = 0;
1450 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001451
Douglas Gregor752a5952011-01-03 22:36:02 +00001452 if (EllipsisLoc.isInvalid() &&
1453 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001454 UPPC_BaseType))
1455 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001456
Douglas Gregor463421d2009-03-03 04:44:36 +00001457 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001458 Virtual, Access, TInfo,
1459 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001460 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001461 else
1462 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001463
Douglas Gregor463421d2009-03-03 04:44:36 +00001464 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001465}
Douglas Gregor556877c2008-04-13 21:30:24 +00001466
Douglas Gregor463421d2009-03-03 04:44:36 +00001467/// \brief Performs the actual work of attaching the given base class
1468/// specifiers to a C++ class.
1469bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1470 unsigned NumBases) {
1471 if (NumBases == 0)
1472 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001473
1474 // Used to keep track of which base types we have already seen, so
1475 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001476 // that the key is always the unqualified canonical type of the base
1477 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001478 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1479
1480 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001481 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001482 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001483 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001484 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001485 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001486 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001487
1488 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1489 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001490 // C++ [class.mi]p3:
1491 // A class shall not be specified as a direct base class of a
1492 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001493 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001494 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001495 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001496 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001497
1498 // Delete the duplicate base class specifier; we're going to
1499 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001500 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001501
1502 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001503 } else {
1504 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001505 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001506 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001507 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1508 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1509 if (Class->isInterface() &&
1510 (!RD->isInterface() ||
1511 KnownBase->getAccessSpecifier() != AS_public)) {
1512 // The Microsoft extension __interface does not permit bases that
1513 // are not themselves public interfaces.
1514 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1515 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1516 << RD->getSourceRange();
1517 Invalid = true;
1518 }
1519 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001520 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001521 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001522 }
1523 }
1524
1525 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001526 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001527
1528 // Delete the remaining (good) base class specifiers, since their
1529 // data has been copied into the CXXRecordDecl.
1530 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001531 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001532
1533 return Invalid;
1534}
1535
1536/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1537/// class, after checking whether there are any duplicate base
1538/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001539void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001540 unsigned NumBases) {
1541 if (!ClassDecl || !Bases || !NumBases)
1542 return;
1543
1544 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001545 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001546}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001547
Douglas Gregor36d1b142009-10-06 17:59:45 +00001548/// \brief Determine whether the type \p Derived is a C++ class that is
1549/// derived from the type \p Base.
1550bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001551 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001552 return false;
John McCalle78aac42010-03-10 03:28:59 +00001553
Douglas Gregor45bb4832013-03-26 23:36:30 +00001554 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001555 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001556 return false;
1557
Douglas Gregor45bb4832013-03-26 23:36:30 +00001558 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001559 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001560 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001561
1562 // If either the base or the derived type is invalid, don't try to
1563 // check whether one is derived from the other.
1564 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1565 return false;
1566
John McCall67da35c2010-02-04 22:26:26 +00001567 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1568 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001569}
1570
1571/// \brief Determine whether the type \p Derived is a C++ class that is
1572/// derived from the type \p Base.
1573bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001574 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001575 return false;
1576
Douglas Gregor45bb4832013-03-26 23:36:30 +00001577 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001578 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001579 return false;
1580
Douglas Gregor45bb4832013-03-26 23:36:30 +00001581 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001582 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001583 return false;
1584
Douglas Gregor36d1b142009-10-06 17:59:45 +00001585 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1586}
1587
Anders Carlssona70cff62010-04-24 19:06:50 +00001588void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001589 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001590 assert(BasePathArray.empty() && "Base path array must be empty!");
1591 assert(Paths.isRecordingPaths() && "Must record paths!");
1592
1593 const CXXBasePath &Path = Paths.front();
1594
1595 // We first go backward and check if we have a virtual base.
1596 // FIXME: It would be better if CXXBasePath had the base specifier for
1597 // the nearest virtual base.
1598 unsigned Start = 0;
1599 for (unsigned I = Path.size(); I != 0; --I) {
1600 if (Path[I - 1].Base->isVirtual()) {
1601 Start = I - 1;
1602 break;
1603 }
1604 }
1605
1606 // Now add all bases.
1607 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001608 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001609}
1610
Douglas Gregor88d292c2010-05-13 16:44:06 +00001611/// \brief Determine whether the given base path includes a virtual
1612/// base class.
John McCallcf142162010-08-07 06:22:56 +00001613bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1614 for (CXXCastPath::const_iterator B = BasePath.begin(),
1615 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001616 B != BEnd; ++B)
1617 if ((*B)->isVirtual())
1618 return true;
1619
1620 return false;
1621}
1622
Douglas Gregor36d1b142009-10-06 17:59:45 +00001623/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1624/// conversion (where Derived and Base are class types) is
1625/// well-formed, meaning that the conversion is unambiguous (and
1626/// that all of the base classes are accessible). Returns true
1627/// and emits a diagnostic if the code is ill-formed, returns false
1628/// otherwise. Loc is the location where this routine should point to
1629/// if there is an error, and Range is the source range to highlight
1630/// if there is an error.
1631bool
1632Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001633 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001634 unsigned AmbigiousBaseConvID,
1635 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001636 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001637 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001638 // First, determine whether the path from Derived to Base is
1639 // ambiguous. This is slightly more expensive than checking whether
1640 // the Derived to Base conversion exists, because here we need to
1641 // explore multiple paths to determine if there is an ambiguity.
1642 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1643 /*DetectVirtual=*/false);
1644 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1645 assert(DerivationOkay &&
1646 "Can only be used with a derived-to-base conversion");
1647 (void)DerivationOkay;
1648
1649 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001650 if (InaccessibleBaseID) {
1651 // Check that the base class can be accessed.
1652 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1653 InaccessibleBaseID)) {
1654 case AR_inaccessible:
1655 return true;
1656 case AR_accessible:
1657 case AR_dependent:
1658 case AR_delayed:
1659 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001660 }
John McCall5b0829a2010-02-10 09:31:12 +00001661 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001662
1663 // Build a base path if necessary.
1664 if (BasePath)
1665 BuildBasePathArray(Paths, *BasePath);
1666 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001667 }
1668
David Majnemer626032f2013-06-22 06:43:58 +00001669 if (AmbigiousBaseConvID) {
1670 // We know that the derived-to-base conversion is ambiguous, and
1671 // we're going to produce a diagnostic. Perform the derived-to-base
1672 // search just one more time to compute all of the possible paths so
1673 // that we can print them out. This is more expensive than any of
1674 // the previous derived-to-base checks we've done, but at this point
1675 // performance isn't as much of an issue.
1676 Paths.clear();
1677 Paths.setRecordingPaths(true);
1678 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1679 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1680 (void)StillOkay;
1681
1682 // Build up a textual representation of the ambiguous paths, e.g.,
1683 // D -> B -> A, that will be used to illustrate the ambiguous
1684 // conversions in the diagnostic. We only print one of the paths
1685 // to each base class subobject.
1686 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1687
1688 Diag(Loc, AmbigiousBaseConvID)
1689 << Derived << Base << PathDisplayStr << Range << Name;
1690 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001691 return true;
1692}
1693
1694bool
1695Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001696 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001697 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001698 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001699 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001700 IgnoreAccess ? 0
1701 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001702 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001703 Loc, Range, DeclarationName(),
1704 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001705}
1706
1707
1708/// @brief Builds a string representing ambiguous paths from a
1709/// specific derived class to different subobjects of the same base
1710/// class.
1711///
1712/// This function builds a string that can be used in error messages
1713/// to show the different paths that one can take through the
1714/// inheritance hierarchy to go from the derived class to different
1715/// subobjects of a base class. The result looks something like this:
1716/// @code
1717/// struct D -> struct B -> struct A
1718/// struct D -> struct C -> struct A
1719/// @endcode
1720std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1721 std::string PathDisplayStr;
1722 std::set<unsigned> DisplayedPaths;
1723 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1724 Path != Paths.end(); ++Path) {
1725 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1726 // We haven't displayed a path to this particular base
1727 // class subobject yet.
1728 PathDisplayStr += "\n ";
1729 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1730 for (CXXBasePath::const_iterator Element = Path->begin();
1731 Element != Path->end(); ++Element)
1732 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1733 }
1734 }
1735
1736 return PathDisplayStr;
1737}
1738
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001739//===----------------------------------------------------------------------===//
1740// C++ class member Handling
1741//===----------------------------------------------------------------------===//
1742
Abramo Bagnarad7340582010-06-05 05:09:32 +00001743/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001744bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1745 SourceLocation ASLoc,
1746 SourceLocation ColonLoc,
1747 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001748 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001749 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001750 ASLoc, ColonLoc);
1751 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001752 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001753}
1754
Richard Smith18f07db2012-08-06 03:25:17 +00001755/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001756void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001757 if (D->isInvalidDecl())
1758 return;
1759
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001760 // We only care about "override" and "final" declarations.
1761 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1762 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001763
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001764 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001765
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001766 // We can't check dependent instance methods.
1767 if (MD && MD->isInstance() &&
1768 (MD->getParent()->hasAnyDependentBases() ||
1769 MD->getType()->isDependentType()))
1770 return;
1771
1772 if (MD && !MD->isVirtual()) {
1773 // If we have a non-virtual method, check if if hides a virtual method.
1774 // (In that case, it's most likely the method has the wrong type.)
1775 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1776 FindHiddenVirtualMethods(MD, OverloadedMethods);
1777
1778 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001779 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1780 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001781 diag::override_keyword_hides_virtual_member_function)
1782 << "override" << (OverloadedMethods.size() > 1);
1783 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001784 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001785 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001786 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1787 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001788 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001789 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1790 MD->setInvalidDecl();
1791 return;
1792 }
1793 // Fall through into the general case diagnostic.
1794 // FIXME: We might want to attempt typo correction here.
1795 }
1796
1797 if (!MD || !MD->isVirtual()) {
1798 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1799 Diag(OA->getLocation(),
1800 diag::override_keyword_only_allowed_on_virtual_member_functions)
1801 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1802 D->dropAttr<OverrideAttr>();
1803 }
1804 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1805 Diag(FA->getLocation(),
1806 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001807 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1808 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001809 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001810 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001811 return;
1812 }
Richard Smith18f07db2012-08-06 03:25:17 +00001813
Richard Smith18f07db2012-08-06 03:25:17 +00001814 // C++11 [class.virtual]p5:
1815 // If a virtual function is marked with the virt-specifier override and
1816 // does not override a member function of a base class, the program is
1817 // ill-formed.
1818 bool HasOverriddenMethods =
1819 MD->begin_overridden_methods() != MD->end_overridden_methods();
1820 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1821 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1822 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001823}
1824
Richard Smith18f07db2012-08-06 03:25:17 +00001825/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001826/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001827/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001828bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1829 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001830 FinalAttr *FA = Old->getAttr<FinalAttr>();
1831 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001832 return false;
1833
1834 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001835 << New->getDeclName()
1836 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001837 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1838 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001839}
1840
Daniel Jasper0baec5492012-06-06 08:32:04 +00001841static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001842 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1843 // FIXME: Destruction of ObjC lifetime types has side-effects.
1844 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1845 return !RD->isCompleteDefinition() ||
1846 !RD->hasTrivialDefaultConstructor() ||
1847 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001848 return false;
1849}
1850
John McCall5e77d762013-04-16 07:28:30 +00001851static AttributeList *getMSPropertyAttr(AttributeList *list) {
1852 for (AttributeList* it = list; it != 0; it = it->getNext())
1853 if (it->isDeclspecPropertyAttribute())
1854 return it;
1855 return 0;
1856}
1857
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001858/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1859/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001860/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001861/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1862/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001863NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001864Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001865 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001866 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001867 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001868 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001869 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1870 DeclarationName Name = NameInfo.getName();
1871 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001872
1873 // For anonymous bitfields, the location should point to the type.
1874 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001875 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001876
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001877 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001878
John McCallb1cd7da2010-06-04 08:34:12 +00001879 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001880 assert(!DS.isFriendSpecified());
1881
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001882 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001883
John McCalldb632ac2012-09-25 07:32:39 +00001884 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1885 // The Microsoft extension __interface only permits public member functions
1886 // and prohibits constructors, destructors, operators, non-public member
1887 // functions, static methods and data members.
1888 unsigned InvalidDecl;
1889 bool ShowDeclName = true;
1890 if (!isFunc)
1891 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1892 else if (AS != AS_public)
1893 InvalidDecl = 2;
1894 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1895 InvalidDecl = 3;
1896 else switch (Name.getNameKind()) {
1897 case DeclarationName::CXXConstructorName:
1898 InvalidDecl = 4;
1899 ShowDeclName = false;
1900 break;
1901
1902 case DeclarationName::CXXDestructorName:
1903 InvalidDecl = 5;
1904 ShowDeclName = false;
1905 break;
1906
1907 case DeclarationName::CXXOperatorName:
1908 case DeclarationName::CXXConversionFunctionName:
1909 InvalidDecl = 6;
1910 break;
1911
1912 default:
1913 InvalidDecl = 0;
1914 break;
1915 }
1916
1917 if (InvalidDecl) {
1918 if (ShowDeclName)
1919 Diag(Loc, diag::err_invalid_member_in_interface)
1920 << (InvalidDecl-1) << Name;
1921 else
1922 Diag(Loc, diag::err_invalid_member_in_interface)
1923 << (InvalidDecl-1) << "";
1924 return 0;
1925 }
1926 }
1927
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001928 // C++ 9.2p6: A member shall not be declared to have automatic storage
1929 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001930 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1931 // data members and cannot be applied to names declared const or static,
1932 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001933 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001934 case DeclSpec::SCS_unspecified:
1935 case DeclSpec::SCS_typedef:
1936 case DeclSpec::SCS_static:
1937 break;
1938 case DeclSpec::SCS_mutable:
1939 if (isFunc) {
1940 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001941
Richard Smithb4a9e862013-04-12 22:46:28 +00001942 // FIXME: It would be nicer if the keyword was ignored only for this
1943 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001944 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001945 }
1946 break;
1947 default:
1948 Diag(DS.getStorageClassSpecLoc(),
1949 diag::err_storageclass_invalid_for_member);
1950 D.getMutableDeclSpec().ClearStorageClassSpecs();
1951 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001952 }
1953
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001954 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1955 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001956 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001957
David Blaikie35506f82013-01-30 01:22:18 +00001958 if (DS.isConstexprSpecified() && isInstField) {
1959 SemaDiagnosticBuilder B =
1960 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1961 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1962 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00001963 B << 0 << 0;
1964 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
1965 B << FixItHint::CreateRemoval(ConstexprLoc);
1966 else {
1967 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
1968 D.getMutableDeclSpec().ClearConstexprSpec();
1969 const char *PrevSpec;
1970 unsigned DiagID;
1971 bool Failed = D.getMutableDeclSpec().SetTypeQual(
1972 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
1973 (void)Failed;
1974 assert(!Failed && "Making a constexpr member const shouldn't fail");
1975 }
David Blaikie35506f82013-01-30 01:22:18 +00001976 } else {
1977 B << 1;
1978 const char *PrevSpec;
1979 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001980 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001981 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1982 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001983 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001984 "This is the only DeclSpec that should fail to be applied");
1985 B << 1;
1986 } else {
1987 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1988 isInstField = false;
1989 }
1990 }
1991 }
1992
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001993 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001994 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001995 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001996
1997 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00001998 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001999 Diag(Loc, diag::err_bad_variable_name)
2000 << Name;
2001 return 0;
2002 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002003
Benjamin Kramer365082d2012-05-19 16:34:46 +00002004 IdentifierInfo *II = Name.getAsIdentifierInfo();
2005
Douglas Gregor7c26c042011-09-21 14:40:46 +00002006 // Member field could not be with "template" keyword.
2007 // So TemplateParameterLists should be empty in this case.
2008 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002009 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002010 if (TemplateParams->size()) {
2011 // There is no such thing as a member field template.
2012 Diag(D.getIdentifierLoc(), diag::err_template_member)
2013 << II
2014 << SourceRange(TemplateParams->getTemplateLoc(),
2015 TemplateParams->getRAngleLoc());
2016 } else {
2017 // There is an extraneous 'template<>' for this member.
2018 Diag(TemplateParams->getTemplateLoc(),
2019 diag::err_template_member_noparams)
2020 << II
2021 << SourceRange(TemplateParams->getTemplateLoc(),
2022 TemplateParams->getRAngleLoc());
2023 }
2024 return 0;
2025 }
2026
Douglas Gregora007d362010-10-13 22:19:53 +00002027 if (SS.isSet() && !SS.isInvalid()) {
2028 // The user provided a superfluous scope specifier inside a class
2029 // definition:
2030 //
2031 // class X {
2032 // int X::member;
2033 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002034 if (DeclContext *DC = computeDeclContext(SS, false))
2035 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002036 else
2037 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2038 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002039
Douglas Gregora007d362010-10-13 22:19:53 +00002040 SS.clear();
2041 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002042
John McCall5e77d762013-04-16 07:28:30 +00002043 AttributeList *MSPropertyAttr =
2044 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002045 if (MSPropertyAttr) {
2046 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2047 BitWidth, InitStyle, AS, MSPropertyAttr);
2048 if (!Member)
2049 return 0;
2050 isInstField = false;
2051 } else {
2052 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2053 BitWidth, InitStyle, AS);
2054 assert(Member && "HandleField never returns null");
2055 }
2056 } else {
2057 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2058
2059 Member = HandleDeclarator(S, D, TemplateParameterLists);
2060 if (!Member)
2061 return 0;
2062
2063 // Non-instance-fields can't have a bitfield.
2064 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002065 if (Member->isInvalidDecl()) {
2066 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002067 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002068 // C++ 9.6p3: A bit-field shall not be a static member.
2069 // "static member 'A' cannot be a bit-field"
2070 Diag(Loc, diag::err_static_not_bitfield)
2071 << Name << BitWidth->getSourceRange();
2072 } else if (isa<TypedefDecl>(Member)) {
2073 // "typedef member 'x' cannot be a bit-field"
2074 Diag(Loc, diag::err_typedef_not_bitfield)
2075 << Name << BitWidth->getSourceRange();
2076 } else {
2077 // A function typedef ("typedef int f(); f a;").
2078 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2079 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002080 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002081 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002082 }
Mike Stump11289f42009-09-09 15:08:12 +00002083
Chris Lattnerd26760a2009-03-05 23:01:03 +00002084 BitWidth = 0;
2085 Member->setInvalidDecl();
2086 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002087
2088 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002089
Larisse Voufo39a1e502013-08-06 01:03:05 +00002090 // If we have declared a member function template or static data member
2091 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002092 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2093 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002094 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2095 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002096 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002097
Richard Smith18f07db2012-08-06 03:25:17 +00002098 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002099 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002100 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002101 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2102 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002103
Douglas Gregorf2f08062011-03-08 17:10:18 +00002104 if (VS.getLastLocation().isValid()) {
2105 // Update the end location of a method that has a virt-specifiers.
2106 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2107 MD->setRangeEnd(VS.getLastLocation());
2108 }
Richard Smith18f07db2012-08-06 03:25:17 +00002109
Anders Carlssonc87f8612011-01-20 06:29:02 +00002110 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002111
Douglas Gregor92751d42008-11-17 22:58:34 +00002112 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002113
Daniel Jasper0baec5492012-06-06 08:32:04 +00002114 if (isInstField) {
2115 FieldDecl *FD = cast<FieldDecl>(Member);
2116 FieldCollector->Add(FD);
2117
2118 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2119 FD->getLocation())
2120 != DiagnosticsEngine::Ignored) {
2121 // Remember all explicit private FieldDecls that have a name, no side
2122 // effects and are not part of a dependent type declaration.
2123 if (!FD->isImplicit() && FD->getDeclName() &&
2124 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002125 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002126 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002127 !InitializationHasSideEffects(*FD))
2128 UnusedPrivateFields.insert(FD);
2129 }
2130 }
2131
John McCall48871652010-08-21 09:40:31 +00002132 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002133}
2134
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002135namespace {
2136 class UninitializedFieldVisitor
2137 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2138 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002139 // List of Decls to generate a warning on. Also remove Decls that become
2140 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002141 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002142 // If non-null, add a note to the warning pointing back to the constructor.
2143 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002144 public:
2145 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002146 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002147 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002148 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002149 : Inherited(S.Context), S(S), Decls(Decls),
2150 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002151
Richard Trieufd687772013-09-16 20:46:50 +00002152 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002153 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2154 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002155
Richard Trieu1bc22c12013-09-13 03:20:53 +00002156 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2157 // or union.
2158 MemberExpr *FieldME = ME;
2159
2160 Expr *Base = ME;
2161 while (isa<MemberExpr>(Base)) {
2162 ME = cast<MemberExpr>(Base);
2163
2164 if (isa<VarDecl>(ME->getMemberDecl()))
2165 return;
2166
2167 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2168 if (!FD->isAnonymousStructOrUnion())
2169 FieldME = ME;
2170
2171 Base = ME->getBase();
2172 }
2173
Richard Trieufd687772013-09-16 20:46:50 +00002174 if (!isa<CXXThisExpr>(Base))
2175 return;
2176
Richard Trieu406e65c2013-09-20 03:03:06 +00002177 ValueDecl* FoundVD = FieldME->getMemberDecl();
2178
Richard Trieuef64e942013-10-25 00:56:00 +00002179 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002180 return;
2181
Richard Trieuef64e942013-10-25 00:56:00 +00002182 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002183
Richard Trieuef64e942013-10-25 00:56:00 +00002184 // Prevent double warnings on use of unbounded references.
2185 if (IsReference != CheckReferenceOnly)
2186 return;
2187
2188 unsigned diag = IsReference
2189 ? diag::warn_reference_field_is_uninit
2190 : diag::warn_field_is_uninit;
2191 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2192 if (Constructor)
2193 S.Diag(Constructor->getLocation(),
2194 diag::note_uninit_in_this_constructor)
2195 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2196
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002197 }
2198
2199 void HandleValue(Expr *E) {
2200 E = E->IgnoreParens();
2201
2202 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002203 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002204 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002205 }
2206
2207 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2208 HandleValue(CO->getTrueExpr());
2209 HandleValue(CO->getFalseExpr());
2210 return;
2211 }
2212
2213 if (BinaryConditionalOperator *BCO =
2214 dyn_cast<BinaryConditionalOperator>(E)) {
2215 HandleValue(BCO->getCommon());
2216 HandleValue(BCO->getFalseExpr());
2217 return;
2218 }
2219
2220 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2221 switch (BO->getOpcode()) {
2222 default:
2223 return;
2224 case(BO_PtrMemD):
2225 case(BO_PtrMemI):
2226 HandleValue(BO->getLHS());
2227 return;
2228 case(BO_Comma):
2229 HandleValue(BO->getRHS());
2230 return;
2231 }
2232 }
2233 }
2234
Richard Trieu1bc22c12013-09-13 03:20:53 +00002235 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002236 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002237 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002238
2239 Inherited::VisitMemberExpr(ME);
2240 }
2241
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002242 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2243 if (E->getCastKind() == CK_LValueToRValue)
2244 HandleValue(E->getSubExpr());
2245
2246 Inherited::VisitImplicitCastExpr(E);
2247 }
2248
Richard Trieu1bc22c12013-09-13 03:20:53 +00002249 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002250 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002251 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2252 if (ICE->getCastKind() == CK_NoOp)
2253 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002254 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002255
2256 Inherited::VisitCXXConstructExpr(E);
2257 }
2258
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002259 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2260 Expr *Callee = E->getCallee();
2261 if (isa<MemberExpr>(Callee))
2262 HandleValue(Callee);
2263
2264 Inherited::VisitCXXMemberCallExpr(E);
2265 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002266
2267 void VisitBinaryOperator(BinaryOperator *E) {
2268 // If a field assignment is detected, remove the field from the
2269 // uninitiailized field set.
2270 if (E->getOpcode() == BO_Assign)
2271 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2272 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002273 if (!FD->getType()->isReferenceType())
2274 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002275
2276 Inherited::VisitBinaryOperator(E);
2277 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002278 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002279 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002280 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2281 const CXXConstructorDecl *Constructor) {
2282 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002283 return;
2284
Richard Trieuef64e942013-10-25 00:56:00 +00002285 if (!E)
2286 return;
2287
2288 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2289 E = Default->getExpr();
2290 if (!E)
2291 return;
2292 // In class initializers will point to the constructor.
2293 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2294 } else {
2295 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2296 }
2297 }
2298
2299 // Diagnose value-uses of fields to initialize themselves, e.g.
2300 // foo(foo)
2301 // where foo is not also a parameter to the constructor.
2302 // Also diagnose across field uninitialized use such as
2303 // x(y), y(x)
2304 // TODO: implement -Wuninitialized and fold this into that framework.
2305 static void DiagnoseUninitializedFields(
2306 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2307
2308 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2309 Constructor->getLocation())
2310 == DiagnosticsEngine::Ignored) {
2311 return;
2312 }
2313
2314 if (Constructor->isInvalidDecl())
2315 return;
2316
2317 const CXXRecordDecl *RD = Constructor->getParent();
2318
2319 // Holds fields that are uninitialized.
2320 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2321
2322 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002323 for (auto *I : RD->decls()) {
2324 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002325 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002326 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002327 UninitializedFields.insert(IFD->getAnonField());
2328 }
2329 }
2330
Aaron Ballman0ad78302014-03-13 17:34:31 +00002331 for (const auto *FieldInit : Constructor->inits()) {
2332 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002333
2334 CheckInitExprContainsUninitializedFields(
2335 SemaRef, InitExpr, UninitializedFields, Constructor);
2336
Aaron Ballman0ad78302014-03-13 17:34:31 +00002337 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002338 UninitializedFields.erase(Field);
2339 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002340 }
2341} // namespace
2342
Richard Smith74108172014-01-17 03:11:34 +00002343/// \brief Enter a new C++ default initializer scope. After calling this, the
2344/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2345/// parsing or instantiating the initializer failed.
2346void Sema::ActOnStartCXXInClassMemberInitializer() {
2347 // Create a synthetic function scope to represent the call to the constructor
2348 // that notionally surrounds a use of this initializer.
2349 PushFunctionScope();
2350}
2351
2352/// \brief This is invoked after parsing an in-class initializer for a
2353/// non-static C++ class member, and after instantiating an in-class initializer
2354/// in a class template. Such actions are deferred until the class is complete.
2355void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2356 SourceLocation InitLoc,
2357 Expr *InitExpr) {
2358 // Pop the notional constructor scope we created earlier.
2359 PopFunctionScopeInfo(0, D);
2360
Richard Smith938f40b2011-06-11 17:19:42 +00002361 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002362 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2363 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002364
2365 if (!InitExpr) {
2366 FD->setInvalidDecl();
2367 FD->removeInClassInitializer();
2368 return;
2369 }
2370
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002371 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2372 FD->setInvalidDecl();
2373 FD->removeInClassInitializer();
2374 return;
2375 }
2376
Richard Smith938f40b2011-06-11 17:19:42 +00002377 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002378 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002379 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002380 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002381 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002382 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002383 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2384 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002385 if (Init.isInvalid()) {
2386 FD->setInvalidDecl();
2387 return;
2388 }
Richard Smith938f40b2011-06-11 17:19:42 +00002389 }
2390
Richard Smith945f8d32013-01-14 22:39:08 +00002391 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002392 // The initialization of each base and member constitutes a
2393 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002394 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002395 if (Init.isInvalid()) {
2396 FD->setInvalidDecl();
2397 return;
2398 }
2399
2400 InitExpr = Init.release();
2401
2402 FD->setInClassInitializer(InitExpr);
2403}
2404
Douglas Gregor15e77a22009-12-31 09:10:24 +00002405/// \brief Find the direct and/or virtual base specifiers that
2406/// correspond to the given base type, for use in base initialization
2407/// within a constructor.
2408static bool FindBaseInitializer(Sema &SemaRef,
2409 CXXRecordDecl *ClassDecl,
2410 QualType BaseType,
2411 const CXXBaseSpecifier *&DirectBaseSpec,
2412 const CXXBaseSpecifier *&VirtualBaseSpec) {
2413 // First, check for a direct base class.
2414 DirectBaseSpec = 0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002415 for (const auto &Base : ClassDecl->bases()) {
2416 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002417 // We found a direct base of this type. That's what we're
2418 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002419 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002420 break;
2421 }
2422 }
2423
2424 // Check for a virtual base class.
2425 // FIXME: We might be able to short-circuit this if we know in advance that
2426 // there are no virtual bases.
2427 VirtualBaseSpec = 0;
2428 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2429 // We haven't found a base yet; search the class hierarchy for a
2430 // virtual base class.
2431 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2432 /*DetectVirtual=*/false);
2433 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2434 BaseType, Paths)) {
2435 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2436 Path != Paths.end(); ++Path) {
2437 if (Path->back().Base->isVirtual()) {
2438 VirtualBaseSpec = Path->back().Base;
2439 break;
2440 }
2441 }
2442 }
2443 }
2444
2445 return DirectBaseSpec || VirtualBaseSpec;
2446}
2447
Sebastian Redla74948d2011-09-24 17:48:25 +00002448/// \brief Handle a C++ member initializer using braced-init-list syntax.
2449MemInitResult
2450Sema::ActOnMemInitializer(Decl *ConstructorD,
2451 Scope *S,
2452 CXXScopeSpec &SS,
2453 IdentifierInfo *MemberOrBase,
2454 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002455 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002456 SourceLocation IdLoc,
2457 Expr *InitList,
2458 SourceLocation EllipsisLoc) {
2459 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002460 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002461 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002462}
2463
2464/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002465MemInitResult
John McCall48871652010-08-21 09:40:31 +00002466Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002467 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002468 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002469 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002470 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002471 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002472 SourceLocation IdLoc,
2473 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002474 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002475 SourceLocation RParenLoc,
2476 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002477 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002478 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002479 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002480 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002481}
2482
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002483namespace {
2484
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002485// Callback to only accept typo corrections that can be a valid C++ member
2486// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002487class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002488public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002489 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2490 : ClassDecl(ClassDecl) {}
2491
Craig Toppera798a9d2014-03-02 09:32:10 +00002492 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002493 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2494 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2495 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002496 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002497 }
2498 return false;
2499 }
2500
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002501private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002502 CXXRecordDecl *ClassDecl;
2503};
2504
2505}
2506
Sebastian Redla74948d2011-09-24 17:48:25 +00002507/// \brief Handle a C++ member initializer.
2508MemInitResult
2509Sema::BuildMemInitializer(Decl *ConstructorD,
2510 Scope *S,
2511 CXXScopeSpec &SS,
2512 IdentifierInfo *MemberOrBase,
2513 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002514 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002515 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002516 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002517 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002518 if (!ConstructorD)
2519 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002520
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002521 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002522
2523 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002524 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002525 if (!Constructor) {
2526 // The user wrote a constructor initializer on a function that is
2527 // not a C++ constructor. Ignore the error for now, because we may
2528 // have more member initializers coming; we'll diagnose it just
2529 // once in ActOnMemInitializers.
2530 return true;
2531 }
2532
2533 CXXRecordDecl *ClassDecl = Constructor->getParent();
2534
2535 // C++ [class.base.init]p2:
2536 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002537 // constructor's class and, if not found in that scope, are looked
2538 // up in the scope containing the constructor's definition.
2539 // [Note: if the constructor's class contains a member with the
2540 // same name as a direct or virtual base class of the class, a
2541 // mem-initializer-id naming the member or base class and composed
2542 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002543 // mem-initializer-id for the hidden base class may be specified
2544 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002545 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002546 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002547 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002548 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002549 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002550 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002551 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2552 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002553 if (EllipsisLoc.isValid())
2554 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002555 << MemberOrBase
2556 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002557
Sebastian Redla9351792012-02-11 23:51:47 +00002558 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002559 }
Francois Pichetd583da02010-12-04 09:14:42 +00002560 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002561 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002562 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002563 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002564 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002565
2566 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002567 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002568 } else if (DS.getTypeSpecType() == TST_decltype) {
2569 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002570 } else {
2571 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2572 LookupParsedName(R, S, &SS);
2573
2574 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2575 if (!TyD) {
2576 if (R.isAmbiguous()) return true;
2577
John McCallda6841b2010-04-09 19:01:14 +00002578 // We don't want access-control diagnostics here.
2579 R.suppressDiagnostics();
2580
Douglas Gregora3b624a2010-01-19 06:46:48 +00002581 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2582 bool NotUnknownSpecialization = false;
2583 DeclContext *DC = computeDeclContext(SS, false);
2584 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2585 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2586
2587 if (!NotUnknownSpecialization) {
2588 // When the scope specifier can refer to a member of an unknown
2589 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002590 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2591 SS.getWithLocInContext(Context),
2592 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002593 if (BaseType.isNull())
2594 return true;
2595
Douglas Gregora3b624a2010-01-19 06:46:48 +00002596 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002597 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002598 }
2599 }
2600
Douglas Gregor15e77a22009-12-31 09:10:24 +00002601 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002602 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002603 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002604 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002605 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00002606 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002607 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002608 // We have found a non-static data member with a similar
2609 // name to what was typed; complain and initialize that
2610 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002611 diagnoseTypo(Corr,
2612 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2613 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002614 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002615 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002616 const CXXBaseSpecifier *DirectBaseSpec;
2617 const CXXBaseSpecifier *VirtualBaseSpec;
2618 if (FindBaseInitializer(*this, ClassDecl,
2619 Context.getTypeDeclType(Type),
2620 DirectBaseSpec, VirtualBaseSpec)) {
2621 // We have found a direct or virtual base class with a
2622 // similar name to what was typed; complain and initialize
2623 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002624 diagnoseTypo(Corr,
2625 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2626 << MemberOrBase << false,
2627 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002628
Richard Smithf9b15102013-08-17 00:46:16 +00002629 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2630 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002631 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002632 diag::note_base_class_specified_here)
2633 << BaseSpec->getType()
2634 << BaseSpec->getSourceRange();
2635
Douglas Gregor15e77a22009-12-31 09:10:24 +00002636 TyD = Type;
2637 }
2638 }
2639 }
2640
Douglas Gregora3b624a2010-01-19 06:46:48 +00002641 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002642 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002643 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002644 return true;
2645 }
John McCallb5a0d312009-12-21 10:41:20 +00002646 }
2647
Douglas Gregora3b624a2010-01-19 06:46:48 +00002648 if (BaseType.isNull()) {
2649 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002650 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002651 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002652 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2653 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002654 }
2655 }
Mike Stump11289f42009-09-09 15:08:12 +00002656
John McCallbcd03502009-12-07 02:54:59 +00002657 if (!TInfo)
2658 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002659
Sebastian Redla9351792012-02-11 23:51:47 +00002660 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002661}
2662
Chandler Carruth599deef2011-09-03 01:14:15 +00002663/// Checks a member initializer expression for cases where reference (or
2664/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002665static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2666 Expr *Init,
2667 SourceLocation IdLoc) {
2668 QualType MemberTy = Member->getType();
2669
2670 // We only handle pointers and references currently.
2671 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2672 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2673 return;
2674
2675 const bool IsPointer = MemberTy->isPointerType();
2676 if (IsPointer) {
2677 if (const UnaryOperator *Op
2678 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2679 // The only case we're worried about with pointers requires taking the
2680 // address.
2681 if (Op->getOpcode() != UO_AddrOf)
2682 return;
2683
2684 Init = Op->getSubExpr();
2685 } else {
2686 // We only handle address-of expression initializers for pointers.
2687 return;
2688 }
2689 }
2690
Richard Smithe3b28bc2013-06-12 21:51:50 +00002691 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002692 // We only warn when referring to a non-reference parameter declaration.
2693 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2694 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002695 return;
2696
2697 S.Diag(Init->getExprLoc(),
2698 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2699 : diag::warn_bind_ref_member_to_parameter)
2700 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002701 } else {
2702 // Other initializers are fine.
2703 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002704 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002705
2706 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2707 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002708}
2709
John McCallfaf5fb42010-08-26 23:41:50 +00002710MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002711Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002712 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002713 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2714 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2715 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002716 "Member must be a FieldDecl or IndirectFieldDecl");
2717
Sebastian Redla9351792012-02-11 23:51:47 +00002718 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002719 return true;
2720
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002721 if (Member->isInvalidDecl())
2722 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002723
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002724 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002725 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002726 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002727 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002728 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002729 } else {
2730 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002731 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002732 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002733
Sebastian Redla9351792012-02-11 23:51:47 +00002734 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002735
Sebastian Redla9351792012-02-11 23:51:47 +00002736 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002737 // Can't check initialization for a member of dependent type or when
2738 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002739 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002740 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002741 bool InitList = false;
2742 if (isa<InitListExpr>(Init)) {
2743 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002744 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002745 }
2746
Chandler Carruthd44c3102010-12-06 09:23:57 +00002747 // Initialize the member.
2748 InitializedEntity MemberEntity =
2749 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2750 : InitializedEntity::InitializeMember(IndirectMember, 0);
2751 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002752 InitList ? InitializationKind::CreateDirectList(IdLoc)
2753 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2754 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002755
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002756 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2757 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002758 if (MemberInit.isInvalid())
2759 return true;
2760
Richard Smith736a9472013-06-12 20:42:33 +00002761 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2762
Richard Smith945f8d32013-01-14 22:39:08 +00002763 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002764 // The initialization of each base and member constitutes a
2765 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002766 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002767 if (MemberInit.isInvalid())
2768 return true;
2769
Richard Smithd59b8322012-12-19 01:39:02 +00002770 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002771 }
2772
Chandler Carruthd44c3102010-12-06 09:23:57 +00002773 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002774 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2775 InitRange.getBegin(), Init,
2776 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002777 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002778 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2779 InitRange.getBegin(), Init,
2780 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002781 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002782}
2783
John McCallfaf5fb42010-08-26 23:41:50 +00002784MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002785Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002786 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002787 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002788 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002789 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002790 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002791 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002792
Sebastian Redl0501c632012-02-12 16:37:36 +00002793 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002794 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002795 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2796 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002797 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002798 }
2799
Sebastian Redla9351792012-02-11 23:51:47 +00002800 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002801 // Initialize the object.
2802 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2803 QualType(ClassDecl->getTypeForDecl(), 0));
2804 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002805 InitList ? InitializationKind::CreateDirectList(NameLoc)
2806 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2807 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002808 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002809 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002810 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002811 if (DelegationInit.isInvalid())
2812 return true;
2813
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002814 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2815 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002816
Richard Smith945f8d32013-01-14 22:39:08 +00002817 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002818 // The initialization of each base and member constitutes a
2819 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002820 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2821 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002822 if (DelegationInit.isInvalid())
2823 return true;
2824
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002825 // If we are in a dependent context, template instantiation will
2826 // perform this type-checking again. Just save the arguments that we
2827 // received in a ParenListExpr.
2828 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2829 // of the information that we have about the base
2830 // initializer. However, deconstructing the ASTs is a dicey process,
2831 // and this approach is far more likely to get the corner cases right.
2832 if (CurContext->isDependentContext())
2833 DelegationInit = Owned(Init);
2834
Sebastian Redla9351792012-02-11 23:51:47 +00002835 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002836 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002837 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002838}
2839
2840MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002841Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002842 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002843 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002844 SourceLocation BaseLoc
2845 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002846
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002847 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2848 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2849 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2850
2851 // C++ [class.base.init]p2:
2852 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002853 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002854 // of that class, the mem-initializer is ill-formed. A
2855 // mem-initializer-list can initialize a base class using any
2856 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002857 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002858
Sebastian Redla9351792012-02-11 23:51:47 +00002859 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002860 if (EllipsisLoc.isValid()) {
2861 // This is a pack expansion.
2862 if (!BaseType->containsUnexpandedParameterPack()) {
2863 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002864 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002865
Douglas Gregor44e7df62011-01-04 00:32:56 +00002866 EllipsisLoc = SourceLocation();
2867 }
2868 } else {
2869 // Check for any unexpanded parameter packs.
2870 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2871 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002872
Sebastian Redla9351792012-02-11 23:51:47 +00002873 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002874 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002875 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002876
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002877 // Check for direct and virtual base classes.
2878 const CXXBaseSpecifier *DirectBaseSpec = 0;
2879 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2880 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002881 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2882 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002883 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002884
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002885 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2886 VirtualBaseSpec);
2887
2888 // C++ [base.class.init]p2:
2889 // Unless the mem-initializer-id names a nonstatic data member of the
2890 // constructor's class or a direct or virtual base of that class, the
2891 // mem-initializer is ill-formed.
2892 if (!DirectBaseSpec && !VirtualBaseSpec) {
2893 // If the class has any dependent bases, then it's possible that
2894 // one of those types will resolve to the same type as
2895 // BaseType. Therefore, just treat this as a dependent base
2896 // class initialization. FIXME: Should we try to check the
2897 // initialization anyway? It seems odd.
2898 if (ClassDecl->hasAnyDependentBases())
2899 Dependent = true;
2900 else
2901 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2902 << BaseType << Context.getTypeDeclType(ClassDecl)
2903 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2904 }
2905 }
2906
2907 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002908 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002909
Sebastian Redla74948d2011-09-24 17:48:25 +00002910 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2911 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002912 InitRange.getBegin(), Init,
2913 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002914 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002915
2916 // C++ [base.class.init]p2:
2917 // If a mem-initializer-id is ambiguous because it designates both
2918 // a direct non-virtual base class and an inherited virtual base
2919 // class, the mem-initializer is ill-formed.
2920 if (DirectBaseSpec && VirtualBaseSpec)
2921 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002922 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002923
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002924 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002925 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002926 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002927
2928 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002929 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002930 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002931 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002932 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002933 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002934 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002935
2936 InitializedEntity BaseEntity =
2937 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2938 InitializationKind Kind =
2939 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2940 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2941 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002942 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2943 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002944 if (BaseInit.isInvalid())
2945 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002946
Richard Smith945f8d32013-01-14 22:39:08 +00002947 // C++11 [class.base.init]p7:
2948 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002949 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002950 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002951 if (BaseInit.isInvalid())
2952 return true;
2953
2954 // If we are in a dependent context, template instantiation will
2955 // perform this type-checking again. Just save the arguments that we
2956 // received in a ParenListExpr.
2957 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2958 // of the information that we have about the base
2959 // initializer. However, deconstructing the ASTs is a dicey process,
2960 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002961 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002962 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002963
Alexis Hunt1d792652011-01-08 20:30:50 +00002964 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002965 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002966 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002967 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002968 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002969}
2970
Sebastian Redl22653ba2011-08-30 19:58:05 +00002971// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002972static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2973 if (T.isNull()) T = E->getType();
2974 QualType TargetType = SemaRef.BuildReferenceType(
2975 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002976 SourceLocation ExprLoc = E->getLocStart();
2977 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2978 TargetType, ExprLoc);
2979
2980 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2981 SourceRange(ExprLoc, ExprLoc),
2982 E->getSourceRange()).take();
2983}
2984
Anders Carlsson1b00e242010-04-23 03:10:23 +00002985/// ImplicitInitializerKind - How an implicit base or member initializer should
2986/// initialize its base or member.
2987enum ImplicitInitializerKind {
2988 IIK_Default,
2989 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002990 IIK_Move,
2991 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002992};
2993
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002994static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002995BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002996 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002997 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002998 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002999 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003000 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003001 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3002 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003003
John McCalldadc5752010-08-24 06:29:42 +00003004 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003005
3006 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003007 case IIK_Inherit: {
3008 const CXXRecordDecl *Inherited =
3009 Constructor->getInheritedConstructor()->getParent();
3010 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3011 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3012 // C++11 [class.inhctor]p8:
3013 // Each expression in the expression-list is of the form
3014 // static_cast<T&&>(p), where p is the name of the corresponding
3015 // constructor parameter and T is the declared type of p.
3016 SmallVector<Expr*, 16> Args;
3017 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3018 ParmVarDecl *PD = Constructor->getParamDecl(I);
3019 ExprResult ArgExpr =
3020 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3021 VK_LValue, SourceLocation());
3022 if (ArgExpr.isInvalid())
3023 return true;
3024 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3025 }
3026
3027 InitializationKind InitKind = InitializationKind::CreateDirect(
3028 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003029 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003030 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3031 break;
3032 }
3033 }
3034 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003035 case IIK_Default: {
3036 InitializationKind InitKind
3037 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003038 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3039 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003040 break;
3041 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003042
Sebastian Redl22653ba2011-08-30 19:58:05 +00003043 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003044 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003045 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003046 ParmVarDecl *Param = Constructor->getParamDecl(0);
3047 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003048
Anders Carlsson1b00e242010-04-23 03:10:23 +00003049 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003050 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003051 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003052 Constructor->getLocation(), ParamType,
3053 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003054
Eli Friedmanfa0df832012-02-02 03:46:19 +00003055 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3056
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003057 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003058 QualType ArgTy =
3059 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3060 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003061
Sebastian Redl22653ba2011-08-30 19:58:05 +00003062 if (Moving) {
3063 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3064 }
3065
John McCallcf142162010-08-07 06:22:56 +00003066 CXXCastPath BasePath;
3067 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003068 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3069 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003070 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003071 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003072
Anders Carlsson1b00e242010-04-23 03:10:23 +00003073 InitializationKind InitKind
3074 = InitializationKind::CreateDirect(Constructor->getLocation(),
3075 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003076 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3077 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003078 break;
3079 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003080 }
John McCallb268a282010-08-23 23:25:46 +00003081
Douglas Gregora40433a2010-12-07 00:41:46 +00003082 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003083 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003084 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003085
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003086 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003087 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003088 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3089 SourceLocation()),
3090 BaseSpec->isVirtual(),
3091 SourceLocation(),
3092 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003093 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003094 SourceLocation());
3095
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003096 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003097}
3098
Sebastian Redl22653ba2011-08-30 19:58:05 +00003099static bool RefersToRValueRef(Expr *MemRef) {
3100 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3101 return Referenced->getType()->isRValueReferenceType();
3102}
3103
Anders Carlsson3c1db572010-04-23 02:15:47 +00003104static bool
3105BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003106 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003107 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003108 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003109 if (Field->isInvalidDecl())
3110 return true;
3111
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003112 SourceLocation Loc = Constructor->getLocation();
3113
Sebastian Redl22653ba2011-08-30 19:58:05 +00003114 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3115 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003116 ParmVarDecl *Param = Constructor->getParamDecl(0);
3117 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003118
3119 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003120 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3121 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003122
Anders Carlsson423f5d82010-04-23 16:04:08 +00003123 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003124 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003125 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003126 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003127
Eli Friedmanfa0df832012-02-02 03:46:19 +00003128 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3129
Sebastian Redl22653ba2011-08-30 19:58:05 +00003130 if (Moving) {
3131 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3132 }
3133
Douglas Gregor94f9a482010-05-05 05:51:00 +00003134 // Build a reference to this field within the parameter.
3135 CXXScopeSpec SS;
3136 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3137 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003138 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3139 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003140 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003141 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003142 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003143 ParamType, Loc,
3144 /*IsArrow=*/false,
3145 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003146 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00003147 /*FirstQualifierInScope=*/0,
3148 MemberLookup,
3149 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003150 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003151 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003152
3153 // C++11 [class.copy]p15:
3154 // - if a member m has rvalue reference type T&&, it is direct-initialized
3155 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003156 if (RefersToRValueRef(CtorArg.get())) {
3157 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003158 }
3159
Douglas Gregor94f9a482010-05-05 05:51:00 +00003160 // When the field we are copying is an array, create index variables for
3161 // each dimension of the array. We use these index variables to subscript
3162 // the source array, and other clients (e.g., CodeGen) will perform the
3163 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003164 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003165 QualType BaseType = Field->getType();
3166 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003167 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003168 while (const ConstantArrayType *Array
3169 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003170 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003171 // Create the iteration variable for this array index.
3172 IdentifierInfo *IterationVarName = 0;
3173 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003174 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003175 llvm::raw_svector_ostream OS(Str);
3176 OS << "__i" << IndexVariables.size();
3177 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3178 }
3179 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003180 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003181 IterationVarName, SizeType,
3182 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003183 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003184 IndexVariables.push_back(IterationVar);
3185
3186 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003187 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003188 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003189 assert(!IterationVarRef.isInvalid() &&
3190 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003191 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3192 assert(!IterationVarRef.isInvalid() &&
3193 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003194
Douglas Gregor94f9a482010-05-05 05:51:00 +00003195 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003196 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003197 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003198 Loc);
3199 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003200 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003201
Douglas Gregor94f9a482010-05-05 05:51:00 +00003202 BaseType = Array->getElementType();
3203 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003204
3205 // The array subscript expression is an lvalue, which is wrong for moving.
3206 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003207 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003208
Douglas Gregor94f9a482010-05-05 05:51:00 +00003209 // Construct the entity that we will be initializing. For an array, this
3210 // will be first element in the array, which may require several levels
3211 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003212 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003213 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003214 if (Indirect)
3215 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3216 else
3217 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003218 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3219 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3220 0,
3221 Entities.back()));
3222
3223 // Direct-initialize to use the copy constructor.
3224 InitializationKind InitKind =
3225 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3226
Sebastian Redle9c4e842011-09-04 18:14:28 +00003227 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003228 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003229
John McCalldadc5752010-08-24 06:29:42 +00003230 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003231 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003232 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003233 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003234 if (MemberInit.isInvalid())
3235 return true;
3236
Douglas Gregor493627b2011-08-10 15:22:55 +00003237 if (Indirect) {
3238 assert(IndexVariables.size() == 0 &&
3239 "Indirect field improperly initialized");
3240 CXXMemberInit
3241 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3242 Loc, Loc,
3243 MemberInit.takeAs<Expr>(),
3244 Loc);
3245 } else
3246 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3247 Loc, MemberInit.takeAs<Expr>(),
3248 Loc,
3249 IndexVariables.data(),
3250 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003251 return false;
3252 }
3253
Richard Smithc2bc61b2013-03-18 21:12:30 +00003254 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3255 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003256
Anders Carlsson3c1db572010-04-23 02:15:47 +00003257 QualType FieldBaseElementType =
3258 SemaRef.Context.getBaseElementType(Field->getType());
3259
Anders Carlsson3c1db572010-04-23 02:15:47 +00003260 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003261 InitializedEntity InitEntity
3262 = Indirect? InitializedEntity::InitializeMember(Indirect)
3263 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003264 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003265 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003266
3267 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3268 ExprResult MemberInit =
3269 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003270
Douglas Gregora40433a2010-12-07 00:41:46 +00003271 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003272 if (MemberInit.isInvalid())
3273 return true;
3274
Douglas Gregor493627b2011-08-10 15:22:55 +00003275 if (Indirect)
3276 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3277 Indirect, Loc,
3278 Loc,
3279 MemberInit.get(),
3280 Loc);
3281 else
3282 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3283 Field, Loc, Loc,
3284 MemberInit.get(),
3285 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003286 return false;
3287 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003288
Alexis Hunt8b455182011-05-17 00:19:05 +00003289 if (!Field->getParent()->isUnion()) {
3290 if (FieldBaseElementType->isReferenceType()) {
3291 SemaRef.Diag(Constructor->getLocation(),
3292 diag::err_uninitialized_member_in_ctor)
3293 << (int)Constructor->isImplicit()
3294 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3295 << 0 << Field->getDeclName();
3296 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3297 return true;
3298 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003299
Alexis Hunt8b455182011-05-17 00:19:05 +00003300 if (FieldBaseElementType.isConstQualified()) {
3301 SemaRef.Diag(Constructor->getLocation(),
3302 diag::err_uninitialized_member_in_ctor)
3303 << (int)Constructor->isImplicit()
3304 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3305 << 1 << Field->getDeclName();
3306 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3307 return true;
3308 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003309 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003310
David Blaikiebbafb8a2012-03-11 07:00:24 +00003311 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003312 FieldBaseElementType->isObjCRetainableType() &&
3313 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3314 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003315 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003316 // Default-initialize Objective-C pointers to NULL.
3317 CXXMemberInit
3318 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3319 Loc, Loc,
3320 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3321 Loc);
3322 return false;
3323 }
3324
Anders Carlsson3c1db572010-04-23 02:15:47 +00003325 // Nothing to initialize.
3326 CXXMemberInit = 0;
3327 return false;
3328}
John McCallbc83b3f2010-05-20 23:23:51 +00003329
3330namespace {
3331struct BaseAndFieldInfo {
3332 Sema &S;
3333 CXXConstructorDecl *Ctor;
3334 bool AnyErrorsInInits;
3335 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003336 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003337 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003338 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003339
3340 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3341 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003342 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3343 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003344 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003345 else if (Generated && Ctor->isMoveConstructor())
3346 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003347 else if (Ctor->getInheritedConstructor())
3348 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003349 else
3350 IIK = IIK_Default;
3351 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003352
3353 bool isImplicitCopyOrMove() const {
3354 switch (IIK) {
3355 case IIK_Copy:
3356 case IIK_Move:
3357 return true;
3358
3359 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003360 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003361 return false;
3362 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003363
3364 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003365 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003366
3367 bool addFieldInitializer(CXXCtorInitializer *Init) {
3368 AllToInit.push_back(Init);
3369
3370 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003371 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003372 S.UnusedPrivateFields.remove(Init->getAnyMember());
3373
3374 return false;
3375 }
John McCallbc83b3f2010-05-20 23:23:51 +00003376
Richard Smithab44d5b2013-12-10 08:25:00 +00003377 bool isInactiveUnionMember(FieldDecl *Field) {
3378 RecordDecl *Record = Field->getParent();
3379 if (!Record->isUnion())
3380 return false;
3381
Richard Smith8d183852013-12-10 20:56:03 +00003382 if (FieldDecl *Active =
3383 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003384 return Active != Field->getCanonicalDecl();
3385
3386 // In an implicit copy or move constructor, ignore any in-class initializer.
3387 if (isImplicitCopyOrMove())
3388 return true;
3389
3390 // If there's no explicit initialization, the field is active only if it
3391 // has an in-class initializer...
3392 if (Field->hasInClassInitializer())
3393 return false;
3394 // ... or it's an anonymous struct or union whose class has an in-class
3395 // initializer.
3396 if (!Field->isAnonymousStructOrUnion())
3397 return true;
3398 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3399 return !FieldRD->hasInClassInitializer();
3400 }
3401
3402 /// \brief Determine whether the given field is, or is within, a union member
3403 /// that is inactive (because there was an initializer given for a different
3404 /// member of the union, or because the union was not initialized at all).
3405 bool isWithinInactiveUnionMember(FieldDecl *Field,
3406 IndirectFieldDecl *Indirect) {
3407 if (!Indirect)
3408 return isInactiveUnionMember(Field);
3409
Aaron Ballman29c94602014-03-07 18:36:15 +00003410 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003411 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003412 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003413 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003414 }
3415 return false;
3416 }
3417};
Richard Smithc94ec842011-09-19 13:34:43 +00003418}
3419
Douglas Gregor10f939c2011-11-02 23:04:16 +00003420/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3421/// array type.
3422static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3423 if (T->isIncompleteArrayType())
3424 return true;
3425
3426 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3427 if (!ArrayT->getSize())
3428 return true;
3429
3430 T = ArrayT->getElementType();
3431 }
3432
3433 return false;
3434}
3435
Richard Smith938f40b2011-06-11 17:19:42 +00003436static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003437 FieldDecl *Field,
3438 IndirectFieldDecl *Indirect = 0) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003439 if (Field->isInvalidDecl())
3440 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003441
Chandler Carruth139e9622010-06-30 02:59:29 +00003442 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0a8cfc72012-08-07 21:30:42 +00003443 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3444 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003445
Richard Smithab44d5b2013-12-10 08:25:00 +00003446 // C++11 [class.base.init]p8:
3447 // if the entity is a non-static data member that has a
3448 // brace-or-equal-initializer and either
3449 // -- the constructor's class is a union and no other variant member of that
3450 // union is designated by a mem-initializer-id or
3451 // -- the constructor's class is not a union, and, if the entity is a member
3452 // of an anonymous union, no other member of that union is designated by
3453 // a mem-initializer-id,
3454 // the entity is initialized as specified in [dcl.init].
3455 //
3456 // We also apply the same rules to handle anonymous structs within anonymous
3457 // unions.
3458 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3459 return false;
3460
Douglas Gregor7db3e952011-11-28 20:03:15 +00003461 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003462 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3463 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003464 CXXCtorInitializer *Init;
3465 if (Indirect)
3466 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3467 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003468 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003469 SourceLocation());
3470 else
3471 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3472 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003473 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003474 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003475 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003476 }
3477
Douglas Gregor10f939c2011-11-02 23:04:16 +00003478 // Don't initialize incomplete or zero-length arrays.
3479 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3480 return false;
3481
John McCallbc83b3f2010-05-20 23:23:51 +00003482 // Don't try to build an implicit initializer if there were semantic
3483 // errors in any of the initializers (and therefore we might be
3484 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003485 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003486 return false;
3487
Alexis Hunt1d792652011-01-08 20:30:50 +00003488 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003489 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3490 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003491 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003492
Richard Smith0a8cfc72012-08-07 21:30:42 +00003493 if (!Init)
3494 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003495
Richard Smith0a8cfc72012-08-07 21:30:42 +00003496 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003497}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003498
3499bool
3500Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3501 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003502 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003503 Constructor->setNumCtorInitializers(1);
3504 CXXCtorInitializer **initializer =
3505 new (Context) CXXCtorInitializer*[1];
3506 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3507 Constructor->setCtorInitializers(initializer);
3508
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003509 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003510 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003511 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3512 }
3513
Alexis Hunte2622992011-05-05 00:05:47 +00003514 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003515
Alexis Hunt61bc1732011-05-01 07:04:31 +00003516 return false;
3517}
Douglas Gregor493627b2011-08-10 15:22:55 +00003518
David Blaikie3fc2f912013-01-17 05:26:25 +00003519bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3520 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003521 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003522 // Just store the initializers as written, they will be checked during
3523 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003524 if (!Initializers.empty()) {
3525 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003526 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003527 new (Context) CXXCtorInitializer*[Initializers.size()];
3528 memcpy(baseOrMemberInitializers, Initializers.data(),
3529 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003530 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003531 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003532
3533 // Let template instantiation know whether we had errors.
3534 if (AnyErrors)
3535 Constructor->setInvalidDecl();
3536
Anders Carlssondb0a9652010-04-02 06:26:44 +00003537 return false;
3538 }
3539
John McCallbc83b3f2010-05-20 23:23:51 +00003540 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003541
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003542 // We need to build the initializer AST according to order of construction
3543 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003544 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003545 if (!ClassDecl)
3546 return true;
3547
Eli Friedman9cf6b592009-11-09 19:20:36 +00003548 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003549
David Blaikie3fc2f912013-01-17 05:26:25 +00003550 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003551 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003552
Anders Carlssondb0a9652010-04-02 06:26:44 +00003553 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003554 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003555 else {
Francois Pichetd583da02010-12-04 09:14:42 +00003556 Info.AllBaseFields[Member->getAnyMember()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003557
3558 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003559 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003560 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003561 if (FD && FD->getParent()->isUnion())
3562 Info.ActiveUnionMember.insert(std::make_pair(
3563 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3564 }
3565 } else if (FieldDecl *FD = Member->getMember()) {
3566 if (FD->getParent()->isUnion())
3567 Info.ActiveUnionMember.insert(std::make_pair(
3568 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3569 }
3570 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003571 }
3572
Anders Carlsson43c64af2010-04-21 19:52:01 +00003573 // Keep track of the direct virtual bases.
3574 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003575 for (auto &I : ClassDecl->bases()) {
3576 if (I.isVirtual())
3577 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003578 }
3579
Anders Carlssondb0a9652010-04-02 06:26:44 +00003580 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003581 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003582 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003583 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003584 // [class.base.init]p7, per DR257:
3585 // A mem-initializer where the mem-initializer-id names a virtual base
3586 // class is ignored during execution of a constructor of any class that
3587 // is not the most derived class.
3588 if (ClassDecl->isAbstract()) {
3589 // FIXME: Provide a fixit to remove the base specifier. This requires
3590 // tracking the location of the associated comma for a base specifier.
3591 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003592 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003593 DiagnoseAbstractType(ClassDecl);
3594 }
3595
John McCallbc83b3f2010-05-20 23:23:51 +00003596 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003597 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3598 // [class.base.init]p8, per DR257:
3599 // If a given [...] base class is not named by a mem-initializer-id
3600 // [...] and the entity is not a virtual base class of an abstract
3601 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003602 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003603 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003604 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003605 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003606 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003607 HadError = true;
3608 continue;
3609 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003610
John McCallbc83b3f2010-05-20 23:23:51 +00003611 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003612 }
3613 }
Mike Stump11289f42009-09-09 15:08:12 +00003614
John McCallbc83b3f2010-05-20 23:23:51 +00003615 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003616 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003617 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003618 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003619 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003620
Alexis Hunt1d792652011-01-08 20:30:50 +00003621 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003622 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003623 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003624 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003625 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003626 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003627 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003628 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003629 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003630 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003631 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003632
John McCallbc83b3f2010-05-20 23:23:51 +00003633 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003634 }
3635 }
Mike Stump11289f42009-09-09 15:08:12 +00003636
John McCallbc83b3f2010-05-20 23:23:51 +00003637 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003638 for (auto *Mem : ClassDecl->decls()) {
3639 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003640 // C++ [class.bit]p2:
3641 // A declaration for a bit-field that omits the identifier declares an
3642 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3643 // initialized.
3644 if (F->isUnnamedBitfield())
3645 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003646
Sebastian Redl22653ba2011-08-30 19:58:05 +00003647 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003648 // handle anonymous struct/union fields based on their individual
3649 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003650 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003651 continue;
3652
3653 if (CollectFieldInitializer(*this, Info, F))
3654 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003655 continue;
3656 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003657
3658 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003659 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003660 continue;
3661
Aaron Ballman629afae2014-03-07 19:56:05 +00003662 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003663 if (F->getType()->isIncompleteArrayType()) {
3664 assert(ClassDecl->hasFlexibleArrayMember() &&
3665 "Incomplete array type is not valid");
3666 continue;
3667 }
3668
Douglas Gregor493627b2011-08-10 15:22:55 +00003669 // Initialize each field of an anonymous struct individually.
3670 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3671 HadError = true;
3672
3673 continue;
3674 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003675 }
Mike Stump11289f42009-09-09 15:08:12 +00003676
David Blaikie3fc2f912013-01-17 05:26:25 +00003677 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003678 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003679 Constructor->setNumCtorInitializers(NumInitializers);
3680 CXXCtorInitializer **baseOrMemberInitializers =
3681 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003682 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003683 NumInitializers * sizeof(CXXCtorInitializer*));
3684 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003685
John McCalla6309952010-03-16 21:39:52 +00003686 // Constructors implicitly reference the base and member
3687 // destructors.
3688 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3689 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003690 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003691
3692 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003693}
3694
David Blaikieb61b8152013-01-17 08:49:22 +00003695static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003696 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003697 const RecordDecl *RD = RT->getDecl();
3698 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003699 for (auto *Field : RD->fields())
3700 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003701 return;
3702 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003703 }
David Blaikieb61b8152013-01-17 08:49:22 +00003704 IdealInits.push_back(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003705}
3706
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003707static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3708 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003709}
3710
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003711static const void *GetKeyForMember(ASTContext &Context,
3712 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003713 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003714 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003715
David Blaikieb61b8152013-01-17 08:49:22 +00003716 return Member->getAnyMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00003717}
3718
David Blaikie3fc2f912013-01-17 05:26:25 +00003719static void DiagnoseBaseOrMemInitializerOrder(
3720 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3721 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003722 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003723 return;
Mike Stump11289f42009-09-09 15:08:12 +00003724
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003725 // Don't check initializers order unless the warning is enabled at the
3726 // location of at least one initializer.
3727 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003728 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003729 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003730 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3731 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003732 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003733 ShouldCheckOrder = true;
3734 break;
3735 }
3736 }
3737 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003738 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003739
John McCallbb7b6582010-04-10 07:37:23 +00003740 // Build the list of bases and members in the order that they'll
3741 // actually be initialized. The explicit initializers should be in
3742 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003743 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003744
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003745 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3746
John McCallbb7b6582010-04-10 07:37:23 +00003747 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003748 for (const auto &VBase : ClassDecl->vbases())
3749 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003750
John McCallbb7b6582010-04-10 07:37:23 +00003751 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003752 for (const auto &Base : ClassDecl->bases()) {
3753 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003754 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003755 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003756 }
Mike Stump11289f42009-09-09 15:08:12 +00003757
John McCallbb7b6582010-04-10 07:37:23 +00003758 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003759 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003760 if (Field->isUnnamedBitfield())
3761 continue;
3762
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003763 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003764 }
3765
John McCallbb7b6582010-04-10 07:37:23 +00003766 unsigned NumIdealInits = IdealInitKeys.size();
3767 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003768
Alexis Hunt1d792652011-01-08 20:30:50 +00003769 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003770 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003771 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003772 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003773
3774 // Scan forward to try to find this initializer in the idealized
3775 // initializers list.
3776 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3777 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003778 break;
John McCallbb7b6582010-04-10 07:37:23 +00003779
3780 // If we didn't find this initializer, it must be because we
3781 // scanned past it on a previous iteration. That can only
3782 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003783 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003784 Sema::SemaDiagnosticBuilder D =
3785 SemaRef.Diag(PrevInit->getSourceLocation(),
3786 diag::warn_initializer_out_of_order);
3787
Francois Pichetd583da02010-12-04 09:14:42 +00003788 if (PrevInit->isAnyMemberInitializer())
3789 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003790 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003791 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003792
Francois Pichetd583da02010-12-04 09:14:42 +00003793 if (Init->isAnyMemberInitializer())
3794 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003795 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003796 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003797
3798 // Move back to the initializer's location in the ideal list.
3799 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3800 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003801 break;
John McCallbb7b6582010-04-10 07:37:23 +00003802
3803 assert(IdealIndex != NumIdealInits &&
3804 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003805 }
John McCallbb7b6582010-04-10 07:37:23 +00003806
3807 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003808 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003809}
3810
John McCall23eebd92010-04-10 09:28:51 +00003811namespace {
3812bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003813 CXXCtorInitializer *Init,
3814 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003815 if (!PrevInit) {
3816 PrevInit = Init;
3817 return false;
3818 }
3819
Douglas Gregorea306a12013-03-25 23:28:23 +00003820 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003821 S.Diag(Init->getSourceLocation(),
3822 diag::err_multiple_mem_initialization)
3823 << Field->getDeclName()
3824 << Init->getSourceRange();
3825 else {
John McCall424cec92011-01-19 06:33:43 +00003826 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003827 assert(BaseClass && "neither field nor base");
3828 S.Diag(Init->getSourceLocation(),
3829 diag::err_multiple_base_initialization)
3830 << QualType(BaseClass, 0)
3831 << Init->getSourceRange();
3832 }
3833 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3834 << 0 << PrevInit->getSourceRange();
3835
3836 return true;
3837}
3838
Alexis Hunt1d792652011-01-08 20:30:50 +00003839typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003840typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3841
3842bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003843 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003844 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003845 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003846 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003847 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003848
3849 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003850 if (Parent->isUnion()) {
3851 UnionEntry &En = Unions[Parent];
3852 if (En.first && En.first != Child) {
3853 S.Diag(Init->getSourceLocation(),
3854 diag::err_multiple_mem_union_initialization)
3855 << Field->getDeclName()
3856 << Init->getSourceRange();
3857 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3858 << 0 << En.second->getSourceRange();
3859 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003860 }
3861 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003862 En.first = Child;
3863 En.second = Init;
3864 }
David Blaikie0f65d592011-11-17 06:01:57 +00003865 if (!Parent->isAnonymousStructOrUnion())
3866 return false;
John McCall23eebd92010-04-10 09:28:51 +00003867 }
3868
3869 Child = Parent;
3870 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003871 }
John McCall23eebd92010-04-10 09:28:51 +00003872
3873 return false;
3874}
3875}
3876
Anders Carlssone857b292010-04-02 03:37:03 +00003877/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003878void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003879 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003880 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003881 bool AnyErrors) {
3882 if (!ConstructorDecl)
3883 return;
3884
3885 AdjustDeclIfTemplate(ConstructorDecl);
3886
3887 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003888 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003889
3890 if (!Constructor) {
3891 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3892 return;
3893 }
3894
John McCall23eebd92010-04-10 09:28:51 +00003895 // Mapping for the duplicate initializers check.
3896 // For member initializers, this is keyed with a FieldDecl*.
3897 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003898 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003899
3900 // Mapping for the inconsistent anonymous-union initializers check.
3901 RedundantUnionMap MemberUnions;
3902
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003903 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003904 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003905 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003906
Abramo Bagnara341d7832010-05-26 18:09:23 +00003907 // Set the source order index.
3908 Init->setSourceOrder(i);
3909
Francois Pichetd583da02010-12-04 09:14:42 +00003910 if (Init->isAnyMemberInitializer()) {
3911 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003912 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3913 CheckRedundantUnionInit(*this, Init, MemberUnions))
3914 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003915 } else if (Init->isBaseInitializer()) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003916 const void *Key =
3917 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall23eebd92010-04-10 09:28:51 +00003918 if (CheckRedundantInit(*this, Init, Members[Key]))
3919 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003920 } else {
3921 assert(Init->isDelegatingInitializer());
3922 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003923 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003924 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003925 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003926 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003927 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003928 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003929 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003930 // Return immediately as the initializer is set.
3931 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003932 }
Anders Carlssone857b292010-04-02 03:37:03 +00003933 }
3934
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003935 if (HadError)
3936 return;
3937
David Blaikie3fc2f912013-01-17 05:26:25 +00003938 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003939
David Blaikie3fc2f912013-01-17 05:26:25 +00003940 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003941
Richard Trieuef64e942013-10-25 00:56:00 +00003942 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003943}
3944
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003945void
John McCalla6309952010-03-16 21:39:52 +00003946Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3947 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003948 // Ignore dependent contexts. Also ignore unions, since their members never
3949 // have destructors implicitly called.
3950 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003951 return;
John McCall1064d7e2010-03-16 05:22:47 +00003952
3953 // FIXME: all the access-control diagnostics are positioned on the
3954 // field/base declaration. That's probably good; that said, the
3955 // user might reasonably want to know why the destructor is being
3956 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003957
Anders Carlssondee9a302009-11-17 04:44:12 +00003958 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003959 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003960 if (Field->isInvalidDecl())
3961 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003962
3963 // Don't destroy incomplete or zero-length arrays.
3964 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3965 continue;
3966
Anders Carlssondee9a302009-11-17 04:44:12 +00003967 QualType FieldType = Context.getBaseElementType(Field->getType());
3968
3969 const RecordType* RT = FieldType->getAs<RecordType>();
3970 if (!RT)
3971 continue;
3972
3973 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003974 if (FieldClassDecl->isInvalidDecl())
3975 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003976 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003977 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003978 // The destructor for an implicit anonymous union member is never invoked.
3979 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3980 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003981
Douglas Gregore71edda2010-07-01 22:47:18 +00003982 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003983 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003984 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003985 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003986 << Field->getDeclName()
3987 << FieldType);
3988
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003989 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003990 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003991 }
3992
John McCall1064d7e2010-03-16 05:22:47 +00003993 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3994
Anders Carlssondee9a302009-11-17 04:44:12 +00003995 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003996 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00003997 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00003998 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00003999
4000 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004001 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004002 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004003
John McCall1064d7e2010-03-16 05:22:47 +00004004 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004005 // If our base class is invalid, we probably can't get its dtor anyway.
4006 if (BaseClassDecl->isInvalidDecl())
4007 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004008 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004009 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004010
Douglas Gregore71edda2010-07-01 22:47:18 +00004011 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004012 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004013
4014 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004015 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004016 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004017 << Base.getType()
4018 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004019 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004020
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004021 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004022 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004023 }
4024
4025 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004026 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004027 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004028 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004029
4030 // Ignore direct virtual bases.
4031 if (DirectVirtualBases.count(RT))
4032 continue;
4033
John McCall1064d7e2010-03-16 05:22:47 +00004034 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004035 // If our base class is invalid, we probably can't get its dtor anyway.
4036 if (BaseClassDecl->isInvalidDecl())
4037 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004038 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004039 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004040
Douglas Gregore71edda2010-07-01 22:47:18 +00004041 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004042 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004043 if (CheckDestructorAccess(
4044 ClassDecl->getLocation(), Dtor,
4045 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004046 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004047 Context.getTypeDeclType(ClassDecl)) ==
4048 AR_accessible) {
4049 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004050 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004051 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4052 SourceRange(), DeclarationName(), 0);
4053 }
John McCall1064d7e2010-03-16 05:22:47 +00004054
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004055 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004056 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004057 }
4058}
4059
John McCall48871652010-08-21 09:40:31 +00004060void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004061 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004062 return;
Mike Stump11289f42009-09-09 15:08:12 +00004063
Mike Stump11289f42009-09-09 15:08:12 +00004064 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004065 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004066 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004067 DiagnoseUninitializedFields(*this, Constructor);
4068 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004069}
4070
Mike Stump11289f42009-09-09 15:08:12 +00004071bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004072 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004073 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4074 unsigned DiagID;
4075 AbstractDiagSelID SelID;
4076
4077 public:
4078 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4079 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004080
Craig Toppera798a9d2014-03-02 09:32:10 +00004081 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004082 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004083 if (SelID == -1)
4084 S.Diag(Loc, DiagID) << T;
4085 else
4086 S.Diag(Loc, DiagID) << SelID << T;
4087 }
4088 } Diagnoser(DiagID, SelID);
4089
4090 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004091}
4092
Anders Carlssoneabf7702009-08-27 00:13:57 +00004093bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004094 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004095 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004096 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004097
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004098 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004099 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004100
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004101 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004102 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004103 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004104 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004105
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004106 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004107 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004108 }
Mike Stump11289f42009-09-09 15:08:12 +00004109
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004110 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004111 if (!RT)
4112 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004113
John McCall67da35c2010-02-04 22:26:26 +00004114 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004115
John McCall02db245d2010-08-18 09:41:07 +00004116 // We can't answer whether something is abstract until it has a
4117 // definition. If it's currently being defined, we'll walk back
4118 // over all the declarations when we have a full definition.
4119 const CXXRecordDecl *Def = RD->getDefinition();
4120 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004121 return false;
4122
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004123 if (!RD->isAbstract())
4124 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004125
Douglas Gregorae298422012-05-04 17:09:59 +00004126 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004127 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004128
John McCall02db245d2010-08-18 09:41:07 +00004129 return true;
4130}
4131
4132void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4133 // Check if we've already emitted the list of pure virtual functions
4134 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004135 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004136 return;
Mike Stump11289f42009-09-09 15:08:12 +00004137
Richard Smithbc46e432013-07-22 02:56:56 +00004138 // If the diagnostic is suppressed, don't emit the notes. We're only
4139 // going to emit them once, so try to attach them to a diagnostic we're
4140 // actually going to show.
4141 if (Diags.isLastDiagnosticIgnored())
4142 return;
4143
Douglas Gregor4165bd62010-03-23 23:47:56 +00004144 CXXFinalOverriderMap FinalOverriders;
4145 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004146
Anders Carlssona2f74f32010-06-03 01:00:02 +00004147 // Keep a set of seen pure methods so we won't diagnose the same method
4148 // more than once.
4149 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4150
Douglas Gregor4165bd62010-03-23 23:47:56 +00004151 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4152 MEnd = FinalOverriders.end();
4153 M != MEnd;
4154 ++M) {
4155 for (OverridingMethods::iterator SO = M->second.begin(),
4156 SOEnd = M->second.end();
4157 SO != SOEnd; ++SO) {
4158 // C++ [class.abstract]p4:
4159 // A class is abstract if it contains or inherits at least one
4160 // pure virtual function for which the final overrider is pure
4161 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004162
Douglas Gregor4165bd62010-03-23 23:47:56 +00004163 //
4164 if (SO->second.size() != 1)
4165 continue;
4166
4167 if (!SO->second.front().Method->isPure())
4168 continue;
4169
Anders Carlssona2f74f32010-06-03 01:00:02 +00004170 if (!SeenPureMethods.insert(SO->second.front().Method))
4171 continue;
4172
Douglas Gregor4165bd62010-03-23 23:47:56 +00004173 Diag(SO->second.front().Method->getLocation(),
4174 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004175 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004176 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004177 }
4178
4179 if (!PureVirtualClassDiagSet)
4180 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4181 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004182}
4183
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004184namespace {
John McCall02db245d2010-08-18 09:41:07 +00004185struct AbstractUsageInfo {
4186 Sema &S;
4187 CXXRecordDecl *Record;
4188 CanQualType AbstractType;
4189 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004190
John McCall02db245d2010-08-18 09:41:07 +00004191 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4192 : S(S), Record(Record),
4193 AbstractType(S.Context.getCanonicalType(
4194 S.Context.getTypeDeclType(Record))),
4195 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004196
John McCall02db245d2010-08-18 09:41:07 +00004197 void DiagnoseAbstractType() {
4198 if (Invalid) return;
4199 S.DiagnoseAbstractType(Record);
4200 Invalid = true;
4201 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004202
John McCall02db245d2010-08-18 09:41:07 +00004203 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4204};
4205
4206struct CheckAbstractUsage {
4207 AbstractUsageInfo &Info;
4208 const NamedDecl *Ctx;
4209
4210 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4211 : Info(Info), Ctx(Ctx) {}
4212
4213 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4214 switch (TL.getTypeLocClass()) {
4215#define ABSTRACT_TYPELOC(CLASS, PARENT)
4216#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004217 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004218#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004219 }
John McCall02db245d2010-08-18 09:41:07 +00004220 }
Mike Stump11289f42009-09-09 15:08:12 +00004221
John McCall02db245d2010-08-18 09:41:07 +00004222 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004223 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004224 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4225 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004226 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004227
4228 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004229 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004230 }
John McCall02db245d2010-08-18 09:41:07 +00004231 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004232
John McCall02db245d2010-08-18 09:41:07 +00004233 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4234 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4235 }
Mike Stump11289f42009-09-09 15:08:12 +00004236
John McCall02db245d2010-08-18 09:41:07 +00004237 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4238 // Visit the type parameters from a permissive context.
4239 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4240 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4241 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4242 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4243 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4244 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004245 }
John McCall02db245d2010-08-18 09:41:07 +00004246 }
Mike Stump11289f42009-09-09 15:08:12 +00004247
John McCall02db245d2010-08-18 09:41:07 +00004248 // Visit pointee types from a permissive context.
4249#define CheckPolymorphic(Type) \
4250 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4251 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4252 }
4253 CheckPolymorphic(PointerTypeLoc)
4254 CheckPolymorphic(ReferenceTypeLoc)
4255 CheckPolymorphic(MemberPointerTypeLoc)
4256 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004257 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004258
John McCall02db245d2010-08-18 09:41:07 +00004259 /// Handle all the types we haven't given a more specific
4260 /// implementation for above.
4261 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4262 // Every other kind of type that we haven't called out already
4263 // that has an inner type is either (1) sugar or (2) contains that
4264 // inner type in some way as a subobject.
4265 if (TypeLoc Next = TL.getNextTypeLoc())
4266 return Visit(Next, Sel);
4267
4268 // If there's no inner type and we're in a permissive context,
4269 // don't diagnose.
4270 if (Sel == Sema::AbstractNone) return;
4271
4272 // Check whether the type matches the abstract type.
4273 QualType T = TL.getType();
4274 if (T->isArrayType()) {
4275 Sel = Sema::AbstractArrayType;
4276 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004277 }
John McCall02db245d2010-08-18 09:41:07 +00004278 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4279 if (CT != Info.AbstractType) return;
4280
4281 // It matched; do some magic.
4282 if (Sel == Sema::AbstractArrayType) {
4283 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4284 << T << TL.getSourceRange();
4285 } else {
4286 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4287 << Sel << T << TL.getSourceRange();
4288 }
4289 Info.DiagnoseAbstractType();
4290 }
4291};
4292
4293void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4294 Sema::AbstractDiagSelID Sel) {
4295 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4296}
4297
4298}
4299
4300/// Check for invalid uses of an abstract type in a method declaration.
4301static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4302 CXXMethodDecl *MD) {
4303 // No need to do the check on definitions, which require that
4304 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004305 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004306 return;
4307
4308 // For safety's sake, just ignore it if we don't have type source
4309 // information. This should never happen for non-implicit methods,
4310 // but...
4311 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4312 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4313}
4314
4315/// Check for invalid uses of an abstract type within a class definition.
4316static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4317 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004318 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004319 if (D->isImplicit()) continue;
4320
4321 // Methods and method templates.
4322 if (isa<CXXMethodDecl>(D)) {
4323 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4324 } else if (isa<FunctionTemplateDecl>(D)) {
4325 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4326 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4327
4328 // Fields and static variables.
4329 } else if (isa<FieldDecl>(D)) {
4330 FieldDecl *FD = cast<FieldDecl>(D);
4331 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4332 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4333 } else if (isa<VarDecl>(D)) {
4334 VarDecl *VD = cast<VarDecl>(D);
4335 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4336 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4337
4338 // Nested classes and class templates.
4339 } else if (isa<CXXRecordDecl>(D)) {
4340 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4341 } else if (isa<ClassTemplateDecl>(D)) {
4342 CheckAbstractClassUsage(Info,
4343 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4344 }
4345 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004346}
4347
Douglas Gregorc99f1552009-12-03 18:33:45 +00004348/// \brief Perform semantic checks on a class definition that has been
4349/// completing, introducing implicitly-declared members, checking for
4350/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004351void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004352 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004353 return;
4354
John McCall02db245d2010-08-18 09:41:07 +00004355 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4356 AbstractUsageInfo Info(*this, Record);
4357 CheckAbstractClassUsage(Info, Record);
4358 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004359
4360 // If this is not an aggregate type and has no user-declared constructor,
4361 // complain about any non-static data members of reference or const scalar
4362 // type, since they will never get initializers.
4363 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004364 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4365 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004366 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004367 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004368 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004369 continue;
4370
Douglas Gregor454a5b62010-04-15 00:00:53 +00004371 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004372 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004373 if (!Complained) {
4374 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4375 << Record->getTagKind() << Record;
4376 Complained = true;
4377 }
4378
4379 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4380 << F->getType()->isReferenceType()
4381 << F->getDeclName();
4382 }
4383 }
4384 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004385
Anders Carlssone771e762011-01-25 18:08:22 +00004386 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004387 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004388
4389 if (Record->getIdentifier()) {
4390 // C++ [class.mem]p13:
4391 // If T is the name of a class, then each of the following shall have a
4392 // name different from T:
4393 // - every member of every anonymous union that is a member of class T.
4394 //
4395 // C++ [class.mem]p14:
4396 // In addition, if class T has a user-declared constructor (12.1), every
4397 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004398 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4399 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4400 ++I) {
4401 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004402 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4403 isa<IndirectFieldDecl>(D)) {
4404 Diag(D->getLocation(), diag::err_member_name_of_class)
4405 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004406 break;
4407 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004408 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004409 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004410
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004411 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004412 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004413 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004414 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004415 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4416 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4417 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004418
David Majnemera5433082013-10-18 00:33:31 +00004419 if (Record->isAbstract()) {
4420 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4421 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4422 << FA->isSpelledAsSealed();
4423 DiagnoseAbstractType(Record);
4424 }
David Blaikie348df502012-09-21 03:21:07 +00004425 }
4426
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004427 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004428 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004429 // See if a method overloads virtual methods in a base
4430 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004431 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004432 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004433
4434 // Check whether the explicitly-defaulted special members are valid.
4435 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004436 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004437
4438 // For an explicitly defaulted or deleted special member, we defer
4439 // determining triviality until the class is complete. That time is now!
4440 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004441 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004442 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004443 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004444
4445 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004446 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004447 }
4448 }
4449 }
4450 }
4451
4452 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4453 // function that is not a constructor declares that member function to be
4454 // const. [...] The class of which that function is a member shall be
4455 // a literal type.
4456 //
4457 // If the class has virtual bases, any constexpr members will already have
4458 // been diagnosed by the checks performed on the member declaration, so
4459 // suppress this (less useful) diagnostic.
4460 //
4461 // We delay this until we know whether an explicitly-defaulted (or deleted)
4462 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004463 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004464 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004465 for (const auto *M : Record->methods()) {
4466 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004467 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 Kyrtzidis7272d9c2011-02-03 18:01:15 +00004486 }
4487 }
Sebastian Redl08905022011-02-05 19:23:19 +00004488
John McCall95833f32014-02-27 20:30:49 +00004489 // ms_struct is a request to use the same ABI rules as MSVC. Check
4490 // whether this class uses any C++ features that are implemented
4491 // completely differently in MSVC, and if so, emit a diagnostic.
4492 // That diagnostic defaults to an error, but we allow projects to
4493 // map it down to a warning (or ignore it). It's a fairly common
4494 // practice among users of the ms_struct pragma to mass-annotate
4495 // headers, sweeping up a bunch of types that the project doesn't
4496 // really rely on MSVC-compatible layout for. We must therefore
4497 // support "ms_struct except for C++ stuff" as a secondary ABI.
4498 if (Record->isMsStruct(Context) &&
4499 (Record->isPolymorphic() || Record->getNumBases())) {
4500 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004501 }
4502
Richard Smithc2bc61b2013-03-18 21:12:30 +00004503 // Declare inheriting constructors. We do this eagerly here because:
4504 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004505 // constructors from different classes.
4506 // - The lazy declaration of the other implicit constructors is so as to not
4507 // waste space and performance on classes that are not meant to be
4508 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004509 // have inheriting constructors.
4510 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004511}
4512
Richard Smith41c35d62013-11-27 03:39:20 +00004513/// Look up the special member function that would be called by a special
4514/// member function for a subobject of class type.
4515///
4516/// \param Class The class type of the subobject.
4517/// \param CSM The kind of special member function.
4518/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4519/// \param ConstRHS True if this is a copy operation with a const object
4520/// on its RHS, that is, if the argument to the outer special member
4521/// function is 'const' and this is not a field marked 'mutable'.
4522static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4523 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4524 unsigned FieldQuals, bool ConstRHS) {
4525 unsigned LHSQuals = 0;
4526 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4527 LHSQuals = FieldQuals;
4528
4529 unsigned RHSQuals = FieldQuals;
4530 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4531 RHSQuals = 0;
4532 else if (ConstRHS)
4533 RHSQuals |= Qualifiers::Const;
4534
4535 return S.LookupSpecialMember(Class, CSM,
4536 RHSQuals & Qualifiers::Const,
4537 RHSQuals & Qualifiers::Volatile,
4538 false,
4539 LHSQuals & Qualifiers::Const,
4540 LHSQuals & Qualifiers::Volatile);
4541}
4542
Richard Smithb5800092012-06-10 05:43:50 +00004543/// Is the special member function which would be selected to perform the
4544/// specified operation on the specified class type a constexpr constructor?
4545static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4546 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004547 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004548 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004549 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004550 if (!SMOR || !SMOR->getMethod())
4551 // A constructor we wouldn't select can't be "involved in initializing"
4552 // anything.
4553 return true;
4554 return SMOR->getMethod()->isConstexpr();
4555}
4556
4557/// Determine whether the specified special member function would be constexpr
4558/// if it were implicitly defined.
4559static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4560 Sema::CXXSpecialMember CSM,
4561 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004562 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004563 return false;
4564
4565 // C++11 [dcl.constexpr]p4:
4566 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004567 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004568 switch (CSM) {
4569 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004570 // Since default constructor lookup is essentially trivial (and cannot
4571 // involve, for instance, template instantiation), we compute whether a
4572 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4573 //
4574 // This is important for performance; we need to know whether the default
4575 // constructor is constexpr to determine whether the type is a literal type.
4576 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4577
Richard Smithb5800092012-06-10 05:43:50 +00004578 case Sema::CXXCopyConstructor:
4579 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004580 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004581 break;
4582
4583 case Sema::CXXCopyAssignment:
4584 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004585 if (!S.getLangOpts().CPlusPlus1y)
4586 return false;
4587 // In C++1y, we need to perform overload resolution.
4588 Ctor = false;
4589 break;
4590
Richard Smithb5800092012-06-10 05:43:50 +00004591 case Sema::CXXDestructor:
4592 case Sema::CXXInvalid:
4593 return false;
4594 }
4595
4596 // -- if the class is a non-empty union, or for each non-empty anonymous
4597 // union member of a non-union class, exactly one non-static data member
4598 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004599 //
4600 // If we squint, this is guaranteed, since exactly one non-static data member
4601 // will be initialized (if the constructor isn't deleted), we just don't know
4602 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004603 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004604 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004605
4606 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004607 if (Ctor && ClassDecl->getNumVBases())
4608 return false;
4609
4610 // C++1y [class.copy]p26:
4611 // -- [the class] is a literal type, and
4612 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004613 return false;
4614
4615 // -- every constructor involved in initializing [...] base class
4616 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004617 // -- the assignment operator selected to copy/move each direct base
4618 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004619 for (const auto &B : ClassDecl->bases()) {
4620 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004621 if (!BaseType) continue;
4622
4623 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004624 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004625 return false;
4626 }
4627
4628 // -- every constructor involved in initializing non-static data members
4629 // [...] shall be a constexpr constructor;
4630 // -- every non-static data member and base class sub-object shall be
4631 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004632 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004633 // thereof), the assignment operator selected to copy/move that member is
4634 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004635 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004636 if (F->isInvalidDecl())
4637 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004638 QualType BaseType = S.Context.getBaseElementType(F->getType());
4639 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004640 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004641 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4642 BaseType.getCVRQualifiers(),
4643 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004644 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004645 }
4646 }
4647
4648 // All OK, it's constexpr!
4649 return true;
4650}
4651
Richard Smithd3b5c9082012-07-27 04:22:15 +00004652static Sema::ImplicitExceptionSpecification
4653computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4654 switch (S.getSpecialMember(MD)) {
4655 case Sema::CXXDefaultConstructor:
4656 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4657 case Sema::CXXCopyConstructor:
4658 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4659 case Sema::CXXCopyAssignment:
4660 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4661 case Sema::CXXMoveConstructor:
4662 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4663 case Sema::CXXMoveAssignment:
4664 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4665 case Sema::CXXDestructor:
4666 return S.ComputeDefaultedDtorExceptionSpec(MD);
4667 case Sema::CXXInvalid:
4668 break;
4669 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004670 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4671 "only special members have implicit exception specs");
4672 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004673}
4674
Reid Kleckner78af0702013-08-27 23:08:25 +00004675static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4676 CXXMethodDecl *MD) {
4677 FunctionProtoType::ExtProtoInfo EPI;
4678
4679 // Build an exception specification pointing back at this member.
4680 EPI.ExceptionSpecType = EST_Unevaluated;
4681 EPI.ExceptionSpecDecl = MD;
4682
4683 // Set the calling convention to the default for C++ instance methods.
4684 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4685 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4686 /*IsCXXMethod=*/true));
4687 return EPI;
4688}
4689
Richard Smithd3b5c9082012-07-27 04:22:15 +00004690void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4691 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4692 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4693 return;
4694
Richard Smith7f782272012-07-30 23:48:14 +00004695 // Evaluate the exception specification.
4696 ImplicitExceptionSpecification ExceptSpec =
4697 computeImplicitExceptionSpec(*this, Loc, MD);
4698
Richard Smith564417a2014-03-20 21:47:22 +00004699 FunctionProtoType::ExtProtoInfo EPI;
4700 ExceptSpec.getEPI(EPI);
4701
Richard Smith7f782272012-07-30 23:48:14 +00004702 // Update the type of the special member to use it.
Richard Smith564417a2014-03-20 21:47:22 +00004703 UpdateExceptionSpec(MD, EPI);
Richard Smith7f782272012-07-30 23:48:14 +00004704
4705 // A user-provided destructor can be defined outside the class. When that
4706 // happens, be sure to update the exception specification on both
4707 // declarations.
4708 const FunctionProtoType *CanonicalFPT =
4709 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4710 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith564417a2014-03-20 21:47:22 +00004711 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004712}
4713
Richard Smithb9e90b12012-05-15 04:39:51 +00004714void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4715 CXXRecordDecl *RD = MD->getParent();
4716 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004717
Richard Smithb9e90b12012-05-15 04:39:51 +00004718 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4719 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004720
4721 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004722 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004723 bool First = MD == MD->getCanonicalDecl();
4724
4725 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004726
4727 // C++11 [dcl.fct.def.default]p1:
4728 // A function that is explicitly defaulted shall
4729 // -- be a special member function (checked elsewhere),
4730 // -- have the same type (except for ref-qualifiers, and except that a
4731 // copy operation can take a non-const reference) as an implicit
4732 // declaration, and
4733 // -- not have default arguments.
4734 unsigned ExpectedParams = 1;
4735 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4736 ExpectedParams = 0;
4737 if (MD->getNumParams() != ExpectedParams) {
4738 // This also checks for default arguments: a copy or move constructor with a
4739 // default argument is classified as a default constructor, and assignment
4740 // operations and destructors can't have default arguments.
4741 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4742 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004743 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004744 } else if (MD->isVariadic()) {
4745 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4746 << CSM << MD->getSourceRange();
4747 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004748 }
4749
Richard Smithb9e90b12012-05-15 04:39:51 +00004750 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004751
Richard Smithb5800092012-06-10 05:43:50 +00004752 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004753 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004754 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004755 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004756 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004757
Richard Smithb9e90b12012-05-15 04:39:51 +00004758 QualType ReturnType = Context.VoidTy;
4759 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4760 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004761 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004762 QualType ExpectedReturnType =
4763 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4764 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4765 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4766 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4767 HadError = true;
4768 }
4769
4770 // A defaulted special member cannot have cv-qualifiers.
4771 if (Type->getTypeQuals()) {
4772 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004773 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004774 HadError = true;
4775 }
4776 }
4777
4778 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004779 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004780 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004781 if (ExpectedParams && ArgType->isReferenceType()) {
4782 // Argument must be reference to possibly-const T.
4783 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004784 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004785
4786 if (ReferentType.isVolatileQualified()) {
4787 Diag(MD->getLocation(),
4788 diag::err_defaulted_special_member_volatile_param) << CSM;
4789 HadError = true;
4790 }
4791
Richard Smithb5800092012-06-10 05:43:50 +00004792 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004793 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4794 Diag(MD->getLocation(),
4795 diag::err_defaulted_special_member_copy_const_param)
4796 << (CSM == CXXCopyAssignment);
4797 // FIXME: Explain why this special member can't be const.
4798 } else {
4799 Diag(MD->getLocation(),
4800 diag::err_defaulted_special_member_move_const_param)
4801 << (CSM == CXXMoveAssignment);
4802 }
4803 HadError = true;
4804 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004805 } else if (ExpectedParams) {
4806 // A copy assignment operator can take its argument by value, but a
4807 // defaulted one cannot.
4808 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004809 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004810 HadError = true;
4811 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004812
Richard Smithcc36f692011-12-22 02:22:31 +00004813 // C++11 [dcl.fct.def.default]p2:
4814 // An explicitly-defaulted function may be declared constexpr only if it
4815 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004816 // Do not apply this rule to members of class templates, since core issue 1358
4817 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004818 // functions which cannot be constexpr (for non-constructors in C++11 and for
4819 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004820 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4821 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004822 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4823 : isa<CXXConstructorDecl>(MD)) &&
4824 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004825 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4826 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004827 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004828 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004829 }
Richard Smithbd305122012-12-11 01:14:52 +00004830
Richard Smithcc36f692011-12-22 02:22:31 +00004831 // and may have an explicit exception-specification only if it is compatible
4832 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004833 if (Type->hasExceptionSpec()) {
4834 // Delay the check if this is the first declaration of the special member,
4835 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004836 if (First) {
4837 // If the exception specification needs to be instantiated, do so now,
4838 // before we clobber it with an EST_Unevaluated specification below.
4839 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4840 InstantiateExceptionSpec(MD->getLocStart(), MD);
4841 Type = MD->getType()->getAs<FunctionProtoType>();
4842 }
Richard Smithbd305122012-12-11 01:14:52 +00004843 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004844 } else
Richard Smithbd305122012-12-11 01:14:52 +00004845 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4846 }
Richard Smithcc36f692011-12-22 02:22:31 +00004847
4848 // If a function is explicitly defaulted on its first declaration,
4849 if (First) {
4850 // -- it is implicitly considered to be constexpr if the implicit
4851 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004852 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004853
Richard Smithb9e90b12012-05-15 04:39:51 +00004854 // -- it is implicitly considered to have the same exception-specification
4855 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004856 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4857 EPI.ExceptionSpecType = EST_Unevaluated;
4858 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004859 MD->setType(Context.getFunctionType(ReturnType,
4860 ArrayRef<QualType>(&ArgType,
4861 ExpectedParams),
4862 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004863 }
4864
Richard Smithb9e90b12012-05-15 04:39:51 +00004865 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004866 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004867 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004868 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004869 // C++11 [dcl.fct.def.default]p4:
4870 // [For a] user-provided explicitly-defaulted function [...] if such a
4871 // function is implicitly defined as deleted, the program is ill-formed.
4872 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00004873 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00004874 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004875 }
4876 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004877
Richard Smithb9e90b12012-05-15 04:39:51 +00004878 if (HadError)
4879 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004880}
4881
Richard Smithbd305122012-12-11 01:14:52 +00004882/// Check whether the exception specification provided for an
4883/// explicitly-defaulted special member matches the exception specification
4884/// that would have been generated for an implicit special member, per
4885/// C++11 [dcl.fct.def.default]p2.
4886void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4887 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4888 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004889 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4890 /*IsCXXMethod=*/true);
4891 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004892 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4893 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004894 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004895
4896 // Ensure that it matches.
4897 CheckEquivalentExceptionSpec(
4898 PDiag(diag::err_incorrect_defaulted_exception_spec)
4899 << getSpecialMember(MD), PDiag(),
4900 ImplicitType, SourceLocation(),
4901 SpecifiedType, MD->getLocation());
4902}
4903
Alp Tokerae3a9442013-10-18 05:54:19 +00004904void Sema::CheckDelayedMemberExceptionSpecs() {
4905 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4906 2> Checks;
4907 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00004908
Alp Tokerae3a9442013-10-18 05:54:19 +00004909 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4910 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4911
4912 // Perform any deferred checking of exception specifications for virtual
4913 // destructors.
4914 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4915 const CXXDestructorDecl *Dtor = Checks[i].first;
4916 assert(!Dtor->getParent()->isDependentType() &&
4917 "Should not ever add destructors of templates into the list.");
4918 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4919 }
4920
4921 // Check that any explicitly-defaulted methods have exception specifications
4922 // compatible with their implicit exception specifications.
4923 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4924 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4925 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00004926}
4927
Richard Smithd951a1d2012-02-18 02:02:13 +00004928namespace {
4929struct SpecialMemberDeletionInfo {
4930 Sema &S;
4931 CXXMethodDecl *MD;
4932 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004933 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004934
4935 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00004936 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00004937 SourceLocation Loc;
4938
4939 bool AllFieldsAreConst;
4940
4941 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004942 Sema::CXXSpecialMember CSM, bool Diagnose)
4943 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004944 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00004945 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00004946 AllFieldsAreConst(true) {
4947 switch (CSM) {
4948 case Sema::CXXDefaultConstructor:
4949 case Sema::CXXCopyConstructor:
4950 IsConstructor = true;
4951 break;
4952 case Sema::CXXMoveConstructor:
4953 IsConstructor = true;
4954 IsMove = true;
4955 break;
4956 case Sema::CXXCopyAssignment:
4957 IsAssignment = true;
4958 break;
4959 case Sema::CXXMoveAssignment:
4960 IsAssignment = true;
4961 IsMove = true;
4962 break;
4963 case Sema::CXXDestructor:
4964 break;
4965 case Sema::CXXInvalid:
4966 llvm_unreachable("invalid special member kind");
4967 }
4968
4969 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00004970 if (const ReferenceType *RT =
4971 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
4972 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00004973 }
4974 }
4975
4976 bool inUnion() const { return MD->getParent()->isUnion(); }
4977
4978 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00004979 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00004980 unsigned Quals, bool IsMutable) {
4981 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
4982 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00004983 }
4984
Richard Smith852265f2012-03-30 20:53:28 +00004985 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00004986
Richard Smith852265f2012-03-30 20:53:28 +00004987 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00004988 bool shouldDeleteForField(FieldDecl *FD);
4989 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00004990
Richard Smithaf136f82012-07-18 03:51:16 +00004991 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4992 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00004993 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4994 Sema::SpecialMemberOverloadResult *SMOR,
4995 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00004996
4997 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00004998};
4999}
5000
John McCalld4274212012-04-09 20:53:23 +00005001/// Is the given special member inaccessible when used on the given
5002/// sub-object.
5003bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5004 CXXMethodDecl *target) {
5005 /// If we're operating on a base class, the object type is the
5006 /// type of this special member.
5007 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005008 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005009 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5010 objectTy = S.Context.getTypeDeclType(MD->getParent());
5011 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5012
5013 // If we're operating on a field, the object type is the type of the field.
5014 } else {
5015 objectTy = S.Context.getTypeDeclType(target->getParent());
5016 }
5017
5018 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5019}
5020
Richard Smith852265f2012-03-30 20:53:28 +00005021/// Check whether we should delete a special member due to the implicit
5022/// definition containing a call to a special member of a subobject.
5023bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5024 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5025 bool IsDtorCallInCtor) {
5026 CXXMethodDecl *Decl = SMOR->getMethod();
5027 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5028
5029 int DiagKind = -1;
5030
5031 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5032 DiagKind = !Decl ? 0 : 1;
5033 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5034 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005035 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005036 DiagKind = 3;
5037 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5038 !Decl->isTrivial()) {
5039 // A member of a union must have a trivial corresponding special member.
5040 // As a weird special case, a destructor call from a union's constructor
5041 // must be accessible and non-deleted, but need not be trivial. Such a
5042 // destructor is never actually called, but is semantically checked as
5043 // if it were.
5044 DiagKind = 4;
5045 }
5046
5047 if (DiagKind == -1)
5048 return false;
5049
5050 if (Diagnose) {
5051 if (Field) {
5052 S.Diag(Field->getLocation(),
5053 diag::note_deleted_special_member_class_subobject)
5054 << CSM << MD->getParent() << /*IsField*/true
5055 << Field << DiagKind << IsDtorCallInCtor;
5056 } else {
5057 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5058 S.Diag(Base->getLocStart(),
5059 diag::note_deleted_special_member_class_subobject)
5060 << CSM << MD->getParent() << /*IsField*/false
5061 << Base->getType() << DiagKind << IsDtorCallInCtor;
5062 }
5063
5064 if (DiagKind == 1)
5065 S.NoteDeletedFunction(Decl);
5066 // FIXME: Explain inaccessibility if DiagKind == 3.
5067 }
5068
5069 return true;
5070}
5071
Richard Smith921bd202012-02-26 09:11:52 +00005072/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005073/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005074bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005075 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005076 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005077 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005078
5079 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005080 // -- any direct or virtual base class, or non-static data member with no
5081 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005082 // either M has no default constructor or overload resolution as applied
5083 // to M's default constructor results in an ambiguity or in a function
5084 // that is deleted or inaccessible
5085 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5086 // -- a direct or virtual base class B that cannot be copied/moved because
5087 // overload resolution, as applied to B's corresponding special member,
5088 // results in an ambiguity or a function that is deleted or inaccessible
5089 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005090 // C++11 [class.dtor]p5:
5091 // -- any direct or virtual base class [...] has a type with a destructor
5092 // that is deleted or inaccessible
5093 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005094 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005095 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5096 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005097 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005098
Richard Smith852265f2012-03-30 20:53:28 +00005099 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5100 // -- any direct or virtual base class or non-static data member has a
5101 // type with a destructor that is deleted or inaccessible
5102 if (IsConstructor) {
5103 Sema::SpecialMemberOverloadResult *SMOR =
5104 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5105 false, false, false, false, false);
5106 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5107 return true;
5108 }
5109
Richard Smith921bd202012-02-26 09:11:52 +00005110 return false;
5111}
5112
5113/// Check whether we should delete a special member function due to the class
5114/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005115bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005116 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005117 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005118}
5119
5120/// Check whether we should delete a special member function due to the class
5121/// having a particular non-static data member.
5122bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5123 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5124 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5125
5126 if (CSM == Sema::CXXDefaultConstructor) {
5127 // For a default constructor, all references must be initialized in-class
5128 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005129 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5130 if (Diagnose)
5131 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5132 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005133 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005134 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005135 // C++11 [class.ctor]p5: any non-variant non-static data member of
5136 // const-qualified type (or array thereof) with no
5137 // brace-or-equal-initializer does not have a user-provided default
5138 // constructor.
5139 if (!inUnion() && FieldType.isConstQualified() &&
5140 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005141 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5142 if (Diagnose)
5143 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005144 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005145 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005146 }
5147
5148 if (inUnion() && !FieldType.isConstQualified())
5149 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005150 } else if (CSM == Sema::CXXCopyConstructor) {
5151 // For a copy constructor, data members must not be of rvalue reference
5152 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005153 if (FieldType->isRValueReferenceType()) {
5154 if (Diagnose)
5155 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5156 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005157 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005158 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005159 } else if (IsAssignment) {
5160 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005161 if (FieldType->isReferenceType()) {
5162 if (Diagnose)
5163 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5164 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005165 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005166 }
5167 if (!FieldRecord && FieldType.isConstQualified()) {
5168 // C++11 [class.copy]p23:
5169 // -- a non-static data member of const non-class type (or array thereof)
5170 if (Diagnose)
5171 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005172 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005173 return true;
5174 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005175 }
5176
5177 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005178 // Some additional restrictions exist on the variant members.
5179 if (!inUnion() && FieldRecord->isUnion() &&
5180 FieldRecord->isAnonymousStructOrUnion()) {
5181 bool AllVariantFieldsAreConst = true;
5182
Richard Smith5704fe82012-03-29 19:00:10 +00005183 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005184 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005185 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005186
5187 if (!UnionFieldType.isConstQualified())
5188 AllVariantFieldsAreConst = false;
5189
Richard Smith921bd202012-02-26 09:11:52 +00005190 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5191 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005192 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005193 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005194 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005195 }
5196
5197 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005198 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005199 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005200 if (Diagnose)
5201 S.Diag(FieldRecord->getLocation(),
5202 diag::note_deleted_default_ctor_all_const)
5203 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005204 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005205 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005206
Richard Smith5704fe82012-03-29 19:00:10 +00005207 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005208 // This is technically non-conformant, but sanity demands it.
5209 return false;
5210 }
5211
Richard Smithaf136f82012-07-18 03:51:16 +00005212 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5213 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005214 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005215 }
5216
5217 return false;
5218}
5219
5220/// C++11 [class.ctor] p5:
5221/// A defaulted default constructor for a class X is defined as deleted if
5222/// X is a union and all of its variant members are of const-qualified type.
5223bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005224 // This is a silly definition, because it gives an empty union a deleted
5225 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005226 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005227 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005228 if (Diagnose)
5229 S.Diag(MD->getParent()->getLocation(),
5230 diag::note_deleted_default_ctor_all_const)
5231 << MD->getParent() << /*not anonymous union*/0;
5232 return true;
5233 }
5234 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005235}
5236
5237/// Determine whether a defaulted special member function should be defined as
5238/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5239/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005240bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5241 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005242 if (MD->isInvalidDecl())
5243 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005244 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005245 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005246 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005247 return false;
5248
Richard Smithd951a1d2012-02-18 02:02:13 +00005249 // C++11 [expr.lambda.prim]p19:
5250 // The closure type associated with a lambda-expression has a
5251 // deleted (8.4.3) default constructor and a deleted copy
5252 // assignment operator.
5253 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005254 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5255 if (Diagnose)
5256 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005257 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005258 }
5259
Richard Smith6f1e2c62012-04-02 20:59:25 +00005260 // For an anonymous struct or union, the copy and assignment special members
5261 // will never be used, so skip the check. For an anonymous union declared at
5262 // namespace scope, the constructor and destructor are used.
5263 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5264 RD->isAnonymousStructOrUnion())
5265 return false;
5266
Richard Smith852265f2012-03-30 20:53:28 +00005267 // C++11 [class.copy]p7, p18:
5268 // If the class definition declares a move constructor or move assignment
5269 // operator, an implicitly declared copy constructor or copy assignment
5270 // operator is defined as deleted.
5271 if (MD->isImplicit() &&
5272 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5273 CXXMethodDecl *UserDeclaredMove = 0;
5274
5275 // In Microsoft mode, a user-declared move only causes the deletion of the
5276 // corresponding copy operation, not both copy operations.
5277 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005278 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005279 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005280
5281 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005282 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005283 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005284 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005285 break;
5286 }
5287 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005288 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005289 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005290 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005291 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005292
5293 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005294 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005295 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005296 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005297 break;
5298 }
5299 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005300 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005301 }
5302
5303 if (UserDeclaredMove) {
5304 Diag(UserDeclaredMove->getLocation(),
5305 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005306 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005307 << UserDeclaredMove->isMoveAssignmentOperator();
5308 return true;
5309 }
5310 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005311
Richard Smith6f1e2c62012-04-02 20:59:25 +00005312 // Do access control from the special member function
5313 ContextRAII MethodContext(*this, MD);
5314
Richard Smith921bd202012-02-26 09:11:52 +00005315 // C++11 [class.dtor]p5:
5316 // -- for a virtual destructor, lookup of the non-array deallocation function
5317 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005318 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005319 FunctionDecl *OperatorDelete = 0;
5320 DeclarationName Name =
5321 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5322 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005323 OperatorDelete, false)) {
5324 if (Diagnose)
5325 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005326 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005327 }
Richard Smith921bd202012-02-26 09:11:52 +00005328 }
5329
Richard Smith852265f2012-03-30 20:53:28 +00005330 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005331
Aaron Ballman574705e2014-03-13 15:41:46 +00005332 for (auto &BI : RD->bases())
5333 if (!BI.isVirtual() &&
5334 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005335 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005336
Richard Smithd1627032013-07-22 18:06:23 +00005337 // Per DR1611, do not consider virtual bases of constructors of abstract
5338 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005339 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005340 for (auto &BI : RD->vbases())
5341 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005342 return true;
5343 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005344
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005345 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005346 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005347 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005348 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005349
Richard Smithd951a1d2012-02-18 02:02:13 +00005350 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005351 return true;
5352
5353 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005354}
5355
Richard Smith92f241f2012-12-08 02:53:02 +00005356/// Perform lookup for a special member of the specified kind, and determine
5357/// whether it is trivial. If the triviality can be determined without the
5358/// lookup, skip it. This is intended for use when determining whether a
5359/// special member of a containing object is trivial, and thus does not ever
5360/// perform overload resolution for default constructors.
5361///
5362/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5363/// member that was most likely to be intended to be trivial, if any.
5364static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5365 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005366 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005367 if (Selected)
5368 *Selected = 0;
5369
5370 switch (CSM) {
5371 case Sema::CXXInvalid:
5372 llvm_unreachable("not a special member");
5373
5374 case Sema::CXXDefaultConstructor:
5375 // C++11 [class.ctor]p5:
5376 // A default constructor is trivial if:
5377 // - all the [direct subobjects] have trivial default constructors
5378 //
5379 // Note, no overload resolution is performed in this case.
5380 if (RD->hasTrivialDefaultConstructor())
5381 return true;
5382
5383 if (Selected) {
5384 // If there's a default constructor which could have been trivial, dig it
5385 // out. Otherwise, if there's any user-provided default constructor, point
5386 // to that as an example of why there's not a trivial one.
5387 CXXConstructorDecl *DefCtor = 0;
5388 if (RD->needsImplicitDefaultConstructor())
5389 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005390 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005391 if (!CI->isDefaultConstructor())
5392 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005393 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005394 if (!DefCtor->isUserProvided())
5395 break;
5396 }
5397
5398 *Selected = DefCtor;
5399 }
5400
5401 return false;
5402
5403 case Sema::CXXDestructor:
5404 // C++11 [class.dtor]p5:
5405 // A destructor is trivial if:
5406 // - all the direct [subobjects] have trivial destructors
5407 if (RD->hasTrivialDestructor())
5408 return true;
5409
5410 if (Selected) {
5411 if (RD->needsImplicitDestructor())
5412 S.DeclareImplicitDestructor(RD);
5413 *Selected = RD->getDestructor();
5414 }
5415
5416 return false;
5417
5418 case Sema::CXXCopyConstructor:
5419 // C++11 [class.copy]p12:
5420 // A copy constructor is trivial if:
5421 // - the constructor selected to copy each direct [subobject] is trivial
5422 if (RD->hasTrivialCopyConstructor()) {
5423 if (Quals == Qualifiers::Const)
5424 // We must either select the trivial copy constructor or reach an
5425 // ambiguity; no need to actually perform overload resolution.
5426 return true;
5427 } else if (!Selected) {
5428 return false;
5429 }
5430 // In C++98, we are not supposed to perform overload resolution here, but we
5431 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5432 // cases like B as having a non-trivial copy constructor:
5433 // struct A { template<typename T> A(T&); };
5434 // struct B { mutable A a; };
5435 goto NeedOverloadResolution;
5436
5437 case Sema::CXXCopyAssignment:
5438 // C++11 [class.copy]p25:
5439 // A copy assignment operator is trivial if:
5440 // - the assignment operator selected to copy each direct [subobject] is
5441 // trivial
5442 if (RD->hasTrivialCopyAssignment()) {
5443 if (Quals == Qualifiers::Const)
5444 return true;
5445 } else if (!Selected) {
5446 return false;
5447 }
5448 // In C++98, we are not supposed to perform overload resolution here, but we
5449 // treat that as a language defect.
5450 goto NeedOverloadResolution;
5451
5452 case Sema::CXXMoveConstructor:
5453 case Sema::CXXMoveAssignment:
5454 NeedOverloadResolution:
5455 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005456 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005457
5458 // The standard doesn't describe how to behave if the lookup is ambiguous.
5459 // We treat it as not making the member non-trivial, just like the standard
5460 // mandates for the default constructor. This should rarely matter, because
5461 // the member will also be deleted.
5462 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5463 return true;
5464
5465 if (!SMOR->getMethod()) {
5466 assert(SMOR->getKind() ==
5467 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5468 return false;
5469 }
5470
5471 // We deliberately don't check if we found a deleted special member. We're
5472 // not supposed to!
5473 if (Selected)
5474 *Selected = SMOR->getMethod();
5475 return SMOR->getMethod()->isTrivial();
5476 }
5477
5478 llvm_unreachable("unknown special method kind");
5479}
5480
Benjamin Kramer3e350262013-02-15 12:30:38 +00005481static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005482 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005483 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005484 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005485
5486 // Look for constructor templates.
5487 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5488 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5489 if (CXXConstructorDecl *CD =
5490 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5491 return CD;
5492 }
5493
5494 return 0;
5495}
5496
5497/// The kind of subobject we are checking for triviality. The values of this
5498/// enumeration are used in diagnostics.
5499enum TrivialSubobjectKind {
5500 /// The subobject is a base class.
5501 TSK_BaseClass,
5502 /// The subobject is a non-static data member.
5503 TSK_Field,
5504 /// The object is actually the complete object.
5505 TSK_CompleteObject
5506};
5507
5508/// Check whether the special member selected for a given type would be trivial.
5509static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005510 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005511 Sema::CXXSpecialMember CSM,
5512 TrivialSubobjectKind Kind,
5513 bool Diagnose) {
5514 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5515 if (!SubRD)
5516 return true;
5517
5518 CXXMethodDecl *Selected;
5519 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Richard Smith41c35d62013-11-27 03:39:20 +00005520 ConstRHS, Diagnose ? &Selected : 0))
Richard Smith92f241f2012-12-08 02:53:02 +00005521 return true;
5522
5523 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005524 if (ConstRHS)
5525 SubType.addConst();
5526
Richard Smith92f241f2012-12-08 02:53:02 +00005527 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5528 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5529 << Kind << SubType.getUnqualifiedType();
5530 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5531 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5532 } else if (!Selected)
5533 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5534 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5535 else if (Selected->isUserProvided()) {
5536 if (Kind == TSK_CompleteObject)
5537 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5538 << Kind << SubType.getUnqualifiedType() << CSM;
5539 else {
5540 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5541 << Kind << SubType.getUnqualifiedType() << CSM;
5542 S.Diag(Selected->getLocation(), diag::note_declared_at);
5543 }
5544 } else {
5545 if (Kind != TSK_CompleteObject)
5546 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5547 << Kind << SubType.getUnqualifiedType() << CSM;
5548
5549 // Explain why the defaulted or deleted special member isn't trivial.
5550 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5551 }
5552 }
5553
5554 return false;
5555}
5556
5557/// Check whether the members of a class type allow a special member to be
5558/// trivial.
5559static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5560 Sema::CXXSpecialMember CSM,
5561 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005562 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005563 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5564 continue;
5565
5566 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5567
5568 // Pretend anonymous struct or union members are members of this class.
5569 if (FI->isAnonymousStructOrUnion()) {
5570 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5571 CSM, ConstArg, Diagnose))
5572 return false;
5573 continue;
5574 }
5575
5576 // C++11 [class.ctor]p5:
5577 // A default constructor is trivial if [...]
5578 // -- no non-static data member of its class has a
5579 // brace-or-equal-initializer
5580 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5581 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005582 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005583 return false;
5584 }
5585
5586 // Objective C ARC 4.3.5:
5587 // [...] nontrivally ownership-qualified types are [...] not trivially
5588 // default constructible, copy constructible, move constructible, copy
5589 // assignable, move assignable, or destructible [...]
5590 if (S.getLangOpts().ObjCAutoRefCount &&
5591 FieldType.hasNonTrivialObjCLifetime()) {
5592 if (Diagnose)
5593 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5594 << RD << FieldType.getObjCLifetime();
5595 return false;
5596 }
5597
Richard Smith41c35d62013-11-27 03:39:20 +00005598 bool ConstRHS = ConstArg && !FI->isMutable();
5599 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5600 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005601 return false;
5602 }
5603
5604 return true;
5605}
5606
5607/// Diagnose why the specified class does not have a trivial special member of
5608/// the given kind.
5609void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5610 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005611
Richard Smith41c35d62013-11-27 03:39:20 +00005612 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5613 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005614 TSK_CompleteObject, /*Diagnose*/true);
5615}
5616
5617/// Determine whether a defaulted or deleted special member function is trivial,
5618/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5619/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5620bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5621 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005622 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5623
5624 CXXRecordDecl *RD = MD->getParent();
5625
5626 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005627
Richard Smith2002bfe2013-11-04 02:02:27 +00005628 // C++11 [class.copy]p12, p25: [DR1593]
5629 // A [special member] is trivial if [...] its parameter-type-list is
5630 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005631 switch (CSM) {
5632 case CXXDefaultConstructor:
5633 case CXXDestructor:
5634 // Trivial default constructors and destructors cannot have parameters.
5635 break;
5636
5637 case CXXCopyConstructor:
5638 case CXXCopyAssignment: {
5639 // Trivial copy operations always have const, non-volatile parameter types.
5640 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005641 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005642 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5643 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5644 if (Diagnose)
5645 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5646 << Param0->getSourceRange() << Param0->getType()
5647 << Context.getLValueReferenceType(
5648 Context.getRecordType(RD).withConst());
5649 return false;
5650 }
5651 break;
5652 }
5653
5654 case CXXMoveConstructor:
5655 case CXXMoveAssignment: {
5656 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005657 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005658 const RValueReferenceType *RT =
5659 Param0->getType()->getAs<RValueReferenceType>();
5660 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5661 if (Diagnose)
5662 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5663 << Param0->getSourceRange() << Param0->getType()
5664 << Context.getRValueReferenceType(Context.getRecordType(RD));
5665 return false;
5666 }
5667 break;
5668 }
5669
5670 case CXXInvalid:
5671 llvm_unreachable("not a special member");
5672 }
5673
Richard Smith92f241f2012-12-08 02:53:02 +00005674 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5675 if (Diagnose)
5676 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5677 diag::note_nontrivial_default_arg)
5678 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5679 return false;
5680 }
5681 if (MD->isVariadic()) {
5682 if (Diagnose)
5683 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5684 return false;
5685 }
5686
5687 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5688 // A copy/move [constructor or assignment operator] is trivial if
5689 // -- the [member] selected to copy/move each direct base class subobject
5690 // is trivial
5691 //
5692 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5693 // A [default constructor or destructor] is trivial if
5694 // -- all the direct base classes have trivial [default constructors or
5695 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005696 for (const auto &BI : RD->bases())
5697 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005698 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005699 return false;
5700
5701 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5702 // A copy/move [constructor or assignment operator] for a class X is
5703 // trivial if
5704 // -- for each non-static data member of X that is of class type (or array
5705 // thereof), the constructor selected to copy/move that member is
5706 // trivial
5707 //
5708 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5709 // A [default constructor or destructor] is trivial if
5710 // -- for all of the non-static data members of its class that are of class
5711 // type (or array thereof), each such class has a trivial [default
5712 // constructor or destructor]
5713 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5714 return false;
5715
5716 // C++11 [class.dtor]p5:
5717 // A destructor is trivial if [...]
5718 // -- the destructor is not virtual
5719 if (CSM == CXXDestructor && MD->isVirtual()) {
5720 if (Diagnose)
5721 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5722 return false;
5723 }
5724
5725 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5726 // A [special member] for class X is trivial if [...]
5727 // -- class X has no virtual functions and no virtual base classes
5728 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5729 if (!Diagnose)
5730 return false;
5731
5732 if (RD->getNumVBases()) {
5733 // Check for virtual bases. We already know that the corresponding
5734 // member in all bases is trivial, so vbases must all be direct.
5735 CXXBaseSpecifier &BS = *RD->vbases_begin();
5736 assert(BS.isVirtual());
5737 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5738 return false;
5739 }
5740
5741 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005742 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005743 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 Kyrtzidis7272d9c2011-02-03 18:01:15 +00005757/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005758namespace {
5759 struct FindHiddenVirtualMethodData {
5760 Sema *S;
5761 CXXMethodDecl *Method;
5762 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005763 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005764 };
5765}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005766
David Blaikie282c92a2012-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 Kyrtzidis7272d9c2011-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 Lattner0e62c1c2011-07-23 10:55:15 +00005795 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005796 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005797 !Path.Decls.empty();
5798 Path.Decls = Path.Decls.slice(1)) {
5799 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005800 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005801 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-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 Blaikie282c92a2012-10-19 00:53:08 +00005811 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-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 Blaikie282c92a2012-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 Friedmanaf65120b2013-09-05 23:51:03 +00005833/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005834/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005835void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5836 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005837 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-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 Friedmanaf65120b2013-09-05 23:51:03 +00005849 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-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 Blaikie282c92a2012-10-19 00:53:08 +00005854 ND = shad->getTargetDecl();
5855 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5856 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005857 }
5858
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005859 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5860 OverloadedMethods = Data.OverloadedMethods;
5861}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005862
Eli Friedmanaf65120b2013-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 Kyrtzidis7272d9c2011-02-03 18:01:15 +00005891 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005892}
5893
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005894void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005895 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005896 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005897 SourceLocation RBrac,
5898 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005899 if (!TagDecl)
5900 return;
Mike Stump11289f42009-09-09 15:08:12 +00005901
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005902 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005903
Rafael Espindola06e1b132012-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 Blaikie751c5582011-09-22 02:58:26 +00005912 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005913 // strict aliasing violation!
5914 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005915 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005916
Douglas Gregor0be31a22010-07-02 17:43:08 +00005917 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005918 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005919}
5920
Douglas Gregor05379422008-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 Gregor0be31a22010-07-02 17:43:08 +00005926void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005927 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005928 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005929
Richard Smith6b02d462012-12-08 08:32:28 +00005930 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005931 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005932
Richard Smith6b02d462012-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 Smith2bf7fdb2013-01-02 11:42:31 +00005940 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005941 ++ASTContext::NumImplicitMoveConstructors;
5942
Richard Smith6b02d462012-12-08 08:32:28 +00005943 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5944 DeclareImplicitMoveConstructor(ClassDecl);
5945 }
5946
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005947 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5948 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00005949
5950 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005951 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-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 Gregor330b9cf2010-07-02 21:50:04 +00005956 DeclareImplicitCopyAssignment(ClassDecl);
5957 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005958
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005959 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005960 ++ASTContext::NumImplicitMoveAssignmentOperators;
5961
5962 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00005963 if (ClassDecl->isDynamicClass() ||
5964 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00005965 DeclareImplicitMoveAssignment(ClassDecl);
5966 }
5967
Douglas Gregor7454c562010-07-02 20:37:36 +00005968 if (!ClassDecl->hasUserDeclaredDestructor()) {
5969 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00005970
5971 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-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 Smith6b02d462012-12-08 08:32:28 +00005975 if (ClassDecl->isDynamicClass() ||
5976 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00005977 DeclareImplicitDestructor(ClassDecl);
5978 }
Douglas Gregor05379422008-11-03 17:51:48 +00005979}
5980
Francois Pichet1c229c02011-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 McCall48871652010-08-21 09:40:31 +00006000void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-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 Gregore44a2ad2009-05-27 23:11:45 +00006011 return;
6012
Douglas Gregore44a2ad2009-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 McCall48871652010-08-21 09:40:31 +00006018 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006019 IdResolver.AddDecl(Named);
6020 }
6021 }
6022}
6023
John McCall48871652010-08-21 09:40:31 +00006024void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006025 if (!RecordD) return;
6026 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006027 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006028 PushDeclContext(S, Record);
6029}
6030
John McCall48871652010-08-21 09:40:31 +00006031void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006032 if (!RecordD) return;
6033 PopDeclContext();
6034}
6035
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006036/// This is used to implement the constant expression evaluation part of the
6037/// attribute enable_if extension. There is nothing in standard C++ which would
6038/// require reentering parameters.
6039void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6040 if (!Param)
6041 return;
6042
6043 S->AddDecl(Param);
6044 if (Param->getDeclName())
6045 IdResolver.AddDecl(Param);
6046}
6047
Douglas Gregor4d87df52008-12-16 21:30:33 +00006048/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6049/// parsing a top-level (non-nested) C++ class, and we are now
6050/// parsing those parts of the given Method declaration that could
6051/// not be parsed earlier (C++ [class.mem]p2), such as default
6052/// arguments. This action should enter the scope of the given
6053/// Method declaration as if we had just parsed the qualified method
6054/// name. However, it should not bring the parameters into scope;
6055/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006056void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006057}
6058
6059/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6060/// C++ method declaration. We're (re-)introducing the given
6061/// function parameter into scope for use in parsing later parts of
6062/// the method declaration. For example, we could see an
6063/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006064void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006065 if (!ParamD)
6066 return;
Mike Stump11289f42009-09-09 15:08:12 +00006067
John McCall48871652010-08-21 09:40:31 +00006068 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006069
6070 // If this parameter has an unparsed default argument, clear it out
6071 // to make way for the parsed default argument.
6072 if (Param->hasUnparsedDefaultArg())
6073 Param->setDefaultArg(0);
6074
John McCall48871652010-08-21 09:40:31 +00006075 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006076 if (Param->getDeclName())
6077 IdResolver.AddDecl(Param);
6078}
6079
6080/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6081/// processing the delayed method declaration for Method. The method
6082/// declaration is now considered finished. There may be a separate
6083/// ActOnStartOfFunctionDef action later (not necessarily
6084/// immediately!) for this method, if it was also defined inside the
6085/// class body.
John McCall48871652010-08-21 09:40:31 +00006086void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006087 if (!MethodD)
6088 return;
Mike Stump11289f42009-09-09 15:08:12 +00006089
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006090 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006091
John McCall48871652010-08-21 09:40:31 +00006092 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006093
6094 // Now that we have our default arguments, check the constructor
6095 // again. It could produce additional diagnostics or affect whether
6096 // the class has implicitly-declared destructors, among other
6097 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006098 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6099 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006100
6101 // Check the default arguments, which we may have added.
6102 if (!Method->isInvalidDecl())
6103 CheckCXXDefaultArguments(Method);
6104}
6105
Douglas Gregor831c93f2008-11-05 20:51:48 +00006106/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006107/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006108/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006109/// emit diagnostics and set the invalid bit to true. In any case, the type
6110/// will be updated to reflect a well-formed type for the constructor and
6111/// returned.
6112QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006113 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006114 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006115
6116 // C++ [class.ctor]p3:
6117 // A constructor shall not be virtual (10.3) or static (9.4). A
6118 // constructor can be invoked for a const, volatile or const
6119 // volatile object. A constructor shall not be declared const,
6120 // volatile, or const volatile (9.3.2).
6121 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006122 if (!D.isInvalidType())
6123 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6124 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6125 << SourceRange(D.getIdentifierLoc());
6126 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006127 }
John McCall8e7d6562010-08-26 03:08:43 +00006128 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006129 if (!D.isInvalidType())
6130 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6131 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6132 << SourceRange(D.getIdentifierLoc());
6133 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006134 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006135 }
Mike Stump11289f42009-09-09 15:08:12 +00006136
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006137 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006138 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006139 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006140 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6141 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006142 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006143 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6144 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006145 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006146 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6147 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006148 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006149 }
Mike Stump11289f42009-09-09 15:08:12 +00006150
Douglas Gregordb9d6642011-01-26 05:01:58 +00006151 // C++0x [class.ctor]p4:
6152 // A constructor shall not be declared with a ref-qualifier.
6153 if (FTI.hasRefQualifier()) {
6154 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6155 << FTI.RefQualifierIsLValueRef
6156 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6157 D.setInvalidType();
6158 }
6159
Douglas Gregor831c93f2008-11-05 20:51:48 +00006160 // Rebuild the function type "R" without any type qualifiers (in
6161 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006162 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006163 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006164 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006165 return R;
6166
6167 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6168 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006169 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006170
6171 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006172}
6173
Douglas Gregor4d87df52008-12-16 21:30:33 +00006174/// CheckConstructor - Checks a fully-formed constructor for
6175/// well-formedness, issuing any diagnostics required. Returns true if
6176/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006177void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006178 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006179 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6180 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006181 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006182
6183 // C++ [class.copy]p3:
6184 // A declaration of a constructor for a class X is ill-formed if
6185 // its first parameter is of type (optionally cv-qualified) X and
6186 // either there are no other parameters or else all other
6187 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006188 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006189 ((Constructor->getNumParams() == 1) ||
6190 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006191 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6192 Constructor->getTemplateSpecializationKind()
6193 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006194 QualType ParamType = Constructor->getParamDecl(0)->getType();
6195 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6196 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006197 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006198 const char *ConstRef
6199 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6200 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006201 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006202 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006203
6204 // FIXME: Rather that making the constructor invalid, we should endeavor
6205 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006206 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006207 }
6208 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006209}
6210
John McCalldeb646e2010-08-04 01:04:25 +00006211/// CheckDestructor - Checks a fully-formed destructor definition for
6212/// well-formedness, issuing any diagnostics required. Returns true
6213/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006214bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006215 CXXRecordDecl *RD = Destructor->getParent();
6216
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006217 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006218 SourceLocation Loc;
6219
6220 if (!Destructor->isImplicit())
6221 Loc = Destructor->getLocation();
6222 else
6223 Loc = RD->getLocation();
6224
6225 // If we have a virtual destructor, look up the deallocation function
6226 FunctionDecl *OperatorDelete = 0;
6227 DeclarationName Name =
6228 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006229 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006230 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006231 // If there's no class-specific operator delete, look up the global
6232 // non-array delete.
6233 if (!OperatorDelete)
6234 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006235
Eli Friedmanfa0df832012-02-02 03:46:19 +00006236 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006237
6238 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006239 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006240
6241 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006242}
6243
Mike Stump11289f42009-09-09 15:08:12 +00006244static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00006245FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
Alp Tokerc5350722014-02-26 22:27:52 +00006246 return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6247 FTI.Params[0].Param &&
6248 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00006249}
6250
Douglas Gregor831c93f2008-11-05 20:51:48 +00006251/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6252/// the well-formednes of the destructor declarator @p D with type @p
6253/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006254/// emit diagnostics and set the declarator to invalid. Even if this happens,
6255/// will be updated to reflect a well-formed type for the destructor and
6256/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006257QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006258 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006259 // C++ [class.dtor]p1:
6260 // [...] A typedef-name that names a class is a class-name
6261 // (7.1.3); however, a typedef-name that names a class shall not
6262 // be used as the identifier in the declarator for a destructor
6263 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006264 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006265 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006266 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006267 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006268 else if (const TemplateSpecializationType *TST =
6269 DeclaratorType->getAs<TemplateSpecializationType>())
6270 if (TST->isTypeAlias())
6271 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6272 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006273
6274 // C++ [class.dtor]p2:
6275 // A destructor is used to destroy objects of its class type. A
6276 // destructor takes no parameters, and no return type can be
6277 // specified for it (not even void). The address of a destructor
6278 // shall not be taken. A destructor shall not be static. A
6279 // destructor can be invoked for a const, volatile or const
6280 // volatile object. A destructor shall not be declared const,
6281 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006282 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006283 if (!D.isInvalidType())
6284 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6285 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006286 << SourceRange(D.getIdentifierLoc())
6287 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6288
John McCall8e7d6562010-08-26 03:08:43 +00006289 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006290 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006291 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006292 // Destructors don't have return types, but the parser will
6293 // happily parse something like:
6294 //
6295 // class X {
6296 // float ~X();
6297 // };
6298 //
6299 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006300 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6301 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6302 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006303 }
Mike Stump11289f42009-09-09 15:08:12 +00006304
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006305 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006306 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006307 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006308 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6309 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006310 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006311 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6312 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006313 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006314 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6315 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006316 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006317 }
6318
Douglas Gregordb9d6642011-01-26 05:01:58 +00006319 // C++0x [class.dtor]p2:
6320 // A destructor shall not be declared with a ref-qualifier.
6321 if (FTI.hasRefQualifier()) {
6322 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6323 << FTI.RefQualifierIsLValueRef
6324 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6325 D.setInvalidType();
6326 }
6327
Douglas Gregor831c93f2008-11-05 20:51:48 +00006328 // Make sure we don't have any parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006329 if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006330 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6331
6332 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006333 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006334 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006335 }
6336
Mike Stump11289f42009-09-09 15:08:12 +00006337 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006338 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006339 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006340 D.setInvalidType();
6341 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006342
6343 // Rebuild the function type "R" without any type qualifiers or
6344 // parameters (in case any of the errors above fired) and with
6345 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006346 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006347 if (!D.isInvalidType())
6348 return R;
6349
Douglas Gregor95755162010-07-01 05:10:53 +00006350 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006351 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6352 EPI.Variadic = false;
6353 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006354 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006355 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006356}
6357
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006358/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6359/// well-formednes of the conversion function declarator @p D with
6360/// type @p R. If there are any errors in the declarator, this routine
6361/// will emit diagnostics and return true. Otherwise, it will return
6362/// false. Either way, the type @p R will be updated to reflect a
6363/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006364void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006365 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006366 // C++ [class.conv.fct]p1:
6367 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006368 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006369 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006370 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006371 if (!D.isInvalidType())
6372 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006373 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6374 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006375 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006376 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006377 }
John McCall212fa2e2010-04-13 00:04:31 +00006378
6379 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6380
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006381 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006382 // Conversion functions don't have return types, but the parser will
6383 // happily parse something like:
6384 //
6385 // class X {
6386 // float operator bool();
6387 // };
6388 //
6389 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006390 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6391 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6392 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006393 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006394 }
6395
John McCall212fa2e2010-04-13 00:04:31 +00006396 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6397
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006398 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006399 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006400 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6401
6402 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006403 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006404 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006405 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006406 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006407 D.setInvalidType();
6408 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006409
John McCall212fa2e2010-04-13 00:04:31 +00006410 // Diagnose "&operator bool()" and other such nonsense. This
6411 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006412 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006413 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006414 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006415 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006416 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006417 }
6418
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006419 // C++ [class.conv.fct]p4:
6420 // The conversion-type-id shall not represent a function type nor
6421 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006422 if (ConvType->isArrayType()) {
6423 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6424 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006425 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006426 } else if (ConvType->isFunctionType()) {
6427 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6428 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006429 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006430 }
6431
6432 // Rebuild the function type "R" without any parameters (in case any
6433 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006434 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006435 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006436 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006437
Douglas Gregor5fb53972009-01-14 15:45:31 +00006438 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006439 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006440 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006441 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006442 diag::warn_cxx98_compat_explicit_conversion_functions :
6443 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006444 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006445}
6446
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006447/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6448/// the declaration of the given C++ conversion function. This routine
6449/// is responsible for recording the conversion function in the C++
6450/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006451Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006452 assert(Conversion && "Expected to receive a conversion function declaration");
6453
Douglas Gregor4287b372008-12-12 08:25:50 +00006454 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006455
6456 // Make sure we aren't redeclaring the conversion function.
6457 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006458
6459 // C++ [class.conv.fct]p1:
6460 // [...] A conversion function is never used to convert a
6461 // (possibly cv-qualified) object to the (possibly cv-qualified)
6462 // same object type (or a reference to it), to a (possibly
6463 // cv-qualified) base class of that type (or a reference to it),
6464 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006465 // FIXME: Suppress this warning if the conversion function ends up being a
6466 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006467 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006468 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006469 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006470 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006471 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6472 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006473 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006474 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006475 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6476 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006477 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006478 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006479 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006480 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006481 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006482 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006483 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006484 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006485 }
6486
Douglas Gregor457104e2010-09-29 04:25:11 +00006487 if (FunctionTemplateDecl *ConversionTemplate
6488 = Conversion->getDescribedFunctionTemplate())
6489 return ConversionTemplate;
6490
John McCall48871652010-08-21 09:40:31 +00006491 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006492}
6493
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006494//===----------------------------------------------------------------------===//
6495// Namespace Handling
6496//===----------------------------------------------------------------------===//
6497
Richard Smith45bb8852012-10-04 22:13:39 +00006498/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6499/// reopened.
6500static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6501 SourceLocation Loc,
6502 IdentifierInfo *II, bool *IsInline,
6503 NamespaceDecl *PrevNS) {
6504 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006505
Richard Smithf501cc32012-10-05 01:46:25 +00006506 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6507 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6508 // inline namespaces, with the intention of bringing names into namespace std.
6509 //
6510 // We support this just well enough to get that case working; this is not
6511 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006512 if (*IsInline && II && II->getName().startswith("__atomic") &&
6513 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006514 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006515 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6516 NS = NS->getPreviousDecl())
6517 NS->setInline(*IsInline);
6518 // Patch up the lookup table for the containing namespace. This isn't really
6519 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006520 for (auto *I : PrevNS->decls())
6521 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006522 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6523 return;
6524 }
6525
6526 if (PrevNS->isInline())
6527 // The user probably just forgot the 'inline', so suggest that it
6528 // be added back.
6529 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6530 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6531 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006532 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006533
6534 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6535 *IsInline = PrevNS->isInline();
6536}
John McCallb1be5232010-08-26 09:15:37 +00006537
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006538/// ActOnStartNamespaceDef - This is called at the start of a namespace
6539/// definition.
John McCall48871652010-08-21 09:40:31 +00006540Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006541 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006542 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006543 SourceLocation IdentLoc,
6544 IdentifierInfo *II,
6545 SourceLocation LBrace,
6546 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006547 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6548 // For anonymous namespace, take the location of the left brace.
6549 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006550 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006551 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006552 bool IsStd = false;
6553 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006554 Scope *DeclRegionScope = NamespcScope->getParent();
6555
Douglas Gregore57e7522012-01-07 09:11:48 +00006556 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006557 if (II) {
6558 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006559 // The identifier in an original-namespace-definition shall not
6560 // have been previously defined in the declarative region in
6561 // which the original-namespace-definition appears. The
6562 // identifier in an original-namespace-definition is the name of
6563 // the namespace. Subsequently in that declarative region, it is
6564 // treated as an original-namespace-name.
6565 //
6566 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006567 // look through using directives, just look for any ordinary names.
6568
6569 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006570 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6571 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006572 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006573 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6574 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6575 ++I) {
6576 if ((*I)->getIdentifierNamespace() & IDNS) {
6577 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006578 break;
6579 }
6580 }
6581
Douglas Gregore57e7522012-01-07 09:11:48 +00006582 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6583
6584 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006585 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006586 if (IsInline != PrevNS->isInline())
6587 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6588 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006589 } else if (PrevDecl) {
6590 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006591 Diag(Loc, diag::err_redefinition_different_kind)
6592 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006593 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006594 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006595 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006596 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006597 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006598 // This is the first "real" definition of the namespace "std", so update
6599 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006600 PrevNS = getStdNamespace();
6601 IsStd = true;
6602 AddToKnown = !IsInline;
6603 } else {
6604 // We've seen this namespace for the first time.
6605 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006606 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006607 } else {
John McCall4fa53422009-10-01 00:25:31 +00006608 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006609
6610 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006611 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006612 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006613 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006614 } else {
6615 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006616 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006617 }
6618
Richard Smith45bb8852012-10-04 22:13:39 +00006619 if (PrevNS && IsInline != PrevNS->isInline())
6620 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6621 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006622 }
6623
6624 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6625 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006626 if (IsInvalid)
6627 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006628
6629 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006630
Douglas Gregore57e7522012-01-07 09:11:48 +00006631 // FIXME: Should we be merging attributes?
6632 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006633 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006634
6635 if (IsStd)
6636 StdNamespace = Namespc;
6637 if (AddToKnown)
6638 KnownNamespaces[Namespc] = false;
6639
6640 if (II) {
6641 PushOnScopeChains(Namespc, DeclRegionScope);
6642 } else {
6643 // Link the anonymous namespace into its parent.
6644 DeclContext *Parent = CurContext->getRedeclContext();
6645 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6646 TU->setAnonymousNamespace(Namespc);
6647 } else {
6648 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006649 }
John McCall4fa53422009-10-01 00:25:31 +00006650
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006651 CurContext->addDecl(Namespc);
6652
John McCall4fa53422009-10-01 00:25:31 +00006653 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6654 // behaves as if it were replaced by
6655 // namespace unique { /* empty body */ }
6656 // using namespace unique;
6657 // namespace unique { namespace-body }
6658 // where all occurrences of 'unique' in a translation unit are
6659 // replaced by the same identifier and this identifier differs
6660 // from all other identifiers in the entire program.
6661
6662 // We just create the namespace with an empty name and then add an
6663 // implicit using declaration, just like the standard suggests.
6664 //
6665 // CodeGen enforces the "universally unique" aspect by giving all
6666 // declarations semantically contained within an anonymous
6667 // namespace internal linkage.
6668
Douglas Gregore57e7522012-01-07 09:11:48 +00006669 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006670 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006671 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006672 /* 'using' */ LBrace,
6673 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006674 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006675 /* identifier */ SourceLocation(),
6676 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006677 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006678 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006679 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006680 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006681 }
6682
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006683 ActOnDocumentableDecl(Namespc);
6684
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006685 // Although we could have an invalid decl (i.e. the namespace name is a
6686 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006687 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6688 // for the namespace has the declarations that showed up in that particular
6689 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006690 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006691 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006692}
6693
Sebastian Redla6602e92009-11-23 15:34:23 +00006694/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6695/// is a namespace alias, returns the namespace it points to.
6696static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6697 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6698 return AD->getNamespace();
6699 return dyn_cast_or_null<NamespaceDecl>(D);
6700}
6701
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006702/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6703/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006704void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006705 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6706 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006707 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006708 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006709 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006710 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006711}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006712
John McCall28a0cf72010-08-25 07:42:41 +00006713CXXRecordDecl *Sema::getStdBadAlloc() const {
6714 return cast_or_null<CXXRecordDecl>(
6715 StdBadAlloc.get(Context.getExternalSource()));
6716}
6717
6718NamespaceDecl *Sema::getStdNamespace() const {
6719 return cast_or_null<NamespaceDecl>(
6720 StdNamespace.get(Context.getExternalSource()));
6721}
6722
Douglas Gregorcdf87022010-06-29 17:53:46 +00006723/// \brief Retrieve the special "std" namespace, which may require us to
6724/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006725NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006726 if (!StdNamespace) {
6727 // The "std" namespace has not yet been defined, so build one implicitly.
6728 StdNamespace = NamespaceDecl::Create(Context,
6729 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006730 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006731 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006732 &PP.getIdentifierTable().get("std"),
6733 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006734 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006735 }
6736
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006737 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006738}
6739
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006740bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006741 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006742 "Looking for std::initializer_list outside of C++.");
6743
6744 // We're looking for implicit instantiations of
6745 // template <typename E> class std::initializer_list.
6746
6747 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6748 return false;
6749
Sebastian Redl43144e72012-01-17 22:49:58 +00006750 ClassTemplateDecl *Template = 0;
6751 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006752
Sebastian Redl43144e72012-01-17 22:49:58 +00006753 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006754
Sebastian Redl43144e72012-01-17 22:49:58 +00006755 ClassTemplateSpecializationDecl *Specialization =
6756 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6757 if (!Specialization)
6758 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006759
Sebastian Redl43144e72012-01-17 22:49:58 +00006760 Template = Specialization->getSpecializedTemplate();
6761 Arguments = Specialization->getTemplateArgs().data();
6762 } else if (const TemplateSpecializationType *TST =
6763 Ty->getAs<TemplateSpecializationType>()) {
6764 Template = dyn_cast_or_null<ClassTemplateDecl>(
6765 TST->getTemplateName().getAsTemplateDecl());
6766 Arguments = TST->getArgs();
6767 }
6768 if (!Template)
6769 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006770
6771 if (!StdInitializerList) {
6772 // Haven't recognized std::initializer_list yet, maybe this is it.
6773 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6774 if (TemplateClass->getIdentifier() !=
6775 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006776 !getStdNamespace()->InEnclosingNamespaceSetOf(
6777 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006778 return false;
6779 // This is a template called std::initializer_list, but is it the right
6780 // template?
6781 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006782 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006783 return false;
6784 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6785 return false;
6786
6787 // It's the right template.
6788 StdInitializerList = Template;
6789 }
6790
6791 if (Template != StdInitializerList)
6792 return false;
6793
6794 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006795 if (Element)
6796 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006797 return true;
6798}
6799
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006800static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6801 NamespaceDecl *Std = S.getStdNamespace();
6802 if (!Std) {
6803 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6804 return 0;
6805 }
6806
6807 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6808 Loc, Sema::LookupOrdinaryName);
6809 if (!S.LookupQualifiedName(Result, Std)) {
6810 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6811 return 0;
6812 }
6813 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6814 if (!Template) {
6815 Result.suppressDiagnostics();
6816 // We found something weird. Complain about the first thing we found.
6817 NamedDecl *Found = *Result.begin();
6818 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6819 return 0;
6820 }
6821
6822 // We found some template called std::initializer_list. Now verify that it's
6823 // correct.
6824 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006825 if (Params->getMinRequiredArguments() != 1 ||
6826 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006827 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6828 return 0;
6829 }
6830
6831 return Template;
6832}
6833
6834QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6835 if (!StdInitializerList) {
6836 StdInitializerList = LookupStdInitializerList(*this, Loc);
6837 if (!StdInitializerList)
6838 return QualType();
6839 }
6840
6841 TemplateArgumentListInfo Args(Loc, Loc);
6842 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6843 Context.getTrivialTypeSourceInfo(Element,
6844 Loc)));
6845 return Context.getCanonicalType(
6846 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6847}
6848
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006849bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6850 // C++ [dcl.init.list]p2:
6851 // A constructor is an initializer-list constructor if its first parameter
6852 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6853 // std::initializer_list<E> for some type E, and either there are no other
6854 // parameters or else all other parameters have default arguments.
6855 if (Ctor->getNumParams() < 1 ||
6856 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6857 return false;
6858
6859 QualType ArgType = Ctor->getParamDecl(0)->getType();
6860 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6861 ArgType = RT->getPointeeType().getUnqualifiedType();
6862
6863 return isStdInitializerList(ArgType, 0);
6864}
6865
Douglas Gregora172e082011-03-26 22:25:30 +00006866/// \brief Determine whether a using statement is in a context where it will be
6867/// apply in all contexts.
6868static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6869 switch (CurContext->getDeclKind()) {
6870 case Decl::TranslationUnit:
6871 return true;
6872 case Decl::LinkageSpec:
6873 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6874 default:
6875 return false;
6876 }
6877}
6878
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006879namespace {
6880
6881// Callback to only accept typo corrections that are namespaces.
6882class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006883public:
Craig Toppera798a9d2014-03-02 09:32:10 +00006884 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006885 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006886 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006887 return false;
6888 }
6889};
6890
6891}
6892
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006893static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6894 CXXScopeSpec &SS,
6895 SourceLocation IdentLoc,
6896 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006897 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006898 R.clear();
6899 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006900 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00006901 Validator)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006902 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006903 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6904 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006905 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006906 S.diagnoseTypo(Corrected,
6907 S.PDiag(diag::err_using_directive_member_suggest)
6908 << Ident << DC << DroppedSpecifier << SS.getRange(),
6909 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006910 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006911 S.diagnoseTypo(Corrected,
6912 S.PDiag(diag::err_using_directive_suggest) << Ident,
6913 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006914 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006915 R.addDecl(Corrected.getCorrectionDecl());
6916 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006917 }
6918 return false;
6919}
6920
John McCall48871652010-08-21 09:40:31 +00006921Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006922 SourceLocation UsingLoc,
6923 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006924 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006925 SourceLocation IdentLoc,
6926 IdentifierInfo *NamespcName,
6927 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006928 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6929 assert(NamespcName && "Invalid NamespcName.");
6930 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006931
6932 // This can only happen along a recovery path.
6933 while (S->getFlags() & Scope::TemplateParamScope)
6934 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006935 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006936
Douglas Gregor889ceb72009-02-03 19:21:40 +00006937 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006938 NestedNameSpecifier *Qualifier = 0;
6939 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00006940 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006941
Douglas Gregor34074322009-01-14 22:20:51 +00006942 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006943 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6944 LookupParsedName(R, S, &SS);
6945 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006946 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006947
Douglas Gregorcdf87022010-06-29 17:53:46 +00006948 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006949 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006950 // Allow "using namespace std;" or "using namespace ::std;" even if
6951 // "std" hasn't been defined yet, for GCC compatibility.
6952 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6953 NamespcName->isStr("std")) {
6954 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006955 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006956 R.resolveKind();
6957 }
6958 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006959 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006960 }
6961
John McCall9f3059a2009-10-09 21:13:30 +00006962 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006963 NamedDecl *Named = R.getFoundDecl();
6964 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6965 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006966 // C++ [namespace.udir]p1:
6967 // A using-directive specifies that the names in the nominated
6968 // namespace can be used in the scope in which the
6969 // using-directive appears after the using-directive. During
6970 // unqualified name lookup (3.4.1), the names appear as if they
6971 // were declared in the nearest enclosing namespace which
6972 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006973 // namespace. [Note: in this context, "contains" means "contains
6974 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006975
6976 // Find enclosing context containing both using-directive and
6977 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006978 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006979 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6980 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6981 CommonAncestor = CommonAncestor->getParent();
6982
Sebastian Redla6602e92009-11-23 15:34:23 +00006983 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006984 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006985 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006986
Douglas Gregora172e082011-03-26 22:25:30 +00006987 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00006988 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006989 Diag(IdentLoc, diag::warn_using_directive_in_header);
6990 }
6991
Douglas Gregor889ceb72009-02-03 19:21:40 +00006992 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006993 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006994 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006995 }
6996
Richard Smith54ecd982013-02-20 19:22:51 +00006997 if (UDir)
6998 ProcessDeclAttributeList(S, UDir, AttrList);
6999
John McCall48871652010-08-21 09:40:31 +00007000 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007001}
7002
7003void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007004 // If the scope has an associated entity and the using directive is at
7005 // namespace or translation unit scope, add the UsingDirectiveDecl into
7006 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007007 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007008 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007009 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007010 else
Richard Smith05afe5e2012-03-13 03:12:56 +00007011 // Otherwise, it is at block sope. The using-directives will affect lookup
7012 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007013 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007014}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007015
Douglas Gregorfec52632009-06-20 00:51:54 +00007016
John McCall48871652010-08-21 09:40:31 +00007017Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007018 AccessSpecifier AS,
7019 bool HasUsingKeyword,
7020 SourceLocation UsingLoc,
7021 CXXScopeSpec &SS,
7022 UnqualifiedId &Name,
7023 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007024 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007025 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007026 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007027
Douglas Gregor220f4272009-11-04 16:30:06 +00007028 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007029 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007030 case UnqualifiedId::IK_Identifier:
7031 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007032 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007033 case UnqualifiedId::IK_ConversionFunctionId:
7034 break;
7035
7036 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007037 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007038 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007039 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007040 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007041 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007042 diag::err_using_decl_constructor)
7043 << SS.getRange();
7044
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007045 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007046
John McCall48871652010-08-21 09:40:31 +00007047 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007048
7049 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007050 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007051 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007052 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007053
7054 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007055 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007056 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00007057 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007058 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007059
7060 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7061 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007062 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00007063 return 0;
John McCall3969e302009-12-08 07:46:18 +00007064
Richard Smithc2bc61b2013-03-18 21:12:30 +00007065 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007066 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007067 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007068 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7069 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007070 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007071 }
7072
Douglas Gregorc4356532010-12-16 00:46:58 +00007073 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7074 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7075 return 0;
7076
John McCall3f746822009-11-17 05:59:44 +00007077 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007078 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007079 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007080 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007081 if (UD)
7082 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007083
John McCall48871652010-08-21 09:40:31 +00007084 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007085}
7086
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007087/// \brief Determine whether a using declaration considers the given
7088/// declarations as "equivalent", e.g., if they are redeclarations of
7089/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007090static bool
7091IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7092 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007093 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007094
Richard Smithdda56e42011-04-15 14:24:37 +00007095 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007096 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007097 return Context.hasSameType(TD1->getUnderlyingType(),
7098 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007099
7100 return false;
7101}
7102
7103
John McCall84d87672009-12-10 09:41:52 +00007104/// Determines whether to create a using shadow decl for a particular
7105/// decl, given the set of decls existing prior to this using lookup.
7106bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007107 const LookupResult &Previous,
7108 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007109 // Diagnose finding a decl which is not from a base class of the
7110 // current class. We do this now because there are cases where this
7111 // function will silently decide not to build a shadow decl, which
7112 // will pre-empt further diagnostics.
7113 //
7114 // We don't need to do this in C++0x because we do the check once on
7115 // the qualifier.
7116 //
7117 // FIXME: diagnose the following if we care enough:
7118 // struct A { int foo; };
7119 // struct B : A { using A::foo; };
7120 // template <class T> struct C : A {};
7121 // template <class T> struct D : C<T> { using B::foo; } // <---
7122 // This is invalid (during instantiation) in C++03 because B::foo
7123 // resolves to the using decl in B, which is not a base class of D<T>.
7124 // We can't diagnose it immediately because C<T> is an unknown
7125 // specialization. The UsingShadowDecl in D<T> then points directly
7126 // to A::foo, which will look well-formed when we instantiate.
7127 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007128 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007129 DeclContext *OrigDC = Orig->getDeclContext();
7130
7131 // Handle enums and anonymous structs.
7132 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7133 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7134 while (OrigRec->isAnonymousStructOrUnion())
7135 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7136
7137 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7138 if (OrigDC == CurContext) {
7139 Diag(Using->getLocation(),
7140 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007141 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007142 Diag(Orig->getLocation(), diag::note_using_decl_target);
7143 return true;
7144 }
7145
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007146 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007147 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007148 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007149 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007150 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007151 Diag(Orig->getLocation(), diag::note_using_decl_target);
7152 return true;
7153 }
7154 }
7155
7156 if (Previous.empty()) return false;
7157
7158 NamedDecl *Target = Orig;
7159 if (isa<UsingShadowDecl>(Target))
7160 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7161
John McCalla17e83e2009-12-11 02:33:26 +00007162 // If the target happens to be one of the previous declarations, we
7163 // don't have a conflict.
7164 //
7165 // FIXME: but we might be increasing its access, in which case we
7166 // should redeclare it.
7167 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithfd8634a2013-10-23 02:17:46 +00007168 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007169 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7170 I != E; ++I) {
7171 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007172 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7173 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7174 PrevShadow = Shadow;
7175 FoundEquivalentDecl = true;
7176 }
John McCalla17e83e2009-12-11 02:33:26 +00007177
7178 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7179 }
7180
Richard Smithfd8634a2013-10-23 02:17:46 +00007181 if (FoundEquivalentDecl)
7182 return false;
7183
Alp Tokera2794f92014-01-22 07:29:52 +00007184 if (FunctionDecl *FD = Target->getAsFunction()) {
John McCall84d87672009-12-10 09:41:52 +00007185 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00007186 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007187 case Ovl_Overload:
7188 return false;
7189
7190 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007191 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007192 break;
Richard Smith18819302014-02-06 01:31:33 +00007193
John McCall84d87672009-12-10 09:41:52 +00007194 // We found a decl with the exact signature.
7195 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007196 // If we're in a record, we want to hide the target, so we
7197 // return true (without a diagnostic) to tell the caller not to
7198 // build a shadow decl.
7199 if (CurContext->isRecord())
7200 return true;
7201
7202 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007203 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007204 break;
7205 }
7206
7207 Diag(Target->getLocation(), diag::note_using_decl_target);
7208 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7209 return true;
7210 }
7211
7212 // Target is not a function.
7213
John McCall84d87672009-12-10 09:41:52 +00007214 if (isa<TagDecl>(Target)) {
7215 // No conflict between a tag and a non-tag.
7216 if (!Tag) return false;
7217
John McCalle29c5cd2009-12-10 19:51:03 +00007218 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007219 Diag(Target->getLocation(), diag::note_using_decl_target);
7220 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7221 return true;
7222 }
7223
7224 // No conflict between a tag and a non-tag.
7225 if (!NonTag) return false;
7226
John McCalle29c5cd2009-12-10 19:51:03 +00007227 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007228 Diag(Target->getLocation(), diag::note_using_decl_target);
7229 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7230 return true;
7231}
7232
John McCall3f746822009-11-17 05:59:44 +00007233/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007234UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007235 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007236 NamedDecl *Orig,
7237 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007238
7239 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007240 NamedDecl *Target = Orig;
7241 if (isa<UsingShadowDecl>(Target)) {
7242 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7243 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007244 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007245
John McCall3f746822009-11-17 05:59:44 +00007246 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007247 = UsingShadowDecl::Create(Context, CurContext,
7248 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007249 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007250
Douglas Gregor457104e2010-09-29 04:25:11 +00007251 Shadow->setAccess(UD->getAccess());
7252 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7253 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007254
7255 Shadow->setPreviousDecl(PrevDecl);
7256
John McCall3f746822009-11-17 05:59:44 +00007257 if (S)
John McCall3969e302009-12-08 07:46:18 +00007258 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007259 else
John McCall3969e302009-12-08 07:46:18 +00007260 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007261
John McCall3969e302009-12-08 07:46:18 +00007262
John McCall84d87672009-12-10 09:41:52 +00007263 return Shadow;
7264}
John McCall3969e302009-12-08 07:46:18 +00007265
John McCall84d87672009-12-10 09:41:52 +00007266/// Hides a using shadow declaration. This is required by the current
7267/// using-decl implementation when a resolvable using declaration in a
7268/// class is followed by a declaration which would hide or override
7269/// one or more of the using decl's targets; for example:
7270///
7271/// struct Base { void foo(int); };
7272/// struct Derived : Base {
7273/// using Base::foo;
7274/// void foo(int);
7275/// };
7276///
7277/// The governing language is C++03 [namespace.udecl]p12:
7278///
7279/// When a using-declaration brings names from a base class into a
7280/// derived class scope, member functions in the derived class
7281/// override and/or hide member functions with the same name and
7282/// parameter types in a base class (rather than conflicting).
7283///
7284/// There are two ways to implement this:
7285/// (1) optimistically create shadow decls when they're not hidden
7286/// by existing declarations, or
7287/// (2) don't create any shadow decls (or at least don't make them
7288/// visible) until we've fully parsed/instantiated the class.
7289/// The problem with (1) is that we might have to retroactively remove
7290/// a shadow decl, which requires several O(n) operations because the
7291/// decl structures are (very reasonably) not designed for removal.
7292/// (2) avoids this but is very fiddly and phase-dependent.
7293void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007294 if (Shadow->getDeclName().getNameKind() ==
7295 DeclarationName::CXXConversionFunctionName)
7296 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7297
John McCall84d87672009-12-10 09:41:52 +00007298 // Remove it from the DeclContext...
7299 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007300
John McCall84d87672009-12-10 09:41:52 +00007301 // ...and the scope, if applicable...
7302 if (S) {
John McCall48871652010-08-21 09:40:31 +00007303 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007304 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007305 }
7306
John McCall84d87672009-12-10 09:41:52 +00007307 // ...and the using decl.
7308 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7309
7310 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007311 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007312}
7313
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007314namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007315class UsingValidatorCCC : public CorrectionCandidateCallback {
7316public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007317 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7318 bool RequireMember)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007319 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007320 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007321
Craig Toppera798a9d2014-03-02 09:32:10 +00007322 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007323 NamedDecl *ND = Candidate.getCorrectionDecl();
7324
7325 // Keywords are not valid here.
7326 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007327 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007328
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007329 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7330 !isa<TypeDecl>(ND))
7331 return false;
7332
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007333 // Completely unqualified names are invalid for a 'using' declaration.
7334 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7335 return false;
7336
7337 if (isa<TypeDecl>(ND))
7338 return HasTypenameKeyword || !IsInstantiation;
7339
7340 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007341 }
7342
7343private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007344 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007345 bool IsInstantiation;
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007346 bool RequireMember;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007347};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007348} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007349
John McCalle61f2ba2009-11-18 02:36:19 +00007350/// Builds a using declaration.
7351///
7352/// \param IsInstantiation - Whether this call arises from an
7353/// instantiation of an unresolved using declaration. We treat
7354/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007355NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7356 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007357 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007358 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007359 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007360 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007361 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007362 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007363 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007364 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007365 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007366
Anders Carlssonf038fc22009-08-28 05:49:21 +00007367 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007368
Anders Carlsson59140b32009-08-28 03:16:11 +00007369 if (SS.isEmpty()) {
7370 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007371 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007372 }
Mike Stump11289f42009-09-09 15:08:12 +00007373
John McCall84d87672009-12-10 09:41:52 +00007374 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007375 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007376 ForRedeclaration);
7377 Previous.setHideTags(false);
7378 if (S) {
7379 LookupName(Previous, S);
7380
7381 // It is really dumb that we have to do this.
7382 LookupResult::Filter F = Previous.makeFilter();
7383 while (F.hasNext()) {
7384 NamedDecl *D = F.next();
7385 if (!isDeclInScope(D, CurContext, S))
7386 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007387 // If we found a local extern declaration that's not ordinarily visible,
7388 // and this declaration is being added to a non-block scope, ignore it.
7389 // We're only checking for scope conflicts here, not also for violations
7390 // of the linkage rules.
7391 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7392 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7393 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007394 }
7395 F.done();
7396 } else {
7397 assert(IsInstantiation && "no scope in non-instantiation");
7398 assert(CurContext->isRecord() && "scope not record in instantiation");
7399 LookupQualifiedName(Previous, CurContext);
7400 }
7401
John McCall84d87672009-12-10 09:41:52 +00007402 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007403 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7404 SS, IdentLoc, Previous))
John McCall84d87672009-12-10 09:41:52 +00007405 return 0;
7406
7407 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007408 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
John McCallb96ec562009-12-04 22:46:56 +00007409 return 0;
7410
John McCall84c16cf2009-11-12 03:15:40 +00007411 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007412 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007413 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007414 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007415 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007416 // FIXME: not all declaration name kinds are legal here
7417 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7418 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007419 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007420 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007421 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007422 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7423 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007424 }
John McCallb96ec562009-12-04 22:46:56 +00007425 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007426 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007427 NameInfo, HasTypenameKeyword);
Anders Carlssonf038fc22009-08-28 05:49:21 +00007428 }
John McCallb96ec562009-12-04 22:46:56 +00007429 D->setAccess(AS);
7430 CurContext->addDecl(D);
7431
7432 if (!LookupContext) return D;
7433 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00007434
John McCall0b66eb32010-05-01 00:40:08 +00007435 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00007436 UD->setInvalidDecl();
7437 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00007438 }
7439
Richard Smith23d55872012-04-02 01:30:27 +00007440 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007441 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith23d55872012-04-02 01:30:27 +00007442 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlc1f8e492011-03-12 13:44:32 +00007443 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007444 return UD;
7445 }
7446
7447 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007448
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007449 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007450
John McCall3969e302009-12-08 07:46:18 +00007451 // Unlike most lookups, we don't always want to hide tag
7452 // declarations: tag names are visible through the using declaration
7453 // even if hidden by ordinary names, *except* in a dependent context
7454 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007455 if (!IsInstantiation)
7456 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007457
John McCall5dadb652012-04-07 03:04:20 +00007458 // For the purposes of this lookup, we have a base object type
7459 // equal to that of the current context.
7460 if (CurContext->isRecord()) {
7461 R.setBaseObjectType(
7462 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7463 }
7464
John McCall27b18f82009-11-17 02:14:36 +00007465 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007466
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007467 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007468 if (R.empty()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007469 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7470 CurContext->isRecord());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007471 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7472 R.getLookupKind(), S, &SS, CCC)){
7473 // We reject any correction for which ND would be NULL.
7474 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007475 R.setLookupName(Corrected.getCorrection());
7476 R.addDecl(ND);
Richard Smithf9b15102013-08-17 00:46:16 +00007477 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007478 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007479 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7480 << NameInfo.getName() << LookupContext << 0
7481 << SS.getRange());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007482 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007483 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007484 << NameInfo.getName() << LookupContext << SS.getRange();
7485 UD->setInvalidDecl();
7486 return UD;
7487 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007488 }
7489
John McCallb96ec562009-12-04 22:46:56 +00007490 if (R.isAmbiguous()) {
7491 UD->setInvalidDecl();
7492 return UD;
7493 }
Mike Stump11289f42009-09-09 15:08:12 +00007494
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007495 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007496 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007497 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007498 Diag(IdentLoc, diag::err_using_typename_non_type);
7499 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7500 Diag((*I)->getUnderlyingDecl()->getLocation(),
7501 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007502 UD->setInvalidDecl();
7503 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007504 }
7505 } else {
7506 // If we asked for a non-typename and we got a type, error out,
7507 // but only if this is an instantiation of an unresolved using
7508 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007509 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007510 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7511 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007512 UD->setInvalidDecl();
7513 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007514 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007515 }
7516
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007517 // C++0x N2914 [namespace.udecl]p6:
7518 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007519 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007520 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7521 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007522 UD->setInvalidDecl();
7523 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007524 }
Mike Stump11289f42009-09-09 15:08:12 +00007525
John McCall84d87672009-12-10 09:41:52 +00007526 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithfd8634a2013-10-23 02:17:46 +00007527 UsingShadowDecl *PrevDecl = 0;
7528 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7529 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007530 }
John McCall3f746822009-11-17 05:59:44 +00007531
7532 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007533}
7534
Sebastian Redl08905022011-02-05 19:23:19 +00007535/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007536bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007537 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007538
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007539 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007540 assert(SourceType &&
7541 "Using decl naming constructor doesn't have type in scope spec.");
7542 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7543
7544 // Check whether the named type is a direct base class.
7545 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7546 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7547 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7548 BaseIt != BaseE; ++BaseIt) {
7549 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7550 if (CanonicalSourceType == BaseType)
7551 break;
Richard Smith23d55872012-04-02 01:30:27 +00007552 if (BaseIt->getType()->isDependentType())
7553 break;
Sebastian Redl08905022011-02-05 19:23:19 +00007554 }
7555
7556 if (BaseIt == BaseE) {
7557 // Did not find SourceType in the bases.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007558 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007559 diag::err_using_decl_constructor_not_in_direct_base)
7560 << UD->getNameInfo().getSourceRange()
7561 << QualType(SourceType, 0) << TargetClass;
7562 return true;
7563 }
7564
Richard Smith23d55872012-04-02 01:30:27 +00007565 if (!CurContext->isDependentContext())
7566 BaseIt->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007567
7568 return false;
7569}
7570
John McCall84d87672009-12-10 09:41:52 +00007571/// Checks that the given using declaration is not an invalid
7572/// redeclaration. Note that this is checking only for the using decl
7573/// itself, not for any ill-formedness among the UsingShadowDecls.
7574bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007575 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007576 const CXXScopeSpec &SS,
7577 SourceLocation NameLoc,
7578 const LookupResult &Prev) {
7579 // C++03 [namespace.udecl]p8:
7580 // C++0x [namespace.udecl]p10:
7581 // A using-declaration is a declaration and can therefore be used
7582 // repeatedly where (and only where) multiple declarations are
7583 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007584 //
John McCall032092f2010-11-29 18:01:58 +00007585 // That's in non-member contexts.
7586 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007587 return false;
7588
Aaron Ballman4a979672014-01-03 13:56:08 +00007589 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007590
7591 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7592 NamedDecl *D = *I;
7593
7594 bool DTypename;
7595 NestedNameSpecifier *DQual;
7596 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007597 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007598 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007599 } else if (UnresolvedUsingValueDecl *UD
7600 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7601 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007602 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007603 } else if (UnresolvedUsingTypenameDecl *UD
7604 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7605 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007606 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007607 } else continue;
7608
7609 // using decls differ if one says 'typename' and the other doesn't.
7610 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007611 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007612
7613 // using decls differ if they name different scopes (but note that
7614 // template instantiation can cause this check to trigger when it
7615 // didn't before instantiation).
7616 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7617 Context.getCanonicalNestedNameSpecifier(DQual))
7618 continue;
7619
7620 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007621 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007622 return true;
7623 }
7624
7625 return false;
7626}
7627
John McCall3969e302009-12-08 07:46:18 +00007628
John McCallb96ec562009-12-04 22:46:56 +00007629/// Checks that the given nested-name qualifier used in a using decl
7630/// in the current context is appropriately related to the current
7631/// scope. If an error is found, diagnoses it and returns true.
7632bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7633 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00007634 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00007635 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007636 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007637
John McCall3969e302009-12-08 07:46:18 +00007638 if (!CurContext->isRecord()) {
7639 // C++03 [namespace.udecl]p3:
7640 // C++0x [namespace.udecl]p8:
7641 // A using-declaration for a class member shall be a member-declaration.
7642
7643 // If we weren't able to compute a valid scope, it must be a
7644 // dependent class scope.
7645 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00007646 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7647 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
7648 RD = 0;
7649
John McCall3969e302009-12-08 07:46:18 +00007650 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7651 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00007652
7653 // If we have a complete, non-dependent source type, try to suggest a
7654 // way to get the same effect.
7655 if (!RD)
7656 return true;
7657
7658 // Find what this using-declaration was referring to.
7659 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7660 R.setHideTags(false);
7661 R.suppressDiagnostics();
7662 LookupQualifiedName(R, RD);
7663
7664 if (R.getAsSingle<TypeDecl>()) {
7665 if (getLangOpts().CPlusPlus11) {
7666 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7667 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7668 << 0 // alias declaration
7669 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7670 NameInfo.getName().getAsString() +
7671 " = ");
7672 } else {
7673 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7674 SourceLocation InsertLoc =
7675 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7676 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7677 << 1 // typedef declaration
7678 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7679 << FixItHint::CreateInsertion(
7680 InsertLoc, " " + NameInfo.getName().getAsString());
7681 }
7682 } else if (R.getAsSingle<VarDecl>()) {
7683 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7684 // repeating the type of the static data member here.
7685 FixItHint FixIt;
7686 if (getLangOpts().CPlusPlus11) {
7687 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7688 FixIt = FixItHint::CreateReplacement(
7689 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7690 }
7691
7692 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7693 << 2 // reference declaration
7694 << FixIt;
7695 }
John McCall3969e302009-12-08 07:46:18 +00007696 return true;
7697 }
7698
7699 // Otherwise, everything is known to be fine.
7700 return false;
7701 }
7702
7703 // The current scope is a record.
7704
7705 // If the named context is dependent, we can't decide much.
7706 if (!NamedContext) {
7707 // FIXME: in C++0x, we can diagnose if we can prove that the
7708 // nested-name-specifier does not refer to a base class, which is
7709 // still possible in some cases.
7710
7711 // Otherwise we have to conservatively report that things might be
7712 // okay.
7713 return false;
7714 }
7715
7716 if (!NamedContext->isRecord()) {
7717 // Ideally this would point at the last name in the specifier,
7718 // but we don't have that level of source info.
7719 Diag(SS.getRange().getBegin(),
7720 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007721 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007722 return true;
7723 }
7724
Douglas Gregor7c842292010-12-21 07:41:49 +00007725 if (!NamedContext->isDependentContext() &&
7726 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7727 return true;
7728
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007729 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007730 // C++0x [namespace.udecl]p3:
7731 // In a using-declaration used as a member-declaration, the
7732 // nested-name-specifier shall name a base class of the class
7733 // being defined.
7734
7735 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7736 cast<CXXRecordDecl>(NamedContext))) {
7737 if (CurContext == NamedContext) {
7738 Diag(NameLoc,
7739 diag::err_using_decl_nested_name_specifier_is_current_class)
7740 << SS.getRange();
7741 return true;
7742 }
7743
7744 Diag(SS.getRange().getBegin(),
7745 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007746 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007747 << cast<CXXRecordDecl>(CurContext)
7748 << SS.getRange();
7749 return true;
7750 }
7751
7752 return false;
7753 }
7754
7755 // C++03 [namespace.udecl]p4:
7756 // A using-declaration used as a member-declaration shall refer
7757 // to a member of a base class of the class being defined [etc.].
7758
7759 // Salient point: SS doesn't have to name a base class as long as
7760 // lookup only finds members from base classes. Therefore we can
7761 // diagnose here only if we can prove that that can't happen,
7762 // i.e. if the class hierarchies provably don't intersect.
7763
7764 // TODO: it would be nice if "definitely valid" results were cached
7765 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7766 // need to be repeated.
7767
7768 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007769 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007770
7771 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7772 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7773 Data->Bases.insert(Base);
7774 return true;
7775 }
7776
7777 bool hasDependentBases(const CXXRecordDecl *Class) {
7778 return !Class->forallBases(collect, this);
7779 }
7780
7781 /// Returns true if the base is dependent or is one of the
7782 /// accumulated base classes.
7783 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7784 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7785 return !Data->Bases.count(Base);
7786 }
7787
7788 bool mightShareBases(const CXXRecordDecl *Class) {
7789 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7790 }
7791 };
7792
7793 UserData Data;
7794
7795 // Returns false if we find a dependent base.
7796 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7797 return false;
7798
7799 // Returns false if the class has a dependent base or if it or one
7800 // of its bases is present in the base set of the current context.
7801 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7802 return false;
7803
7804 Diag(SS.getRange().getBegin(),
7805 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007806 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007807 << cast<CXXRecordDecl>(CurContext)
7808 << SS.getRange();
7809
7810 return true;
John McCallb96ec562009-12-04 22:46:56 +00007811}
7812
Richard Smithdda56e42011-04-15 14:24:37 +00007813Decl *Sema::ActOnAliasDeclaration(Scope *S,
7814 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007815 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007816 SourceLocation UsingLoc,
7817 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007818 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007819 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007820 // Skip up to the relevant declaration scope.
7821 while (S->getFlags() & Scope::TemplateParamScope)
7822 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007823 assert((S->getFlags() & Scope::DeclScope) &&
7824 "got alias-declaration outside of declaration scope");
7825
7826 if (Type.isInvalid())
7827 return 0;
7828
7829 bool Invalid = false;
7830 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7831 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007832 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007833
7834 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7835 return 0;
7836
7837 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007838 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007839 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007840 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7841 TInfo->getTypeLoc().getBeginLoc());
7842 }
Richard Smithdda56e42011-04-15 14:24:37 +00007843
7844 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7845 LookupName(Previous, S);
7846
7847 // Warn about shadowing the name of a template parameter.
7848 if (Previous.isSingleResult() &&
7849 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007850 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007851 Previous.clear();
7852 }
7853
7854 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7855 "name in alias declaration must be an identifier");
7856 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7857 Name.StartLocation,
7858 Name.Identifier, TInfo);
7859
7860 NewTD->setAccess(AS);
7861
7862 if (Invalid)
7863 NewTD->setInvalidDecl();
7864
Richard Smith54ecd982013-02-20 19:22:51 +00007865 ProcessDeclAttributeList(S, NewTD, AttrList);
7866
Richard Smith3f1b5d02011-05-05 21:57:07 +00007867 CheckTypedefForVariablyModifiedType(S, NewTD);
7868 Invalid |= NewTD->isInvalidDecl();
7869
Richard Smithdda56e42011-04-15 14:24:37 +00007870 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007871
7872 NamedDecl *NewND;
7873 if (TemplateParamLists.size()) {
7874 TypeAliasTemplateDecl *OldDecl = 0;
7875 TemplateParameterList *OldTemplateParams = 0;
7876
7877 if (TemplateParamLists.size() != 1) {
7878 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007879 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7880 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007881 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007882 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007883
7884 // Only consider previous declarations in the same scope.
7885 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7886 /*ExplicitInstantiationOrSpecialization*/false);
7887 if (!Previous.empty()) {
7888 Redeclaration = true;
7889
7890 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7891 if (!OldDecl && !Invalid) {
7892 Diag(UsingLoc, diag::err_redefinition_different_kind)
7893 << Name.Identifier;
7894
7895 NamedDecl *OldD = Previous.getRepresentativeDecl();
7896 if (OldD->getLocation().isValid())
7897 Diag(OldD->getLocation(), diag::note_previous_definition);
7898
7899 Invalid = true;
7900 }
7901
7902 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7903 if (TemplateParameterListsAreEqual(TemplateParams,
7904 OldDecl->getTemplateParameters(),
7905 /*Complain=*/true,
7906 TPL_TemplateMatch))
7907 OldTemplateParams = OldDecl->getTemplateParameters();
7908 else
7909 Invalid = true;
7910
7911 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7912 if (!Invalid &&
7913 !Context.hasSameType(OldTD->getUnderlyingType(),
7914 NewTD->getUnderlyingType())) {
7915 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7916 // but we can't reasonably accept it.
7917 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7918 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7919 if (OldTD->getLocation().isValid())
7920 Diag(OldTD->getLocation(), diag::note_previous_definition);
7921 Invalid = true;
7922 }
7923 }
7924 }
7925
7926 // Merge any previous default template arguments into our parameters,
7927 // and check the parameter list.
7928 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7929 TPC_TypeAliasTemplate))
7930 return 0;
7931
7932 TypeAliasTemplateDecl *NewDecl =
7933 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7934 Name.Identifier, TemplateParams,
7935 NewTD);
7936
7937 NewDecl->setAccess(AS);
7938
7939 if (Invalid)
7940 NewDecl->setInvalidDecl();
7941 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00007942 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007943
7944 NewND = NewDecl;
7945 } else {
7946 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7947 NewND = NewTD;
7948 }
Richard Smithdda56e42011-04-15 14:24:37 +00007949
7950 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00007951 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00007952
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00007953 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007954 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00007955}
7956
John McCall48871652010-08-21 09:40:31 +00007957Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007958 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00007959 SourceLocation AliasLoc,
7960 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007961 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007962 SourceLocation IdentLoc,
7963 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00007964
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007965 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007966 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7967 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007968
Anders Carlssondca83c42009-03-28 06:23:46 +00007969 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00007970 NamedDecl *PrevDecl
7971 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7972 ForRedeclaration);
7973 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7974 PrevDecl = 0;
7975
7976 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007977 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00007978 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007979 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00007980 // FIXME: At some point, we'll want to create the (redundant)
7981 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00007982 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00007983 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00007984 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007985 }
Mike Stump11289f42009-09-09 15:08:12 +00007986
Anders Carlssondca83c42009-03-28 06:23:46 +00007987 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7988 diag::err_redefinition_different_kind;
7989 Diag(AliasLoc, DiagID) << Alias;
7990 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007991 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00007992 }
7993
John McCall27b18f82009-11-17 02:14:36 +00007994 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007995 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00007996
John McCall9f3059a2009-10-09 21:13:30 +00007997 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007998 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00007999 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00008000 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008001 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008002 }
Mike Stump11289f42009-09-09 15:08:12 +00008003
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008004 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008005 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008006 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008007 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008008
John McCalld8d0d432010-02-16 06:53:13 +00008009 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008010 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008011}
8012
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008013Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008014Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8015 CXXMethodDecl *MD) {
8016 CXXRecordDecl *ClassDecl = MD->getParent();
8017
Douglas Gregor6d880b12010-07-01 22:31:05 +00008018 // C++ [except.spec]p14:
8019 // An implicitly declared special member function (Clause 12) shall have an
8020 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008021 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008022 if (ClassDecl->isInvalidDecl())
8023 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008024
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008025 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008026 for (const auto &B : ClassDecl->bases()) {
8027 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008028 continue;
8029
Aaron Ballman574705e2014-03-13 15:41:46 +00008030 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008031 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008032 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8033 // If this is a deleted function, add it anyway. This might be conformant
8034 // with the standard. This might not. I'm not sure. It might not matter.
8035 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008036 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008037 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008038 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008039
8040 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008041 for (const auto &B : ClassDecl->vbases()) {
8042 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008043 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008044 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8045 // If this is a deleted function, add it anyway. This might be conformant
8046 // with the standard. This might not. I'm not sure. It might not matter.
8047 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008048 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008049 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008050 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008051
8052 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008053 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008054 if (F->hasInClassInitializer()) {
8055 if (Expr *E = F->getInClassInitializer())
8056 ExceptSpec.CalledExpr(E);
8057 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008058 // DR1351:
8059 // If the brace-or-equal-initializer of a non-static data member
8060 // invokes a defaulted default constructor of its class or of an
8061 // enclosing class in a potentially evaluated subexpression, the
8062 // program is ill-formed.
8063 //
8064 // This resolution is unworkable: the exception specification of the
8065 // default constructor can be needed in an unevaluated context, in
8066 // particular, in the operand of a noexcept-expression, and we can be
8067 // unable to compute an exception specification for an enclosed class.
8068 //
8069 // We do not allow an in-class initializer to require the evaluation
8070 // of the exception specification for any in-class initializer whose
8071 // definition is not lexically complete.
8072 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008073 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008074 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008075 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8076 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8077 // If this is a deleted function, add it anyway. This might be conformant
8078 // with the standard. This might not. I'm not sure. It might not matter.
8079 // In particular, the problem is that this function never gets called. It
8080 // might just be ill-formed because this function attempts to refer to
8081 // a deleted function here.
8082 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008083 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008084 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008085 }
John McCalldb40c7f2010-12-14 08:05:40 +00008086
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008087 return ExceptSpec;
8088}
8089
Richard Smithc2bc61b2013-03-18 21:12:30 +00008090Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008091Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8092 CXXRecordDecl *ClassDecl = CD->getParent();
8093
8094 // C++ [except.spec]p14:
8095 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008096 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008097 if (ClassDecl->isInvalidDecl())
8098 return ExceptSpec;
8099
8100 // Inherited constructor.
8101 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8102 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8103 // FIXME: Copying or moving the parameters could add extra exceptions to the
8104 // set, as could the default arguments for the inherited constructor. This
8105 // will be addressed when we implement the resolution of core issue 1351.
8106 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8107
8108 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008109 for (const auto &B : ClassDecl->bases()) {
8110 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008111 continue;
8112
Aaron Ballman574705e2014-03-13 15:41:46 +00008113 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008114 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8115 if (BaseClassDecl == InheritedDecl)
8116 continue;
8117 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8118 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008119 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008120 }
8121 }
8122
8123 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008124 for (const auto &B : ClassDecl->vbases()) {
8125 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008126 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8127 if (BaseClassDecl == InheritedDecl)
8128 continue;
8129 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8130 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008131 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008132 }
8133 }
8134
8135 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008136 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008137 if (F->hasInClassInitializer()) {
8138 if (Expr *E = F->getInClassInitializer())
8139 ExceptSpec.CalledExpr(E);
8140 else if (!F->isInvalidDecl())
8141 Diag(CD->getLocation(),
8142 diag::err_in_class_initializer_references_def_ctor) << CD;
8143 } else if (const RecordType *RecordTy
8144 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8145 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8146 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8147 if (Constructor)
8148 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8149 }
8150 }
8151
Richard Smithc2bc61b2013-03-18 21:12:30 +00008152 return ExceptSpec;
8153}
8154
Richard Smith8bf22e52012-11-29 01:34:07 +00008155namespace {
8156/// RAII object to register a special member as being currently declared.
8157struct DeclaringSpecialMember {
8158 Sema &S;
8159 Sema::SpecialMemberDecl D;
8160 bool WasAlreadyBeingDeclared;
8161
8162 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8163 : S(S), D(RD, CSM) {
8164 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8165 if (WasAlreadyBeingDeclared)
8166 // This almost never happens, but if it does, ensure that our cache
8167 // doesn't contain a stale result.
8168 S.SpecialMemberCache.clear();
8169
8170 // FIXME: Register a note to be produced if we encounter an error while
8171 // declaring the special member.
8172 }
8173 ~DeclaringSpecialMember() {
8174 if (!WasAlreadyBeingDeclared)
8175 S.SpecialMembersBeingDeclared.erase(D);
8176 }
8177
8178 /// \brief Are we already trying to declare this special member?
8179 bool isAlreadyBeingDeclared() const {
8180 return WasAlreadyBeingDeclared;
8181 }
8182};
8183}
8184
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008185CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8186 CXXRecordDecl *ClassDecl) {
8187 // C++ [class.ctor]p5:
8188 // A default constructor for a class X is a constructor of class X
8189 // that can be called without an argument. If there is no
8190 // user-declared constructor for class X, a default constructor is
8191 // implicitly declared. An implicitly-declared default constructor
8192 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008193 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008194 "Should not build implicit default constructor!");
8195
Richard Smith8bf22e52012-11-29 01:34:07 +00008196 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8197 if (DSM.isAlreadyBeingDeclared())
8198 return 0;
8199
Richard Smithb5800092012-06-10 05:43:50 +00008200 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8201 CXXDefaultConstructor,
8202 false);
8203
Douglas Gregor6d880b12010-07-01 22:31:05 +00008204 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008205 CanQualType ClassType
8206 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008207 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008208 DeclarationName Name
8209 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008210 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008211 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00008212 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00008213 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00008214 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008215 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008216 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008217 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008218
8219 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008220 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008221 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008222
Richard Smith6b02d462012-12-08 08:32:28 +00008223 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8224 // constructors is easy to compute.
8225 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8226
8227 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008228 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008229
Douglas Gregor9672f922010-07-03 00:47:00 +00008230 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008231 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008232
Douglas Gregor0be31a22010-07-02 17:43:08 +00008233 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008234 PushOnScopeChains(DefaultCon, S, false);
8235 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008236
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008237 return DefaultCon;
8238}
8239
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008240void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8241 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008242 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008243 !Constructor->doesThisDeclarationHaveABody() &&
8244 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008245 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008246
Anders Carlsson423f5d82010-04-23 16:04:08 +00008247 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008248 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008249
Eli Friedmaneaf34142012-10-18 20:14:08 +00008250 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008251 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008252 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008253 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008254 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008255 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008256 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008257 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008258 }
Douglas Gregor73193272010-09-20 16:48:21 +00008259
8260 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008261 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008262
Eli Friedman276dd182013-09-05 00:02:25 +00008263 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008264 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008265
8266 if (ASTMutationListener *L = getASTMutationListener()) {
8267 L->CompletedImplicitDefinition(Constructor);
8268 }
Richard Trieuef64e942013-10-25 00:56:00 +00008269
8270 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008271}
8272
Richard Smith938f40b2011-06-11 17:19:42 +00008273void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008274 // Perform any delayed checks on exception specifications.
8275 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008276}
8277
Richard Smith185be182013-04-10 05:48:59 +00008278namespace {
8279/// Information on inheriting constructors to declare.
8280class InheritingConstructorInfo {
8281public:
8282 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8283 : SemaRef(SemaRef), Derived(Derived) {
8284 // Mark the constructors that we already have in the derived class.
8285 //
8286 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8287 // unless there is a user-declared constructor with the same signature in
8288 // the class where the using-declaration appears.
8289 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8290 }
8291
8292 void inheritAll(CXXRecordDecl *RD) {
8293 visitAll(RD, &InheritingConstructorInfo::inherit);
8294 }
8295
8296private:
8297 /// Information about an inheriting constructor.
8298 struct InheritingConstructor {
8299 InheritingConstructor()
8300 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8301
8302 /// If \c true, a constructor with this signature is already declared
8303 /// in the derived class.
8304 bool DeclaredInDerived;
8305
8306 /// The constructor which is inherited.
8307 const CXXConstructorDecl *BaseCtor;
8308
8309 /// The derived constructor we declared.
8310 CXXConstructorDecl *DerivedCtor;
8311 };
8312
8313 /// Inheriting constructors with a given canonical type. There can be at
8314 /// most one such non-template constructor, and any number of templated
8315 /// constructors.
8316 struct InheritingConstructorsForType {
8317 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008318 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8319 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008320
8321 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8322 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8323 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8324 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8325 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8326 false, S.TPL_TemplateMatch))
8327 return Templates[I].second;
8328 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8329 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008330 }
Richard Smith185be182013-04-10 05:48:59 +00008331
8332 return NonTemplate;
8333 }
8334 };
8335
8336 /// Get or create the inheriting constructor record for a constructor.
8337 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8338 QualType CtorType) {
8339 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8340 .getEntry(SemaRef, Ctor);
8341 }
8342
8343 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8344
8345 /// Process all constructors for a class.
8346 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008347 for (const auto *Ctor : RD->ctors())
8348 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008349 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8350 I(RD->decls_begin()), E(RD->decls_end());
8351 I != E; ++I) {
8352 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8353 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8354 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008355 }
8356 }
Richard Smith185be182013-04-10 05:48:59 +00008357
8358 /// Note that a constructor (or constructor template) was declared in Derived.
8359 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8360 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8361 }
8362
8363 /// Inherit a single constructor.
8364 void inherit(const CXXConstructorDecl *Ctor) {
8365 const FunctionProtoType *CtorType =
8366 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008367 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008368 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8369
8370 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8371
8372 // Core issue (no number yet): the ellipsis is always discarded.
8373 if (EPI.Variadic) {
8374 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8375 SemaRef.Diag(Ctor->getLocation(),
8376 diag::note_using_decl_constructor_ellipsis);
8377 EPI.Variadic = false;
8378 }
8379
8380 // Declare a constructor for each number of parameters.
8381 //
8382 // C++11 [class.inhctor]p1:
8383 // The candidate set of inherited constructors from the class X named in
8384 // the using-declaration consists of [... modulo defects ...] for each
8385 // constructor or constructor template of X, the set of constructors or
8386 // constructor templates that results from omitting any ellipsis parameter
8387 // specification and successively omitting parameters with a default
8388 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008389 unsigned MinParams = minParamsToInherit(Ctor);
8390 unsigned Params = Ctor->getNumParams();
8391 if (Params >= MinParams) {
8392 do
8393 declareCtor(UsingLoc, Ctor,
8394 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008395 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008396 while (Params > MinParams &&
8397 Ctor->getParamDecl(--Params)->hasDefaultArg());
8398 }
Richard Smith185be182013-04-10 05:48:59 +00008399 }
8400
8401 /// Find the using-declaration which specified that we should inherit the
8402 /// constructors of \p Base.
8403 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8404 // No fancy lookup required; just look for the base constructor name
8405 // directly within the derived class.
8406 ASTContext &Context = SemaRef.Context;
8407 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8408 Context.getCanonicalType(Context.getRecordType(Base)));
8409 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8410 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8411 }
8412
8413 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8414 // C++11 [class.inhctor]p3:
8415 // [F]or each constructor template in the candidate set of inherited
8416 // constructors, a constructor template is implicitly declared
8417 if (Ctor->getDescribedFunctionTemplate())
8418 return 0;
8419
8420 // For each non-template constructor in the candidate set of inherited
8421 // constructors other than a constructor having no parameters or a
8422 // copy/move constructor having a single parameter, a constructor is
8423 // implicitly declared [...]
8424 if (Ctor->getNumParams() == 0)
8425 return 1;
8426 if (Ctor->isCopyOrMoveConstructor())
8427 return 2;
8428
8429 // Per discussion on core reflector, never inherit a constructor which
8430 // would become a default, copy, or move constructor of Derived either.
8431 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8432 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8433 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8434 }
8435
8436 /// Declare a single inheriting constructor, inheriting the specified
8437 /// constructor, with the given type.
8438 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8439 QualType DerivedType) {
8440 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8441
8442 // C++11 [class.inhctor]p3:
8443 // ... a constructor is implicitly declared with the same constructor
8444 // characteristics unless there is a user-declared constructor with
8445 // the same signature in the class where the using-declaration appears
8446 if (Entry.DeclaredInDerived)
8447 return;
8448
8449 // C++11 [class.inhctor]p7:
8450 // If two using-declarations declare inheriting constructors with the
8451 // same signature, the program is ill-formed
8452 if (Entry.DerivedCtor) {
8453 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8454 // Only diagnose this once per constructor.
8455 if (Entry.DerivedCtor->isInvalidDecl())
8456 return;
8457 Entry.DerivedCtor->setInvalidDecl();
8458
8459 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8460 SemaRef.Diag(BaseCtor->getLocation(),
8461 diag::note_using_decl_constructor_conflict_current_ctor);
8462 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8463 diag::note_using_decl_constructor_conflict_previous_ctor);
8464 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8465 diag::note_using_decl_constructor_conflict_previous_using);
8466 } else {
8467 // Core issue (no number): if the same inheriting constructor is
8468 // produced by multiple base class constructors from the same base
8469 // class, the inheriting constructor is defined as deleted.
8470 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8471 }
8472
8473 return;
8474 }
8475
8476 ASTContext &Context = SemaRef.Context;
8477 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8478 Context.getCanonicalType(Context.getRecordType(Derived)));
8479 DeclarationNameInfo NameInfo(Name, UsingLoc);
8480
8481 TemplateParameterList *TemplateParams = 0;
8482 if (const FunctionTemplateDecl *FTD =
8483 BaseCtor->getDescribedFunctionTemplate()) {
8484 TemplateParams = FTD->getTemplateParameters();
8485 // We're reusing template parameters from a different DeclContext. This
8486 // is questionable at best, but works out because the template depth in
8487 // both places is guaranteed to be 0.
8488 // FIXME: Rebuild the template parameters in the new context, and
8489 // transform the function type to refer to them.
8490 }
8491
8492 // Build type source info pointing at the using-declaration. This is
8493 // required by template instantiation.
8494 TypeSourceInfo *TInfo =
8495 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8496 FunctionProtoTypeLoc ProtoLoc =
8497 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8498
8499 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8500 Context, Derived, UsingLoc, NameInfo, DerivedType,
8501 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8502 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8503
8504 // Build an unevaluated exception specification for this constructor.
8505 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8506 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8507 EPI.ExceptionSpecType = EST_Unevaluated;
8508 EPI.ExceptionSpecDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008509 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008510 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008511
8512 // Build the parameter declarations.
8513 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008514 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008515 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008516 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008517 ParmVarDecl *PD = ParmVarDecl::Create(
8518 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
Alp Toker9cacbab2014-01-20 20:26:09 +00008519 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
Richard Smith185be182013-04-10 05:48:59 +00008520 PD->setScopeInfo(0, I);
8521 PD->setImplicit();
8522 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008523 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008524 }
8525
8526 // Set up the new constructor.
8527 DerivedCtor->setAccess(BaseCtor->getAccess());
8528 DerivedCtor->setParams(ParamDecls);
8529 DerivedCtor->setInheritedConstructor(BaseCtor);
8530 if (BaseCtor->isDeleted())
8531 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8532
8533 // If this is a constructor template, build the template declaration.
8534 if (TemplateParams) {
8535 FunctionTemplateDecl *DerivedTemplate =
8536 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8537 TemplateParams, DerivedCtor);
8538 DerivedTemplate->setAccess(BaseCtor->getAccess());
8539 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8540 Derived->addDecl(DerivedTemplate);
8541 } else {
8542 Derived->addDecl(DerivedCtor);
8543 }
8544
8545 Entry.BaseCtor = BaseCtor;
8546 Entry.DerivedCtor = DerivedCtor;
8547 }
8548
8549 Sema &SemaRef;
8550 CXXRecordDecl *Derived;
8551 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8552 MapType Map;
8553};
8554}
8555
8556void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8557 // Defer declaring the inheriting constructors until the class is
8558 // instantiated.
8559 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008560 return;
8561
Richard Smith185be182013-04-10 05:48:59 +00008562 // Find base classes from which we might inherit constructors.
8563 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008564 for (const auto &BaseIt : ClassDecl->bases())
8565 if (BaseIt.getInheritConstructors())
8566 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008567
Richard Smith185be182013-04-10 05:48:59 +00008568 // Go no further if we're not inheriting any constructors.
8569 if (InheritedBases.empty())
8570 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008571
Richard Smith185be182013-04-10 05:48:59 +00008572 // Declare the inherited constructors.
8573 InheritingConstructorInfo ICI(*this, ClassDecl);
8574 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8575 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008576}
8577
Richard Smithc2bc61b2013-03-18 21:12:30 +00008578void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8579 CXXConstructorDecl *Constructor) {
8580 CXXRecordDecl *ClassDecl = Constructor->getParent();
8581 assert(Constructor->getInheritedConstructor() &&
8582 !Constructor->doesThisDeclarationHaveABody() &&
8583 !Constructor->isDeleted());
8584
8585 SynthesizedFunctionScope Scope(*this, Constructor);
8586 DiagnosticErrorTrap Trap(Diags);
8587 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8588 Trap.hasErrorOccurred()) {
8589 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8590 << Context.getTagDeclType(ClassDecl);
8591 Constructor->setInvalidDecl();
8592 return;
8593 }
8594
8595 SourceLocation Loc = Constructor->getLocation();
8596 Constructor->setBody(new (Context) CompoundStmt(Loc));
8597
Eli Friedman276dd182013-09-05 00:02:25 +00008598 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008599 MarkVTableUsed(CurrentLocation, ClassDecl);
8600
8601 if (ASTMutationListener *L = getASTMutationListener()) {
8602 L->CompletedImplicitDefinition(Constructor);
8603 }
8604}
8605
8606
Alexis Huntf91729462011-05-12 22:46:25 +00008607Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008608Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8609 CXXRecordDecl *ClassDecl = MD->getParent();
8610
Douglas Gregorf1203042010-07-01 19:09:28 +00008611 // C++ [except.spec]p14:
8612 // An implicitly declared special member function (Clause 12) shall have
8613 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008614 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008615 if (ClassDecl->isInvalidDecl())
8616 return ExceptSpec;
8617
Douglas Gregorf1203042010-07-01 19:09:28 +00008618 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008619 for (const auto &B : ClassDecl->bases()) {
8620 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008621 continue;
8622
Aaron Ballman574705e2014-03-13 15:41:46 +00008623 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8624 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008625 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008626 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008627
Douglas Gregorf1203042010-07-01 19:09:28 +00008628 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008629 for (const auto &B : ClassDecl->vbases()) {
8630 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8631 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008632 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008633 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008634
Douglas Gregorf1203042010-07-01 19:09:28 +00008635 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008636 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008637 if (const RecordType *RecordTy
8638 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008639 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008640 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008641 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008642
Alexis Huntf91729462011-05-12 22:46:25 +00008643 return ExceptSpec;
8644}
8645
8646CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8647 // C++ [class.dtor]p2:
8648 // If a class has no user-declared destructor, a destructor is
8649 // declared implicitly. An implicitly-declared destructor is an
8650 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008651 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008652
Richard Smith8bf22e52012-11-29 01:34:07 +00008653 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8654 if (DSM.isAlreadyBeingDeclared())
8655 return 0;
8656
Douglas Gregor7454c562010-07-02 20:37:36 +00008657 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008658 CanQualType ClassType
8659 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008660 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008661 DeclarationName Name
8662 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008663 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008664 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008665 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8666 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008667 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008668 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008669 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008670 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008671
8672 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008673 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008674 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008675
Richard Smith6b02d462012-12-08 08:32:28 +00008676 AddOverriddenMethods(ClassDecl, Destructor);
8677
8678 // We don't need to use SpecialMemberIsTrivial here; triviality for
8679 // destructors is easy to compute.
8680 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8681
8682 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008683 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008684
Douglas Gregor7454c562010-07-02 20:37:36 +00008685 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008686 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008687
Douglas Gregor7454c562010-07-02 20:37:36 +00008688 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008689 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008690 PushOnScopeChains(Destructor, S, false);
8691 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008692
Douglas Gregorf1203042010-07-01 19:09:28 +00008693 return Destructor;
8694}
8695
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008696void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008697 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008698 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008699 !Destructor->doesThisDeclarationHaveABody() &&
8700 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008701 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008702 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008703 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008704
Douglas Gregor54818f02010-05-12 16:39:35 +00008705 if (Destructor->isInvalidDecl())
8706 return;
8707
Eli Friedmaneaf34142012-10-18 20:14:08 +00008708 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008709
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008710 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008711 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8712 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008713
Douglas Gregor54818f02010-05-12 16:39:35 +00008714 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008715 Diag(CurrentLocation, diag::note_member_synthesized_at)
8716 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8717
8718 Destructor->setInvalidDecl();
8719 return;
8720 }
8721
Douglas Gregor73193272010-09-20 16:48:21 +00008722 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008723 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008724 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008725 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008726
8727 if (ASTMutationListener *L = getASTMutationListener()) {
8728 L->CompletedImplicitDefinition(Destructor);
8729 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008730}
8731
Richard Smith84973e52012-04-21 18:42:51 +00008732/// \brief Perform any semantic analysis which needs to be delayed until all
8733/// pending class member declarations have been parsed.
8734void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008735 // If the context is an invalid C++ class, just suppress these checks.
8736 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8737 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008738 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008739 DelayedDestructorExceptionSpecChecks.clear();
8740 return;
8741 }
8742 }
Richard Smith84973e52012-04-21 18:42:51 +00008743}
8744
Richard Smithd3b5c9082012-07-27 04:22:15 +00008745void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8746 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008747 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008748 "adjusting dtor exception specs was introduced in c++11");
8749
Sebastian Redl623ea822011-05-19 05:13:44 +00008750 // C++11 [class.dtor]p3:
8751 // A declaration of a destructor that does not have an exception-
8752 // specification is implicitly considered to have the same exception-
8753 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008754 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008755 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008756 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008757 return;
8758
Chandler Carruth9a797572011-09-20 04:55:26 +00008759 // Replace the destructor's type, building off the existing one. Fortunately,
8760 // the only thing of interest in the destructor type is its extended info.
8761 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008762 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8763 EPI.ExceptionSpecType = EST_Unevaluated;
8764 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008765 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008766
Sebastian Redl623ea822011-05-19 05:13:44 +00008767 // FIXME: If the destructor has a body that could throw, and the newly created
8768 // spec doesn't allow exceptions, we should emit a warning, because this
8769 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008770 // However, we don't have a body or an exception specification yet, so it
8771 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008772}
8773
Pavel Labath58934982013-08-30 08:52:28 +00008774namespace {
8775/// \brief An abstract base class for all helper classes used in building the
8776// copy/move operators. These classes serve as factory functions and help us
8777// avoid using the same Expr* in the AST twice.
8778class ExprBuilder {
8779 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8780 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8781
8782protected:
8783 static Expr *assertNotNull(Expr *E) {
8784 assert(E && "Expression construction must not fail.");
8785 return E;
8786 }
8787
8788public:
8789 ExprBuilder() {}
8790 virtual ~ExprBuilder() {}
8791
8792 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8793};
8794
8795class RefBuilder: public ExprBuilder {
8796 VarDecl *Var;
8797 QualType VarType;
8798
8799public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008800 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008801 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8802 }
8803
8804 RefBuilder(VarDecl *Var, QualType VarType)
8805 : Var(Var), VarType(VarType) {}
8806};
8807
8808class ThisBuilder: public ExprBuilder {
8809public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008810 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008811 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8812 }
8813};
8814
8815class CastBuilder: public ExprBuilder {
8816 const ExprBuilder &Builder;
8817 QualType Type;
8818 ExprValueKind Kind;
8819 const CXXCastPath &Path;
8820
8821public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008822 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008823 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8824 CK_UncheckedDerivedToBase, Kind,
8825 &Path).take());
8826 }
8827
8828 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8829 const CXXCastPath &Path)
8830 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8831};
8832
8833class DerefBuilder: public ExprBuilder {
8834 const ExprBuilder &Builder;
8835
8836public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008837 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008838 return assertNotNull(
8839 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8840 }
8841
8842 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8843};
8844
8845class MemberBuilder: public ExprBuilder {
8846 const ExprBuilder &Builder;
8847 QualType Type;
8848 CXXScopeSpec SS;
8849 bool IsArrow;
8850 LookupResult &MemberLookup;
8851
8852public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008853 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008854 return assertNotNull(S.BuildMemberReferenceExpr(
8855 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8856 MemberLookup, 0).take());
8857 }
8858
8859 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8860 LookupResult &MemberLookup)
8861 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8862 MemberLookup(MemberLookup) {}
8863};
8864
8865class MoveCastBuilder: public ExprBuilder {
8866 const ExprBuilder &Builder;
8867
8868public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008869 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008870 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8871 }
8872
8873 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8874};
8875
8876class LvalueConvBuilder: public ExprBuilder {
8877 const ExprBuilder &Builder;
8878
8879public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008880 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008881 return assertNotNull(
8882 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8883 }
8884
8885 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8886};
8887
8888class SubscriptBuilder: public ExprBuilder {
8889 const ExprBuilder &Base;
8890 const ExprBuilder &Index;
8891
8892public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008893 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008894 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8895 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8896 }
8897
8898 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8899 : Base(Base), Index(Index) {}
8900};
8901
8902} // end anonymous namespace
8903
Richard Smith41ae3282012-11-14 00:50:40 +00008904/// When generating a defaulted copy or move assignment operator, if a field
8905/// should be copied with __builtin_memcpy rather than via explicit assignments,
8906/// do so. This optimization only applies for arrays of scalars, and for arrays
8907/// of class type where the selected copy/move-assignment operator is trivial.
8908static StmtResult
8909buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008910 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00008911 // Compute the size of the memory buffer to be copied.
8912 QualType SizeType = S.Context.getSizeType();
8913 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8914 S.Context.getTypeSizeInChars(T).getQuantity());
8915
8916 // Take the address of the field references for "from" and "to". We
8917 // directly construct UnaryOperators here because semantic analysis
8918 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00008919 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008920 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8921 S.Context.getPointerType(From->getType()),
8922 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00008923 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008924 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8925 S.Context.getPointerType(To->getType()),
8926 VK_RValue, OK_Ordinary, Loc);
8927
8928 const Type *E = T->getBaseElementTypeUnsafe();
8929 bool NeedsCollectableMemCpy =
8930 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8931
8932 // Create a reference to the __builtin_objc_memmove_collectable function
8933 StringRef MemCpyName = NeedsCollectableMemCpy ?
8934 "__builtin_objc_memmove_collectable" :
8935 "__builtin_memcpy";
8936 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8937 Sema::LookupOrdinaryName);
8938 S.LookupName(R, S.TUScope, true);
8939
8940 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8941 if (!MemCpy)
8942 // Something went horribly wrong earlier, and we will have complained
8943 // about it.
8944 return StmtError();
8945
8946 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8947 VK_RValue, Loc, 0);
8948 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8949
8950 Expr *CallArgs[] = {
8951 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8952 };
8953 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8954 Loc, CallArgs, Loc);
8955
8956 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8957 return S.Owned(Call.takeAs<Stmt>());
8958}
8959
Sebastian Redl22653ba2011-08-30 19:58:05 +00008960/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00008961/// \c To.
8962///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008963/// This routine is used to copy/move the members of a class with an
8964/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00008965/// copied are arrays, this routine builds for loops to copy them.
8966///
8967/// \param S The Sema object used for type-checking.
8968///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008969/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008970///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008971/// \param T The type of the expressions being copied/moved. Both expressions
8972/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008973///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008974/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008975///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008976/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008977///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008978/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008979/// Otherwise, it's a non-static member subobject.
8980///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008981/// \param Copying Whether we're copying or moving.
8982///
Douglas Gregorb139cd52010-05-01 20:49:11 +00008983/// \param Depth Internal parameter recording the depth of the recursion.
8984///
Richard Smith41ae3282012-11-14 00:50:40 +00008985/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8986/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00008987static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00008988buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008989 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00008990 bool CopyingBaseSubobject, bool Copying,
8991 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00008992 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00008993 // Each subobject is assigned in the manner appropriate to its type:
8994 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00008995 // - if the subobject is of class type, as if by a call to operator= with
8996 // the subobject as the object expression and the corresponding
8997 // subobject of x as a single function argument (as if by explicit
8998 // qualification; that is, ignoring any possible virtual overriding
8999 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009000 //
9001 // C++03 [class.copy]p13:
9002 // - if the subobject is of class type, the copy assignment operator for
9003 // the class is used (as if by explicit qualification; that is,
9004 // ignoring any possible virtual overriding functions in more derived
9005 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009006 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9007 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009008
Douglas Gregorb139cd52010-05-01 20:49:11 +00009009 // Look for operator=.
9010 DeclarationName Name
9011 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9012 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9013 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009014
Richard Smith52c0b582012-11-13 00:54:12 +00009015 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9016 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009017 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009018 LookupResult::Filter F = OpLookup.makeFilter();
9019 while (F.hasNext()) {
9020 NamedDecl *D = F.next();
9021 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9022 if (Method->isCopyAssignmentOperator() ||
9023 (!Copying && Method->isMoveAssignmentOperator()))
9024 continue;
9025
9026 F.erase();
9027 }
9028 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009029 }
Richard Smith52c0b582012-11-13 00:54:12 +00009030
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009031 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009032 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009033 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009034 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009035 // ambiguities), we need to cast "this" to that subobject type; to
9036 // ensure that we don't go through the virtual call mechanism, we need
9037 // to qualify the operator= name with the base class (see below). However,
9038 // this means that if the base class has a protected copy assignment
9039 // operator, the protected member access check will fail. So, we
9040 // rewrite "protected" access to "public" access in this case, since we
9041 // know by construction that we're calling from a derived class.
9042 if (CopyingBaseSubobject) {
9043 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9044 L != LEnd; ++L) {
9045 if (L.getAccess() == AS_protected)
9046 L.setAccess(AS_public);
9047 }
9048 }
Richard Smith52c0b582012-11-13 00:54:12 +00009049
Douglas Gregorb139cd52010-05-01 20:49:11 +00009050 // Create the nested-name-specifier that will be used to qualify the
9051 // reference to operator=; this is required to suppress the virtual
9052 // call mechanism.
9053 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009054 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009055 SS.MakeTrivial(S.Context,
9056 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009057 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009058 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009059
Douglas Gregorb139cd52010-05-01 20:49:11 +00009060 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009061 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009062 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9063 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00009064 /*FirstQualifierInScope=*/0,
9065 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009066 /*TemplateArgs=*/0,
9067 /*SuppressQualifierCheck=*/true);
9068 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009069 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009070
Douglas Gregorb139cd52010-05-01 20:49:11 +00009071 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009072
Pavel Labath58934982013-08-30 08:52:28 +00009073 Expr *FromInst = From.build(S, Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009074 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009075 OpEqualRef.takeAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009076 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009077 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009078 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009079
Richard Smith41ae3282012-11-14 00:50:40 +00009080 // If we built a call to a trivial 'operator=' while copying an array,
9081 // bail out. We'll replace the whole shebang with a memcpy.
9082 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9083 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9084 return StmtResult((Stmt*)0);
9085
Richard Smith52c0b582012-11-13 00:54:12 +00009086 // Convert to an expression-statement, and clean up any produced
9087 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009088 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009089 }
John McCallab8c2732010-03-16 06:11:48 +00009090
Richard Smith52c0b582012-11-13 00:54:12 +00009091 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009092 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009093 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009094 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009095 ExprResult Assignment = S.CreateBuiltinBinOp(
9096 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009097 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009098 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009099 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009100 }
Richard Smith52c0b582012-11-13 00:54:12 +00009101
9102 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009103 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009104
Douglas Gregorb139cd52010-05-01 20:49:11 +00009105 // Construct a loop over the array bounds, e.g.,
9106 //
9107 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9108 //
9109 // that will copy each of the array elements.
9110 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009111
Douglas Gregorb139cd52010-05-01 20:49:11 +00009112 // Create the iteration variable.
9113 IdentifierInfo *IterationVarName = 0;
9114 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009115 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009116 llvm::raw_svector_ostream OS(Str);
9117 OS << "__i" << Depth;
9118 IterationVarName = &S.Context.Idents.get(OS.str());
9119 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009120 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009121 IterationVarName, SizeType,
9122 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009123 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009124
Douglas Gregorb139cd52010-05-01 20:49:11 +00009125 // Initialize the iteration variable to zero.
9126 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009127 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009128
Pavel Labath58934982013-08-30 08:52:28 +00009129 // Creates a reference to the iteration variable.
9130 RefBuilder IterationVarRef(IterationVar, SizeType);
9131 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009132
Douglas Gregorb139cd52010-05-01 20:49:11 +00009133 // Create the DeclStmt that holds the iteration variable.
9134 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009135
Douglas Gregorb139cd52010-05-01 20:49:11 +00009136 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009137 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9138 MoveCastBuilder FromIndexMove(FromIndexCopy);
9139 const ExprBuilder *FromIndex;
9140 if (Copying)
9141 FromIndex = &FromIndexCopy;
9142 else
9143 FromIndex = &FromIndexMove;
9144
9145 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009146
9147 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009148 StmtResult Copy =
9149 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009150 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009151 Copying, Depth + 1);
9152 // Bail out if copying fails or if we determined that we should use memcpy.
9153 if (Copy.isInvalid() || !Copy.get())
9154 return Copy;
9155
9156 // Create the comparison against the array bound.
9157 llvm::APInt Upper
9158 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9159 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009160 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009161 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9162 BO_NE, S.Context.BoolTy,
9163 VK_RValue, OK_Ordinary, Loc, false);
9164
9165 // Create the pre-increment of the iteration variable.
9166 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009167 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9168 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009169
Douglas Gregorb139cd52010-05-01 20:49:11 +00009170 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009171 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009172 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00009173 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00009174 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009175}
9176
Richard Smith41ae3282012-11-14 00:50:40 +00009177static StmtResult
9178buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009179 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009180 bool CopyingBaseSubobject, bool Copying) {
9181 // Maybe we should use a memcpy?
9182 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9183 T.isTriviallyCopyableType(S.Context))
9184 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9185
9186 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9187 CopyingBaseSubobject,
9188 Copying, 0));
9189
9190 // If we ended up picking a trivial assignment operator for an array of a
9191 // non-trivially-copyable class type, just emit a memcpy.
9192 if (!Result.isInvalid() && !Result.get())
9193 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9194
9195 return Result;
9196}
9197
Richard Smithd3b5c9082012-07-27 04:22:15 +00009198Sema::ImplicitExceptionSpecification
9199Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9200 CXXRecordDecl *ClassDecl = MD->getParent();
9201
9202 ImplicitExceptionSpecification ExceptSpec(*this);
9203 if (ClassDecl->isInvalidDecl())
9204 return ExceptSpec;
9205
9206 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009207 assert(T->getNumParams() == 1 && "not a copy assignment op");
9208 unsigned ArgQuals =
9209 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009210
Douglas Gregor68e11362010-07-01 17:48:08 +00009211 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009212 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009213 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009214
9215 // It is unspecified whether or not an implicit copy assignment operator
9216 // attempts to deduplicate calls to assignment operators of virtual bases are
9217 // made. As such, this exception specification is effectively unspecified.
9218 // Based on a similar decision made for constness in C++0x, we're erring on
9219 // the side of assuming such calls to be made regardless of whether they
9220 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009221 for (const auto &Base : ClassDecl->bases()) {
9222 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009223 continue;
9224
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009225 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009226 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009227 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9228 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009229 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009230 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009231
Aaron Ballman445a9392014-03-13 16:15:17 +00009232 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009233 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009234 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009235 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9236 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009237 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009238 }
9239
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009240 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009241 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009242 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9243 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009244 LookupCopyingAssignment(FieldClassDecl,
9245 ArgQuals | FieldType.getCVRQualifiers(),
9246 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009247 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009248 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009249 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009250
Richard Smithd3b5c9082012-07-27 04:22:15 +00009251 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009252}
9253
9254CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9255 // Note: The following rules are largely analoguous to the copy
9256 // constructor rules. Note that virtual bases are not taken into account
9257 // for determining the argument type of the operator. Note also that
9258 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009259 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009260
Richard Smith8bf22e52012-11-29 01:34:07 +00009261 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9262 if (DSM.isAlreadyBeingDeclared())
9263 return 0;
9264
Alexis Hunt119f3652011-05-14 05:23:20 +00009265 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9266 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009267 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9268 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009269 ArgType = ArgType.withConst();
9270 ArgType = Context.getLValueReferenceType(ArgType);
9271
Richard Smith99005e62013-05-07 03:19:20 +00009272 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9273 CXXCopyAssignment,
9274 Const);
9275
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009276 // An implicitly-declared copy assignment operator is an inline public
9277 // member of its class.
9278 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009279 SourceLocation ClassLoc = ClassDecl->getLocation();
9280 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009281 CXXMethodDecl *CopyAssignment =
9282 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9283 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9284 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009285 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009286 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009287 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009288
9289 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009290 FunctionProtoType::ExtProtoInfo EPI =
9291 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009292 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009293
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009294 // Add the parameter to the operator.
9295 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009296 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009297 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009298 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009299 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009300
Richard Smith6b02d462012-12-08 08:32:28 +00009301 AddOverriddenMethods(ClassDecl, CopyAssignment);
9302
9303 CopyAssignment->setTrivial(
9304 ClassDecl->needsOverloadResolutionForCopyAssignment()
9305 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9306 : ClassDecl->hasTrivialCopyAssignment());
9307
Richard Smith852265f2012-03-30 20:53:28 +00009308 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009309 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009310
Richard Smith6b02d462012-12-08 08:32:28 +00009311 // Note that we have added this copy-assignment operator.
9312 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9313
9314 if (Scope *S = getScopeForContext(ClassDecl))
9315 PushOnScopeChains(CopyAssignment, S, false);
9316 ClassDecl->addDecl(CopyAssignment);
9317
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009318 return CopyAssignment;
9319}
9320
Richard Smithd577fbb2013-06-13 03:23:42 +00009321/// Diagnose an implicit copy operation for a class which is odr-used, but
9322/// which is deprecated because the class has a user-declared copy constructor,
9323/// copy assignment operator, or destructor.
9324static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9325 SourceLocation UseLoc) {
9326 assert(CopyOp->isImplicit());
9327
9328 CXXRecordDecl *RD = CopyOp->getParent();
9329 CXXMethodDecl *UserDeclaredOperation = 0;
9330
9331 // In Microsoft mode, assignment operations don't affect constructors and
9332 // vice versa.
9333 if (RD->hasUserDeclaredDestructor()) {
9334 UserDeclaredOperation = RD->getDestructor();
9335 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9336 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009337 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009338 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009339 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009340 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009341 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009342 break;
9343 }
9344 }
9345 assert(UserDeclaredOperation);
9346 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9347 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009348 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009349 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009350 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009351 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009352 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009353 break;
9354 }
9355 }
9356 assert(UserDeclaredOperation);
9357 }
9358
9359 if (UserDeclaredOperation) {
9360 S.Diag(UserDeclaredOperation->getLocation(),
9361 diag::warn_deprecated_copy_operation)
9362 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9363 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9364 S.Diag(UseLoc, diag::note_member_synthesized_at)
9365 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9366 : Sema::CXXCopyAssignment)
9367 << RD;
9368 }
9369}
9370
Douglas Gregorb139cd52010-05-01 20:49:11 +00009371void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9372 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009373 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009374 CopyAssignOperator->isOverloadedOperator() &&
9375 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009376 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9377 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009378 "DefineImplicitCopyAssignment called for wrong function");
9379
9380 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9381
9382 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9383 CopyAssignOperator->setInvalidDecl();
9384 return;
9385 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009386
9387 // C++11 [class.copy]p18:
9388 // The [definition of an implicitly declared copy assignment operator] is
9389 // deprecated if the class has a user-declared copy constructor or a
9390 // user-declared destructor.
9391 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9392 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9393
Eli Friedman276dd182013-09-05 00:02:25 +00009394 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009395
Eli Friedmaneaf34142012-10-18 20:14:08 +00009396 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009397 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009398
9399 // C++0x [class.copy]p30:
9400 // The implicitly-defined or explicitly-defaulted copy assignment operator
9401 // for a non-union class X performs memberwise copy assignment of its
9402 // subobjects. The direct base classes of X are assigned first, in the
9403 // order of their declaration in the base-specifier-list, and then the
9404 // immediate non-static data members of X are assigned, in the order in
9405 // which they were declared in the class definition.
9406
9407 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009408 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009409
9410 // The parameter for the "other" object, which we are copying from.
9411 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9412 Qualifiers OtherQuals = Other->getType().getQualifiers();
9413 QualType OtherRefType = Other->getType();
9414 if (const LValueReferenceType *OtherRef
9415 = OtherRefType->getAs<LValueReferenceType>()) {
9416 OtherRefType = OtherRef->getPointeeType();
9417 OtherQuals = OtherRefType.getQualifiers();
9418 }
9419
9420 // Our location for everything implicitly-generated.
9421 SourceLocation Loc = CopyAssignOperator->getLocation();
9422
Pavel Labath58934982013-08-30 08:52:28 +00009423 // Builds a DeclRefExpr for the "other" object.
9424 RefBuilder OtherRef(Other, OtherRefType);
9425
9426 // Builds the "this" pointer.
9427 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009428
9429 // Assign base classes.
9430 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009431 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009432 // Form the assignment:
9433 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009434 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009435 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009436 Invalid = true;
9437 continue;
9438 }
9439
John McCallcf142162010-08-07 06:22:56 +00009440 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009441 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009442
Douglas Gregorb139cd52010-05-01 20:49:11 +00009443 // Construct the "from" expression, which is an implicit cast to the
9444 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009445 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9446 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009447
9448 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009449 DerefBuilder DerefThis(This);
9450 CastBuilder To(DerefThis,
9451 Context.getCVRQualifiedType(
9452 BaseType, CopyAssignOperator->getTypeQualifiers()),
9453 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009454
9455 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009456 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009457 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009458 /*CopyingBaseSubobject=*/true,
9459 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009460 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009461 Diag(CurrentLocation, diag::note_member_synthesized_at)
9462 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9463 CopyAssignOperator->setInvalidDecl();
9464 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009465 }
9466
9467 // Success! Record the copy.
9468 Statements.push_back(Copy.takeAs<Expr>());
9469 }
9470
Douglas Gregorb139cd52010-05-01 20:49:11 +00009471 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009472 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009473 if (Field->isUnnamedBitfield())
9474 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009475
9476 if (Field->isInvalidDecl()) {
9477 Invalid = true;
9478 continue;
9479 }
9480
Douglas Gregorb139cd52010-05-01 20:49:11 +00009481 // Check for members of reference type; we can't copy those.
9482 if (Field->getType()->isReferenceType()) {
9483 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9484 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9485 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009486 Diag(CurrentLocation, diag::note_member_synthesized_at)
9487 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009488 Invalid = true;
9489 continue;
9490 }
9491
9492 // Check for members of const-qualified, non-class type.
9493 QualType BaseType = Context.getBaseElementType(Field->getType());
9494 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9495 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9496 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9497 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009498 Diag(CurrentLocation, diag::note_member_synthesized_at)
9499 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009500 Invalid = true;
9501 continue;
9502 }
John McCall1b1a1db2011-06-17 00:18:42 +00009503
9504 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009505 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9506 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009507
9508 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009509 if (FieldType->isIncompleteArrayType()) {
9510 assert(ClassDecl->hasFlexibleArrayMember() &&
9511 "Incomplete array type is not valid");
9512 continue;
9513 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009514
9515 // Build references to the field in the object we're copying from and to.
9516 CXXScopeSpec SS; // Intentionally empty
9517 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9518 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009519 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009520 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009521
9522 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9523
9524 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009525
Douglas Gregorb139cd52010-05-01 20:49:11 +00009526 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009527 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009528 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009529 /*CopyingBaseSubobject=*/false,
9530 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009531 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009532 Diag(CurrentLocation, diag::note_member_synthesized_at)
9533 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9534 CopyAssignOperator->setInvalidDecl();
9535 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009536 }
9537
9538 // Success! Record the copy.
9539 Statements.push_back(Copy.takeAs<Stmt>());
9540 }
9541
9542 if (!Invalid) {
9543 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009544 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009545
John McCalldadc5752010-08-24 06:29:42 +00009546 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009547 if (Return.isInvalid())
9548 Invalid = true;
9549 else {
9550 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009551
9552 if (Trap.hasErrorOccurred()) {
9553 Diag(CurrentLocation, diag::note_member_synthesized_at)
9554 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9555 Invalid = true;
9556 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009557 }
9558 }
9559
9560 if (Invalid) {
9561 CopyAssignOperator->setInvalidDecl();
9562 return;
9563 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009564
9565 StmtResult Body;
9566 {
9567 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009568 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009569 /*isStmtExpr=*/false);
9570 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9571 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009572 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009573
9574 if (ASTMutationListener *L = getASTMutationListener()) {
9575 L->CompletedImplicitDefinition(CopyAssignOperator);
9576 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009577}
9578
Sebastian Redl22653ba2011-08-30 19:58:05 +00009579Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009580Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9581 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009582
Richard Smithd3b5c9082012-07-27 04:22:15 +00009583 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009584 if (ClassDecl->isInvalidDecl())
9585 return ExceptSpec;
9586
9587 // C++0x [except.spec]p14:
9588 // An implicitly declared special member function (Clause 12) shall have an
9589 // exception-specification. [...]
9590
9591 // It is unspecified whether or not an implicit move assignment operator
9592 // attempts to deduplicate calls to assignment operators of virtual bases are
9593 // made. As such, this exception specification is effectively unspecified.
9594 // Based on a similar decision made for constness in C++0x, we're erring on
9595 // the side of assuming such calls to be made regardless of whether they
9596 // actually happen.
9597 // Note that a move constructor is not implicitly declared when there are
9598 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009599 for (const auto &Base : ClassDecl->bases()) {
9600 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009601 continue;
9602
9603 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009604 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009605 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009606 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009607 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009608 }
9609
Aaron Ballman445a9392014-03-13 16:15:17 +00009610 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009611 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009612 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009613 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009614 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009615 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009616 }
9617
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009618 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009619 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009620 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009621 if (CXXMethodDecl *MoveAssign =
9622 LookupMovingAssignment(FieldClassDecl,
9623 FieldType.getCVRQualifiers(),
9624 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009625 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009626 }
9627 }
9628
9629 return ExceptSpec;
9630}
9631
9632CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009633 assert(ClassDecl->needsImplicitMoveAssignment());
9634
Richard Smith8bf22e52012-11-29 01:34:07 +00009635 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9636 if (DSM.isAlreadyBeingDeclared())
9637 return 0;
9638
Sebastian Redl22653ba2011-08-30 19:58:05 +00009639 // Note: The following rules are largely analoguous to the move
9640 // constructor rules.
9641
Sebastian Redl22653ba2011-08-30 19:58:05 +00009642 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9643 QualType RetType = Context.getLValueReferenceType(ArgType);
9644 ArgType = Context.getRValueReferenceType(ArgType);
9645
Richard Smith99005e62013-05-07 03:19:20 +00009646 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9647 CXXMoveAssignment,
9648 false);
9649
Sebastian Redl22653ba2011-08-30 19:58:05 +00009650 // An implicitly-declared move assignment operator is an inline public
9651 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009652 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9653 SourceLocation ClassLoc = ClassDecl->getLocation();
9654 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009655 CXXMethodDecl *MoveAssignment =
9656 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9657 /*TInfo=*/0, /*StorageClass=*/SC_None,
9658 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009659 MoveAssignment->setAccess(AS_public);
9660 MoveAssignment->setDefaulted();
9661 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009662
Richard Smithd3b5c9082012-07-27 04:22:15 +00009663 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009664 FunctionProtoType::ExtProtoInfo EPI =
9665 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009666 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009667
Sebastian Redl22653ba2011-08-30 19:58:05 +00009668 // Add the parameter to the operator.
9669 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9670 ClassLoc, ClassLoc, /*Id=*/0,
9671 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009672 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009673 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009674
Richard Smith6b02d462012-12-08 08:32:28 +00009675 AddOverriddenMethods(ClassDecl, MoveAssignment);
9676
9677 MoveAssignment->setTrivial(
9678 ClassDecl->needsOverloadResolutionForMoveAssignment()
9679 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9680 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009681
Richard Smithd951a1d2012-02-18 02:02:13 +00009682 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009683 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9684 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009685 }
9686
Richard Smith6b02d462012-12-08 08:32:28 +00009687 // Note that we have added this copy-assignment operator.
9688 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9689
Sebastian Redl22653ba2011-08-30 19:58:05 +00009690 if (Scope *S = getScopeForContext(ClassDecl))
9691 PushOnScopeChains(MoveAssignment, S, false);
9692 ClassDecl->addDecl(MoveAssignment);
9693
Sebastian Redl22653ba2011-08-30 19:58:05 +00009694 return MoveAssignment;
9695}
9696
Richard Smithb2504bd2013-11-04 04:26:14 +00009697/// Check if we're implicitly defining a move assignment operator for a class
9698/// with virtual bases. Such a move assignment might move-assign the virtual
9699/// base multiple times.
9700static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9701 SourceLocation CurrentLocation) {
9702 assert(!Class->isDependentContext() && "should not define dependent move");
9703
9704 // Only a virtual base could get implicitly move-assigned multiple times.
9705 // Only a non-trivial move assignment can observe this. We only want to
9706 // diagnose if we implicitly define an assignment operator that assigns
9707 // two base classes, both of which move-assign the same virtual base.
9708 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9709 Class->getNumBases() < 2)
9710 return;
9711
9712 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9713 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9714 VBaseMap VBases;
9715
Aaron Ballman574705e2014-03-13 15:41:46 +00009716 for (auto &BI : Class->bases()) {
9717 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009718 while (!Worklist.empty()) {
9719 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9720 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9721
9722 // If the base has no non-trivial move assignment operators,
9723 // we don't care about moves from it.
9724 if (!Base->hasNonTrivialMoveAssignment())
9725 continue;
9726
9727 // If there's nothing virtual here, skip it.
9728 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9729 continue;
9730
9731 // If we're not actually going to call a move assignment for this base,
9732 // or the selected move assignment is trivial, skip it.
9733 Sema::SpecialMemberOverloadResult *SMOR =
9734 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9735 /*ConstArg*/false, /*VolatileArg*/false,
9736 /*RValueThis*/true, /*ConstThis*/false,
9737 /*VolatileThis*/false);
9738 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9739 !SMOR->getMethod()->isMoveAssignmentOperator())
9740 continue;
9741
9742 if (BaseSpec->isVirtual()) {
9743 // We're going to move-assign this virtual base, and its move
9744 // assignment operator is not trivial. If this can happen for
9745 // multiple distinct direct bases of Class, diagnose it. (If it
9746 // only happens in one base, we'll diagnose it when synthesizing
9747 // that base class's move assignment operator.)
9748 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +00009749 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +00009750 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +00009751 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009752 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9753 << Class << Base;
9754 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9755 << (Base->getCanonicalDecl() ==
9756 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9757 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +00009758 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +00009759 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +00009760 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9761 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +00009762
9763 // Only diagnose each vbase once.
9764 Existing = 0;
9765 }
9766 } else {
9767 // Only walk over bases that have defaulted move assignment operators.
9768 // We assume that any user-provided move assignment operator handles
9769 // the multiple-moves-of-vbase case itself somehow.
9770 if (!SMOR->getMethod()->isDefaulted())
9771 continue;
9772
9773 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +00009774 for (auto &BI : Base->bases())
9775 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009776 }
9777 }
9778 }
9779}
9780
Sebastian Redl22653ba2011-08-30 19:58:05 +00009781void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9782 CXXMethodDecl *MoveAssignOperator) {
9783 assert((MoveAssignOperator->isDefaulted() &&
9784 MoveAssignOperator->isOverloadedOperator() &&
9785 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009786 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9787 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009788 "DefineImplicitMoveAssignment called for wrong function");
9789
9790 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9791
9792 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9793 MoveAssignOperator->setInvalidDecl();
9794 return;
9795 }
9796
Eli Friedman276dd182013-09-05 00:02:25 +00009797 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009798
Eli Friedmaneaf34142012-10-18 20:14:08 +00009799 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009800 DiagnosticErrorTrap Trap(Diags);
9801
9802 // C++0x [class.copy]p28:
9803 // The implicitly-defined or move assignment operator for a non-union class
9804 // X performs memberwise move assignment of its subobjects. The direct base
9805 // classes of X are assigned first, in the order of their declaration in the
9806 // base-specifier-list, and then the immediate non-static data members of X
9807 // are assigned, in the order in which they were declared in the class
9808 // definition.
9809
Richard Smithb2504bd2013-11-04 04:26:14 +00009810 // Issue a warning if our implicit move assignment operator will move
9811 // from a virtual base more than once.
9812 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009813
Sebastian Redl22653ba2011-08-30 19:58:05 +00009814 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009815 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009816
9817 // The parameter for the "other" object, which we are move from.
9818 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9819 QualType OtherRefType = Other->getType()->
9820 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009821 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009822 "Bad argument type of defaulted move assignment");
9823
9824 // Our location for everything implicitly-generated.
9825 SourceLocation Loc = MoveAssignOperator->getLocation();
9826
Pavel Labath58934982013-08-30 08:52:28 +00009827 // Builds a reference to the "other" object.
9828 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009829 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009830 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009831
Pavel Labath58934982013-08-30 08:52:28 +00009832 // Builds the "this" pointer.
9833 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009834
Sebastian Redl22653ba2011-08-30 19:58:05 +00009835 // Assign base classes.
9836 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009837 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009838 // C++11 [class.copy]p28:
9839 // It is unspecified whether subobjects representing virtual base classes
9840 // are assigned more than once by the implicitly-defined copy assignment
9841 // operator.
9842 // FIXME: Do not assign to a vbase that will be assigned by some other base
9843 // class. For a move-assignment, this can result in the vbase being moved
9844 // multiple times.
9845
Sebastian Redl22653ba2011-08-30 19:58:05 +00009846 // Form the assignment:
9847 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009848 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009849 if (!BaseType->isRecordType()) {
9850 Invalid = true;
9851 continue;
9852 }
9853
9854 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009855 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009856
9857 // Construct the "from" expression, which is an implicit cast to the
9858 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009859 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009860
9861 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009862 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009863
9864 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009865 CastBuilder To(DerefThis,
9866 Context.getCVRQualifiedType(
9867 BaseType, MoveAssignOperator->getTypeQualifiers()),
9868 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009869
9870 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009871 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009872 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009873 /*CopyingBaseSubobject=*/true,
9874 /*Copying=*/false);
9875 if (Move.isInvalid()) {
9876 Diag(CurrentLocation, diag::note_member_synthesized_at)
9877 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9878 MoveAssignOperator->setInvalidDecl();
9879 return;
9880 }
9881
9882 // Success! Record the move.
9883 Statements.push_back(Move.takeAs<Expr>());
9884 }
9885
Sebastian Redl22653ba2011-08-30 19:58:05 +00009886 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009887 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009888 if (Field->isUnnamedBitfield())
9889 continue;
9890
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009891 if (Field->isInvalidDecl()) {
9892 Invalid = true;
9893 continue;
9894 }
9895
Sebastian Redl22653ba2011-08-30 19:58:05 +00009896 // Check for members of reference type; we can't move those.
9897 if (Field->getType()->isReferenceType()) {
9898 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9899 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9900 Diag(Field->getLocation(), diag::note_declared_at);
9901 Diag(CurrentLocation, diag::note_member_synthesized_at)
9902 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9903 Invalid = true;
9904 continue;
9905 }
9906
9907 // Check for members of const-qualified, non-class type.
9908 QualType BaseType = Context.getBaseElementType(Field->getType());
9909 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9910 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9911 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9912 Diag(Field->getLocation(), diag::note_declared_at);
9913 Diag(CurrentLocation, diag::note_member_synthesized_at)
9914 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9915 Invalid = true;
9916 continue;
9917 }
9918
9919 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009920 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9921 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009922
9923 QualType FieldType = Field->getType().getNonReferenceType();
9924 if (FieldType->isIncompleteArrayType()) {
9925 assert(ClassDecl->hasFlexibleArrayMember() &&
9926 "Incomplete array type is not valid");
9927 continue;
9928 }
9929
9930 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009931 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9932 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009933 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009934 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009935 MemberBuilder From(MoveOther, OtherRefType,
9936 /*IsArrow=*/false, MemberLookup);
9937 MemberBuilder To(This, getCurrentThisType(),
9938 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009939
Pavel Labath58934982013-08-30 08:52:28 +00009940 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +00009941 "Member reference with rvalue base must be rvalue except for reference "
9942 "members, which aren't allowed for move assignment.");
9943
Sebastian Redl22653ba2011-08-30 19:58:05 +00009944 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009945 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009946 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009947 /*CopyingBaseSubobject=*/false,
9948 /*Copying=*/false);
9949 if (Move.isInvalid()) {
9950 Diag(CurrentLocation, diag::note_member_synthesized_at)
9951 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9952 MoveAssignOperator->setInvalidDecl();
9953 return;
9954 }
Richard Smith11d19592012-11-12 23:33:00 +00009955
Sebastian Redl22653ba2011-08-30 19:58:05 +00009956 // Success! Record the copy.
9957 Statements.push_back(Move.takeAs<Stmt>());
9958 }
9959
9960 if (!Invalid) {
9961 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009962 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00009963
9964 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9965 if (Return.isInvalid())
9966 Invalid = true;
9967 else {
9968 Statements.push_back(Return.takeAs<Stmt>());
9969
9970 if (Trap.hasErrorOccurred()) {
9971 Diag(CurrentLocation, diag::note_member_synthesized_at)
9972 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9973 Invalid = true;
9974 }
9975 }
9976 }
9977
9978 if (Invalid) {
9979 MoveAssignOperator->setInvalidDecl();
9980 return;
9981 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009982
9983 StmtResult Body;
9984 {
9985 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009986 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009987 /*isStmtExpr=*/false);
9988 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9989 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00009990 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9991
9992 if (ASTMutationListener *L = getASTMutationListener()) {
9993 L->CompletedImplicitDefinition(MoveAssignOperator);
9994 }
9995}
9996
Richard Smithd3b5c9082012-07-27 04:22:15 +00009997Sema::ImplicitExceptionSpecification
9998Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9999 CXXRecordDecl *ClassDecl = MD->getParent();
10000
10001 ImplicitExceptionSpecification ExceptSpec(*this);
10002 if (ClassDecl->isInvalidDecl())
10003 return ExceptSpec;
10004
10005 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010006 assert(T->getNumParams() >= 1 && "not a copy ctor");
10007 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010008
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010009 // C++ [except.spec]p14:
10010 // An implicitly declared special member function (Clause 12) shall have an
10011 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010012 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010013 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010014 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010015 continue;
10016
Douglas Gregora6d69502010-07-02 23:41:54 +000010017 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010018 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010019 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010020 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010021 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010022 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010023 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010024 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010025 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010026 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010027 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010028 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010029 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010030 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010031 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010032 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10033 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010034 LookupCopyingConstructor(FieldClassDecl,
10035 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010036 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010037 }
10038 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010039
Richard Smithd3b5c9082012-07-27 04:22:15 +000010040 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010041}
10042
10043CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10044 CXXRecordDecl *ClassDecl) {
10045 // C++ [class.copy]p4:
10046 // If the class definition does not explicitly declare a copy
10047 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010048 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010049
Richard Smith8bf22e52012-11-29 01:34:07 +000010050 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10051 if (DSM.isAlreadyBeingDeclared())
10052 return 0;
10053
Alexis Hunt913820d2011-05-13 06:10:58 +000010054 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10055 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010056 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010057 if (Const)
10058 ArgType = ArgType.withConst();
10059 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010060
Richard Smithb5800092012-06-10 05:43:50 +000010061 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10062 CXXCopyConstructor,
10063 Const);
10064
Douglas Gregor54be3392010-07-01 17:57:27 +000010065 DeclarationName Name
10066 = Context.DeclarationNames.getCXXConstructorName(
10067 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010068 SourceLocation ClassLoc = ClassDecl->getLocation();
10069 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010070
10071 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010072 // member of its class.
10073 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010074 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010075 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010076 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010077 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010078 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010079
Richard Smithd3b5c9082012-07-27 04:22:15 +000010080 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010081 FunctionProtoType::ExtProtoInfo EPI =
10082 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010083 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010084 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010085
Douglas Gregor54be3392010-07-01 17:57:27 +000010086 // Add the parameter to the constructor.
10087 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010088 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +000010089 /*IdentifierInfo=*/0,
10090 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +000010091 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010092 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010093
Richard Smith6b02d462012-12-08 08:32:28 +000010094 CopyConstructor->setTrivial(
10095 ClassDecl->needsOverloadResolutionForCopyConstructor()
10096 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10097 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010098
Richard Smith852265f2012-03-30 20:53:28 +000010099 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010100 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010101
Richard Smith6b02d462012-12-08 08:32:28 +000010102 // Note that we have declared this constructor.
10103 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10104
10105 if (Scope *S = getScopeForContext(ClassDecl))
10106 PushOnScopeChains(CopyConstructor, S, false);
10107 ClassDecl->addDecl(CopyConstructor);
10108
Douglas Gregor54be3392010-07-01 17:57:27 +000010109 return CopyConstructor;
10110}
10111
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010112void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010113 CXXConstructorDecl *CopyConstructor) {
10114 assert((CopyConstructor->isDefaulted() &&
10115 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010116 !CopyConstructor->doesThisDeclarationHaveABody() &&
10117 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010118 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010119
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010120 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010121 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010122
Richard Smithd577fbb2013-06-13 03:23:42 +000010123 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010124 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010125 // deprecated if the class has a user-declared copy assignment operator
10126 // or a user-declared destructor.
10127 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10128 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10129
Eli Friedmaneaf34142012-10-18 20:14:08 +000010130 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010131 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010132
David Blaikie3fc2f912013-01-17 05:26:25 +000010133 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010134 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010135 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010136 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010137 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010138 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010139 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010140 CopyConstructor->setBody(ActOnCompoundStmt(
10141 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10142 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010143 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010144
Eli Friedman276dd182013-09-05 00:02:25 +000010145 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010146 if (ASTMutationListener *L = getASTMutationListener()) {
10147 L->CompletedImplicitDefinition(CopyConstructor);
10148 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010149}
10150
Sebastian Redl22653ba2011-08-30 19:58:05 +000010151Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010152Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10153 CXXRecordDecl *ClassDecl = MD->getParent();
10154
Sebastian Redl22653ba2011-08-30 19:58:05 +000010155 // C++ [except.spec]p14:
10156 // An implicitly declared special member function (Clause 12) shall have an
10157 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010158 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010159 if (ClassDecl->isInvalidDecl())
10160 return ExceptSpec;
10161
10162 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010163 for (const auto &B : ClassDecl->bases()) {
10164 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010165 continue;
10166
Aaron Ballman574705e2014-03-13 15:41:46 +000010167 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010168 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010169 CXXConstructorDecl *Constructor =
10170 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010171 // If this is a deleted function, add it anyway. This might be conformant
10172 // with the standard. This might not. I'm not sure. It might not matter.
10173 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010174 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010175 }
10176 }
10177
10178 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010179 for (const auto &B : ClassDecl->vbases()) {
10180 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010181 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010182 CXXConstructorDecl *Constructor =
10183 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010184 // If this is a deleted function, add it anyway. This might be conformant
10185 // with the standard. This might not. I'm not sure. It might not matter.
10186 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010187 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010188 }
10189 }
10190
10191 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010192 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010193 QualType FieldType = Context.getBaseElementType(F->getType());
10194 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10195 CXXConstructorDecl *Constructor =
10196 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010197 // If this is a deleted function, add it anyway. This might be conformant
10198 // with the standard. This might not. I'm not sure. It might not matter.
10199 // In particular, the problem is that this function never gets called. It
10200 // might just be ill-formed because this function attempts to refer to
10201 // a deleted function here.
10202 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010203 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010204 }
10205 }
10206
10207 return ExceptSpec;
10208}
10209
10210CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10211 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010212 assert(ClassDecl->needsImplicitMoveConstructor());
10213
Richard Smith8bf22e52012-11-29 01:34:07 +000010214 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10215 if (DSM.isAlreadyBeingDeclared())
10216 return 0;
10217
Sebastian Redl22653ba2011-08-30 19:58:05 +000010218 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10219 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010220
Richard Smithb5800092012-06-10 05:43:50 +000010221 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10222 CXXMoveConstructor,
10223 false);
10224
Sebastian Redl22653ba2011-08-30 19:58:05 +000010225 DeclarationName Name
10226 = Context.DeclarationNames.getCXXConstructorName(
10227 Context.getCanonicalType(ClassType));
10228 SourceLocation ClassLoc = ClassDecl->getLocation();
10229 DeclarationNameInfo NameInfo(Name, ClassLoc);
10230
Richard Smith99005e62013-05-07 03:19:20 +000010231 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010232 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010233 // member of its class.
10234 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010235 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010236 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010237 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010238 MoveConstructor->setAccess(AS_public);
10239 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010240
Richard Smithd3b5c9082012-07-27 04:22:15 +000010241 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010242 FunctionProtoType::ExtProtoInfo EPI =
10243 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010244 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010245 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010246
Sebastian Redl22653ba2011-08-30 19:58:05 +000010247 // Add the parameter to the constructor.
10248 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10249 ClassLoc, ClassLoc,
10250 /*IdentifierInfo=*/0,
10251 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010252 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010253 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010254
Richard Smith6b02d462012-12-08 08:32:28 +000010255 MoveConstructor->setTrivial(
10256 ClassDecl->needsOverloadResolutionForMoveConstructor()
10257 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10258 : ClassDecl->hasTrivialMoveConstructor());
10259
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010260 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010261 ClassDecl->setImplicitMoveConstructorIsDeleted();
10262 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010263 }
10264
10265 // Note that we have declared this constructor.
10266 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10267
10268 if (Scope *S = getScopeForContext(ClassDecl))
10269 PushOnScopeChains(MoveConstructor, S, false);
10270 ClassDecl->addDecl(MoveConstructor);
10271
10272 return MoveConstructor;
10273}
10274
10275void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10276 CXXConstructorDecl *MoveConstructor) {
10277 assert((MoveConstructor->isDefaulted() &&
10278 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010279 !MoveConstructor->doesThisDeclarationHaveABody() &&
10280 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010281 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10282
10283 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10284 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10285
Eli Friedmaneaf34142012-10-18 20:14:08 +000010286 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010287 DiagnosticErrorTrap Trap(Diags);
10288
David Blaikie3fc2f912013-01-17 05:26:25 +000010289 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010290 Trap.hasErrorOccurred()) {
10291 Diag(CurrentLocation, diag::note_member_synthesized_at)
10292 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10293 MoveConstructor->setInvalidDecl();
10294 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010295 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010296 MoveConstructor->setBody(ActOnCompoundStmt(
10297 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10298 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010299 }
10300
Eli Friedman276dd182013-09-05 00:02:25 +000010301 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010302
10303 if (ASTMutationListener *L = getASTMutationListener()) {
10304 L->CompletedImplicitDefinition(MoveConstructor);
10305 }
10306}
10307
Douglas Gregor74f7d502012-02-15 19:33:52 +000010308bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010309 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010310}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010311
10312void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010313 SourceLocation CurrentLocation,
10314 CXXConversionDecl *Conv) {
10315 CXXRecordDecl *Lambda = Conv->getParent();
10316 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10317 // If we are defining a specialization of a conversion to function-ptr
10318 // cache the deduced template arguments for this specialization
10319 // so that we can use them to retrieve the corresponding call-operator
10320 // and static-invoker.
10321 const TemplateArgumentList *DeducedTemplateArgs = 0;
10322
Douglas Gregor355efbb2012-02-17 03:02:34 +000010323
Faisal Vali571df122013-09-29 08:45:24 +000010324 // Retrieve the corresponding call-operator specialization.
10325 if (Lambda->isGenericLambda()) {
10326 assert(Conv->isFunctionTemplateSpecialization());
10327 FunctionTemplateDecl *CallOpTemplate =
10328 CallOp->getDescribedFunctionTemplate();
10329 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10330 void *InsertPos = 0;
10331 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10332 DeducedTemplateArgs->data(),
10333 DeducedTemplateArgs->size(),
10334 InsertPos);
10335 assert(CallOpSpec &&
10336 "Conversion operator must have a corresponding call operator");
10337 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10338 }
10339 // Mark the call operator referenced (and add to pending instantiations
10340 // if necessary).
10341 // For both the conversion and static-invoker template specializations
10342 // we construct their body's in this function, so no need to add them
10343 // to the PendingInstantiations.
10344 MarkFunctionReferenced(CurrentLocation, CallOp);
10345
Eli Friedmaneaf34142012-10-18 20:14:08 +000010346 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010347 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010348
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010349 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010350 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10351 // ... and get the corresponding specialization for a generic lambda.
10352 if (Lambda->isGenericLambda()) {
10353 assert(DeducedTemplateArgs &&
10354 "Must have deduced template arguments from Conversion Operator");
10355 FunctionTemplateDecl *InvokeTemplate =
10356 Invoker->getDescribedFunctionTemplate();
10357 void *InsertPos = 0;
10358 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10359 DeducedTemplateArgs->data(),
10360 DeducedTemplateArgs->size(),
10361 InsertPos);
10362 assert(InvokeSpec &&
10363 "Must have a corresponding static invoker specialization");
10364 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10365 }
10366 // Construct the body of the conversion function { return __invoke; }.
10367 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10368 VK_LValue, Conv->getLocation()).take();
10369 assert(FunctionRef && "Can't refer to __invoke function?");
10370 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10371 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10372 Conv->getLocation(),
10373 Conv->getLocation()));
10374
10375 Conv->markUsed(Context);
10376 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010377
Faisal Vali571df122013-09-29 08:45:24 +000010378 // Fill in the __invoke function with a dummy implementation. IR generation
10379 // will fill in the actual details.
10380 Invoker->markUsed(Context);
10381 Invoker->setReferenced();
10382 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10383
Douglas Gregord3b672c2012-02-16 01:06:16 +000010384 if (ASTMutationListener *L = getASTMutationListener()) {
10385 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010386 L->CompletedImplicitDefinition(Invoker);
10387 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010388}
10389
Faisal Vali571df122013-09-29 08:45:24 +000010390
10391
Douglas Gregord3b672c2012-02-16 01:06:16 +000010392void Sema::DefineImplicitLambdaToBlockPointerConversion(
10393 SourceLocation CurrentLocation,
10394 CXXConversionDecl *Conv)
10395{
Faisal Vali850da1a2013-09-29 17:08:32 +000010396 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010397
Eli Friedman276dd182013-09-05 00:02:25 +000010398 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010399
Eli Friedmaneaf34142012-10-18 20:14:08 +000010400 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010401 DiagnosticErrorTrap Trap(Diags);
10402
Douglas Gregored90df32012-02-22 05:02:47 +000010403 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010404 Expr *This = ActOnCXXThis(CurrentLocation).take();
10405 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010406
Eli Friedman98b01ed2012-03-01 04:01:32 +000010407 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10408 Conv->getLocation(),
10409 Conv, DerefThis);
10410
10411 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10412 // behavior. Note that only the general conversion function does this
10413 // (since it's unusable otherwise); in the case where we inline the
10414 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010415 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010416 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10417 CK_CopyAndAutoreleaseBlockObject,
10418 BuildBlock.get(), 0, VK_RValue);
10419
10420 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010421 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010422 Conv->setInvalidDecl();
10423 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010424 }
Douglas Gregored90df32012-02-22 05:02:47 +000010425
Douglas Gregored90df32012-02-22 05:02:47 +000010426 // Create the return statement that returns the block from the conversion
10427 // function.
Eli Friedman98b01ed2012-03-01 04:01:32 +000010428 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010429 if (Return.isInvalid()) {
10430 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10431 Conv->setInvalidDecl();
10432 return;
10433 }
10434
10435 // Set the body of the conversion function.
10436 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010437 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010438 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010439 Conv->getLocation()));
10440
Douglas Gregored90df32012-02-22 05:02:47 +000010441 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010442 if (ASTMutationListener *L = getASTMutationListener()) {
10443 L->CompletedImplicitDefinition(Conv);
10444 }
10445}
10446
Douglas Gregord2f70072012-03-10 06:53:13 +000010447/// \brief Determine whether the given list arguments contains exactly one
10448/// "real" (non-default) argument.
10449static bool hasOneRealArgument(MultiExprArg Args) {
10450 switch (Args.size()) {
10451 case 0:
10452 return false;
10453
10454 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010455 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010456 return false;
10457
10458 // fall through
10459 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010460 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010461 }
10462
10463 return false;
10464}
10465
John McCalldadc5752010-08-24 06:29:42 +000010466ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010467Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010468 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010469 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010470 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010471 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010472 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010473 unsigned ConstructKind,
10474 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010475 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010476
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010477 // C++0x [class.copy]p34:
10478 // When certain criteria are met, an implementation is allowed to
10479 // omit the copy/move construction of a class object, even if the
10480 // copy/move constructor and/or destructor for the object have
10481 // side effects. [...]
10482 // - when a temporary class object that has not been bound to a
10483 // reference (12.2) would be copied/moved to a class object
10484 // with the same cv-unqualified type, the copy/move operation
10485 // can be omitted by constructing the temporary object
10486 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010487 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010488 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010489 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010490 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010491 }
Mike Stump11289f42009-09-09 15:08:12 +000010492
10493 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010494 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010495 IsListInitialization, RequiresZeroInit,
10496 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010497}
10498
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010499/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10500/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010501ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010502Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10503 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010504 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010505 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010506 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010507 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010508 unsigned ConstructKind,
10509 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010510 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010511 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010512 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010513 HadMultipleCandidates,
10514 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010515 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10516 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010517}
10518
John McCall03c48482010-02-02 09:10:11 +000010519void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010520 if (VD->isInvalidDecl()) return;
10521
John McCall03c48482010-02-02 09:10:11 +000010522 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010523 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010524 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010525 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010526
Chandler Carruth86d17d32011-03-27 21:26:48 +000010527 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010528 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010529 CheckDestructorAccess(VD->getLocation(), Destructor,
10530 PDiag(diag::err_access_dtor_var)
10531 << VD->getDeclName()
10532 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010533 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010534
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010535 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010536 if (!VD->hasGlobalStorage()) return;
10537
10538 // Emit warning for non-trivial dtor in global scope (a real global,
10539 // class-static, function-static).
10540 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10541
10542 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010543 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000010544 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010545}
10546
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010547/// \brief Given a constructor and the set of arguments provided for the
10548/// constructor, convert the arguments and add any required default arguments
10549/// to form a proper call to this constructor.
10550///
10551/// \returns true if an error occurred, false otherwise.
10552bool
10553Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10554 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010555 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010556 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010557 bool AllowExplicit,
10558 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010559 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10560 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010561 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010562
10563 const FunctionProtoType *Proto
10564 = Constructor->getType()->getAs<FunctionProtoType>();
10565 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010566 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010567
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010568 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010569 if (NumArgs < NumParams)
10570 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010571 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010572 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010573
10574 VariadicCallType CallType =
10575 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010576 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010577 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010578 Proto, 0,
10579 llvm::makeArrayRef(Args, NumArgs),
10580 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010581 CallType, AllowExplicit,
10582 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010583 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010584
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010585 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010586
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010587 CheckConstructorCall(Constructor,
10588 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10589 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010590 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010591
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010592 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010593}
10594
Anders Carlssone363c8e2009-12-12 00:32:00 +000010595static inline bool
10596CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10597 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010598 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010599 if (isa<NamespaceDecl>(DC)) {
10600 return SemaRef.Diag(FnDecl->getLocation(),
10601 diag::err_operator_new_delete_declared_in_namespace)
10602 << FnDecl->getDeclName();
10603 }
10604
10605 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010606 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010607 return SemaRef.Diag(FnDecl->getLocation(),
10608 diag::err_operator_new_delete_declared_static)
10609 << FnDecl->getDeclName();
10610 }
10611
Anders Carlsson60659a82009-12-12 02:43:16 +000010612 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010613}
10614
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010615static inline bool
10616CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10617 CanQualType ExpectedResultType,
10618 CanQualType ExpectedFirstParamType,
10619 unsigned DependentParamTypeDiag,
10620 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010621 QualType ResultType =
10622 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010623
10624 // Check that the result type is not dependent.
10625 if (ResultType->isDependentType())
10626 return SemaRef.Diag(FnDecl->getLocation(),
10627 diag::err_operator_new_delete_dependent_result_type)
10628 << FnDecl->getDeclName() << ExpectedResultType;
10629
10630 // Check that the result type is what we expect.
10631 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10632 return SemaRef.Diag(FnDecl->getLocation(),
10633 diag::err_operator_new_delete_invalid_result_type)
10634 << FnDecl->getDeclName() << ExpectedResultType;
10635
10636 // A function template must have at least 2 parameters.
10637 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10638 return SemaRef.Diag(FnDecl->getLocation(),
10639 diag::err_operator_new_delete_template_too_few_parameters)
10640 << FnDecl->getDeclName();
10641
10642 // The function decl must have at least 1 parameter.
10643 if (FnDecl->getNumParams() == 0)
10644 return SemaRef.Diag(FnDecl->getLocation(),
10645 diag::err_operator_new_delete_too_few_parameters)
10646 << FnDecl->getDeclName();
10647
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010648 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010649 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10650 if (FirstParamType->isDependentType())
10651 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10652 << FnDecl->getDeclName() << ExpectedFirstParamType;
10653
10654 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010655 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010656 ExpectedFirstParamType)
10657 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10658 << FnDecl->getDeclName() << ExpectedFirstParamType;
10659
10660 return false;
10661}
10662
Anders Carlsson12308f42009-12-11 23:23:22 +000010663static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010664CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010665 // C++ [basic.stc.dynamic.allocation]p1:
10666 // A program is ill-formed if an allocation function is declared in a
10667 // namespace scope other than global scope or declared static in global
10668 // scope.
10669 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10670 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010671
10672 CanQualType SizeTy =
10673 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10674
10675 // C++ [basic.stc.dynamic.allocation]p1:
10676 // The return type shall be void*. The first parameter shall have type
10677 // std::size_t.
10678 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10679 SizeTy,
10680 diag::err_operator_new_dependent_param_type,
10681 diag::err_operator_new_param_type))
10682 return true;
10683
10684 // C++ [basic.stc.dynamic.allocation]p1:
10685 // The first parameter shall not have an associated default argument.
10686 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010687 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010688 diag::err_operator_new_default_arg)
10689 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10690
10691 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010692}
10693
10694static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010695CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010696 // C++ [basic.stc.dynamic.deallocation]p1:
10697 // A program is ill-formed if deallocation functions are declared in a
10698 // namespace scope other than global scope or declared static in global
10699 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010700 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10701 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010702
10703 // C++ [basic.stc.dynamic.deallocation]p2:
10704 // Each deallocation function shall return void and its first parameter
10705 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010706 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10707 SemaRef.Context.VoidPtrTy,
10708 diag::err_operator_delete_dependent_param_type,
10709 diag::err_operator_delete_param_type))
10710 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010711
Anders Carlsson12308f42009-12-11 23:23:22 +000010712 return false;
10713}
10714
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010715/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10716/// of this overloaded operator is well-formed. If so, returns false;
10717/// otherwise, emits appropriate diagnostics and returns true.
10718bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010719 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010720 "Expected an overloaded operator declaration");
10721
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010722 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10723
Mike Stump11289f42009-09-09 15:08:12 +000010724 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010725 // The allocation and deallocation functions, operator new,
10726 // operator new[], operator delete and operator delete[], are
10727 // described completely in 3.7.3. The attributes and restrictions
10728 // found in the rest of this subclause do not apply to them unless
10729 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010730 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010731 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010732
Anders Carlsson22f443f2009-12-12 00:26:23 +000010733 if (Op == OO_New || Op == OO_Array_New)
10734 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010735
10736 // C++ [over.oper]p6:
10737 // An operator function shall either be a non-static member
10738 // function or be a non-member function and have at least one
10739 // parameter whose type is a class, a reference to a class, an
10740 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010741 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10742 if (MethodDecl->isStatic())
10743 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010744 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010745 } else {
10746 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010747 for (auto Param : FnDecl->params()) {
10748 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010749 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10750 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010751 ClassOrEnumParam = true;
10752 break;
10753 }
10754 }
10755
Douglas Gregord69246b2008-11-17 16:14:12 +000010756 if (!ClassOrEnumParam)
10757 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010758 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010759 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010760 }
10761
10762 // C++ [over.oper]p8:
10763 // An operator function cannot have default arguments (8.3.6),
10764 // except where explicitly stated below.
10765 //
Mike Stump11289f42009-09-09 15:08:12 +000010766 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010767 // (C++ [over.call]p1).
10768 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010769 for (auto Param : FnDecl->params()) {
10770 if (Param->hasDefaultArg())
10771 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010772 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010773 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010774 }
10775 }
10776
Douglas Gregor6cf08062008-11-10 13:38:07 +000010777 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10778 { false, false, false }
10779#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10780 , { Unary, Binary, MemberOnly }
10781#include "clang/Basic/OperatorKinds.def"
10782 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010783
Douglas Gregor6cf08062008-11-10 13:38:07 +000010784 bool CanBeUnaryOperator = OperatorUses[Op][0];
10785 bool CanBeBinaryOperator = OperatorUses[Op][1];
10786 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010787
10788 // C++ [over.oper]p8:
10789 // [...] Operator functions cannot have more or fewer parameters
10790 // than the number required for the corresponding operator, as
10791 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010792 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010793 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010794 if (Op != OO_Call &&
10795 ((NumParams == 1 && !CanBeUnaryOperator) ||
10796 (NumParams == 2 && !CanBeBinaryOperator) ||
10797 (NumParams < 1) || (NumParams > 2))) {
10798 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010799 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010800 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010801 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010802 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010803 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010804 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010805 assert(CanBeBinaryOperator &&
10806 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010807 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010808 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010809
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010810 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010811 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010812 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010813
Douglas Gregord69246b2008-11-17 16:14:12 +000010814 // Overloaded operators other than operator() cannot be variadic.
10815 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010816 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010817 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010818 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010819 }
10820
10821 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010822 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10823 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010824 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010825 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010826 }
10827
10828 // C++ [over.inc]p1:
10829 // The user-defined function called operator++ implements the
10830 // prefix and postfix ++ operator. If this function is a member
10831 // function with no parameters, or a non-member function with one
10832 // parameter of class or enumeration type, it defines the prefix
10833 // increment operator ++ for objects of that type. If the function
10834 // is a member function with one parameter (which shall be of type
10835 // int) or a non-member function with two parameters (the second
10836 // of which shall be of type int), it defines the postfix
10837 // increment operator ++ for objects of that type.
10838 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10839 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000010840 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010841
Richard Smith538b52a2014-01-30 22:24:05 +000010842 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10843 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000010844 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010845 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010846 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010847 }
10848
Douglas Gregord69246b2008-11-17 16:14:12 +000010849 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010850}
Chris Lattner3b024a32008-12-17 07:09:26 +000010851
Alexis Huntc88db062010-01-13 09:01:02 +000010852/// CheckLiteralOperatorDeclaration - Check whether the declaration
10853/// of this literal operator function is well-formed. If so, returns
10854/// false; otherwise, emits appropriate diagnostics and returns true.
10855bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010856 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010857 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10858 << FnDecl->getDeclName();
10859 return true;
10860 }
10861
Richard Smith72eebee2012-03-04 09:41:16 +000010862 if (FnDecl->isExternC()) {
10863 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10864 return true;
10865 }
10866
Alexis Huntc88db062010-01-13 09:01:02 +000010867 bool Valid = false;
10868
Richard Smithbcc22fc2012-03-09 08:00:36 +000010869 // This might be the definition of a literal operator template.
10870 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10871 // This might be a specialization of a literal operator template.
10872 if (!TpDecl)
10873 TpDecl = FnDecl->getPrimaryTemplate();
10874
Richard Smithb8b41d32013-10-07 19:57:58 +000010875 // template <char...> type operator "" name() and
10876 // template <class T, T...> type operator "" name() are the only valid
10877 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010878 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010879 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000010880 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000010881 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10882 if (Params->size() == 1) {
10883 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010884 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010885
Alexis Hunt7dd26172010-04-07 23:11:06 +000010886 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010887 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10888 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10889 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000010890 } else if (Params->size() == 2) {
10891 TemplateTypeParmDecl *PmType =
10892 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10893 NonTypeTemplateParmDecl *PmArgs =
10894 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10895
10896 // The second template parameter must be a parameter pack with the
10897 // first template parameter as its type.
10898 if (PmType && PmArgs &&
10899 !PmType->isTemplateParameterPack() &&
10900 PmArgs->isTemplateParameterPack()) {
10901 const TemplateTypeParmType *TArgs =
10902 PmArgs->getType()->getAs<TemplateTypeParmType>();
10903 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10904 TArgs->getIndex() == PmType->getIndex()) {
10905 Valid = true;
10906 if (ActiveTemplateInstantiations.empty())
10907 Diag(FnDecl->getLocation(),
10908 diag::ext_string_literal_operator_template);
10909 }
10910 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000010911 }
10912 }
Richard Smith72eebee2012-03-04 09:41:16 +000010913 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010914 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010915 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10916
Richard Smith72eebee2012-03-04 09:41:16 +000010917 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010918
Alexis Hunt079a6f72010-04-07 22:57:35 +000010919 // unsigned long long int, long double, and any character type are allowed
10920 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010921 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10922 Context.hasSameType(T, Context.LongDoubleTy) ||
10923 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010924 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010925 Context.hasSameType(T, Context.Char16Ty) ||
10926 Context.hasSameType(T, Context.Char32Ty)) {
10927 if (++Param == FnDecl->param_end())
10928 Valid = true;
10929 goto FinishedParams;
10930 }
10931
Alexis Hunt079a6f72010-04-07 22:57:35 +000010932 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000010933 const PointerType *PT = T->getAs<PointerType>();
10934 if (!PT)
10935 goto FinishedParams;
10936 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000010937 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000010938 goto FinishedParams;
10939 T = T.getUnqualifiedType();
10940
10941 // Move on to the second parameter;
10942 ++Param;
10943
10944 // If there is no second parameter, the first must be a const char *
10945 if (Param == FnDecl->param_end()) {
10946 if (Context.hasSameType(T, Context.CharTy))
10947 Valid = true;
10948 goto FinishedParams;
10949 }
10950
10951 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10952 // are allowed as the first parameter to a two-parameter function
10953 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010954 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010955 Context.hasSameType(T, Context.Char16Ty) ||
10956 Context.hasSameType(T, Context.Char32Ty)))
10957 goto FinishedParams;
10958
10959 // The second and final parameter must be an std::size_t
10960 T = (*Param)->getType().getUnqualifiedType();
10961 if (Context.hasSameType(T, Context.getSizeType()) &&
10962 ++Param == FnDecl->param_end())
10963 Valid = true;
10964 }
10965
10966 // FIXME: This diagnostic is absolutely terrible.
10967FinishedParams:
10968 if (!Valid) {
10969 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10970 << FnDecl->getDeclName();
10971 return true;
10972 }
10973
Richard Smith768cecc2012-03-09 08:16:22 +000010974 // A parameter-declaration-clause containing a default argument is not
10975 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010976 for (auto Param : FnDecl->params()) {
10977 if (Param->hasDefaultArg()) {
10978 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000010979 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010980 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000010981 break;
10982 }
10983 }
10984
Richard Smith0df56f42012-03-08 02:39:21 +000010985 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000010986 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10987 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000010988 // C++11 [usrlit.suffix]p1:
10989 // Literal suffix identifiers that do not start with an underscore
10990 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000010991 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10992 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000010993 }
Richard Smith0df56f42012-03-08 02:39:21 +000010994
Alexis Huntc88db062010-01-13 09:01:02 +000010995 return false;
10996}
10997
Douglas Gregor07665a62009-01-05 19:45:36 +000010998/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10999/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011000/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11001/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011002/// the '{' brace. Otherwise, this linkage specification does not
11003/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011004Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011005 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011006 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011007 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11008 if (!Lit->isAscii()) {
11009 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11010 << LangStr->getSourceRange();
11011 return 0;
11012 }
11013
11014 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011015 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011016 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011017 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011018 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011019 Language = LinkageSpecDecl::lang_cxx;
11020 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011021 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11022 << LangStr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011023 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000011024 }
Mike Stump11289f42009-09-09 15:08:12 +000011025
Chris Lattner438e5012008-12-17 07:13:27 +000011026 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011027
Richard Smith4ee696d2014-02-17 23:25:27 +000011028 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11029 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011030 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011031 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011032 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011033 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011034}
11035
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011036/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011037/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11038/// valid, it's the position of the closing '}' brace in a linkage
11039/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011040Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011041 Decl *LinkageSpec,
11042 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011043 if (RBraceLoc.isValid()) {
11044 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11045 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011046 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011047 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011048 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011049}
11050
Michael Han84324352013-02-22 17:15:32 +000011051Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11052 AttributeList *AttrList,
11053 SourceLocation SemiLoc) {
11054 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11055 // Attribute declarations appertain to empty declaration so we handle
11056 // them here.
11057 if (AttrList)
11058 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011059
Michael Han84324352013-02-22 17:15:32 +000011060 CurContext->addDecl(ED);
11061 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011062}
11063
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011064/// \brief Perform semantic analysis for the variable declaration that
11065/// occurs within a C++ catch clause, returning the newly-created
11066/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011067VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011068 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011069 SourceLocation StartLoc,
11070 SourceLocation Loc,
11071 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011072 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011073 QualType ExDeclType = TInfo->getType();
11074
Sebastian Redl54c04d42008-12-22 19:15:10 +000011075 // Arrays and functions decay.
11076 if (ExDeclType->isArrayType())
11077 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11078 else if (ExDeclType->isFunctionType())
11079 ExDeclType = Context.getPointerType(ExDeclType);
11080
11081 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11082 // The exception-declaration shall not denote a pointer or reference to an
11083 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011084 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011085 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011086 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011087 Invalid = true;
11088 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011089
Sebastian Redl54c04d42008-12-22 19:15:10 +000011090 QualType BaseType = ExDeclType;
11091 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011092 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011093 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011094 BaseType = Ptr->getPointeeType();
11095 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011096 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011097 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011098 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011099 BaseType = Ref->getPointeeType();
11100 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011101 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011102 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011103 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011104 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011105 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011106
Mike Stump11289f42009-09-09 15:08:12 +000011107 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011108 RequireNonAbstractType(Loc, ExDeclType,
11109 diag::err_abstract_type_in_decl,
11110 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011111 Invalid = true;
11112
John McCall2ca705e2010-07-24 00:37:23 +000011113 // Only the non-fragile NeXT runtime currently supports C++ catches
11114 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011115 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011116 QualType T = ExDeclType;
11117 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11118 T = RT->getPointeeType();
11119
11120 if (T->isObjCObjectType()) {
11121 Diag(Loc, diag::err_objc_object_catch);
11122 Invalid = true;
11123 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011124 // FIXME: should this be a test for macosx-fragile specifically?
11125 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011126 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011127 }
11128 }
11129
Abramo Bagnaradff19302011-03-08 08:55:46 +000011130 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011131 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011132 ExDecl->setExceptionVariable(true);
11133
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011134 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011135 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011136 Invalid = true;
11137
Douglas Gregor750734c2011-07-06 18:14:43 +000011138 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011139 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011140 // Insulate this from anything else we might currently be parsing.
11141 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11142
Douglas Gregor6de584c2010-03-05 23:38:39 +000011143 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011144 // The object declared in an exception-declaration or, if the
11145 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011146 // copy-initialized (8.5) from the exception object. [...]
11147 // The object is destroyed when the handler exits, after the destruction
11148 // of any automatic objects initialized within the handler.
11149 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011150 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011151 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011152 QualType initType = ExDeclType;
11153
11154 InitializedEntity entity =
11155 InitializedEntity::InitializeVariable(ExDecl);
11156 InitializationKind initKind =
11157 InitializationKind::CreateCopy(Loc, SourceLocation());
11158
11159 Expr *opaqueValue =
11160 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011161 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11162 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011163 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011164 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011165 else {
11166 // If the constructor used was non-trivial, set this as the
11167 // "initializer".
Nick Lewycky0f292892013-09-22 10:06:57 +000011168 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011169 if (!construct->getConstructor()->isTrivial()) {
11170 Expr *init = MaybeCreateExprWithCleanups(construct);
11171 ExDecl->setInit(init);
11172 }
11173
11174 // And make sure it's destructable.
11175 FinalizeVarWithDestructor(ExDecl, recordType);
11176 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011177 }
11178 }
11179
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011180 if (Invalid)
11181 ExDecl->setInvalidDecl();
11182
11183 return ExDecl;
11184}
11185
11186/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11187/// handler.
John McCall48871652010-08-21 09:40:31 +000011188Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011189 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011190 bool Invalid = D.isInvalidType();
11191
11192 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011193 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11194 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011195 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11196 D.getIdentifierLoc());
11197 Invalid = true;
11198 }
11199
Sebastian Redl54c04d42008-12-22 19:15:10 +000011200 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011201 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011202 LookupOrdinaryName,
11203 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011204 // The scope should be freshly made just for us. There is just no way
11205 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000011206 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000011207 if (PrevDecl->isTemplateParameter()) {
11208 // Maybe we will complain about the shadowed template parameter.
11209 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000011210 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011211 }
11212 }
11213
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011214 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011215 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11216 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011217 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011218 }
11219
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011220 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011221 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011222 D.getIdentifierLoc(),
11223 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011224 if (Invalid)
11225 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011226
Sebastian Redl54c04d42008-12-22 19:15:10 +000011227 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011228 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011229 PushOnScopeChains(ExDecl, S);
11230 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011231 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011232
Douglas Gregor758a8692009-06-17 21:51:59 +000011233 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011234 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011235}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011236
Abramo Bagnaraea947882011-03-08 16:41:52 +000011237Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011238 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011239 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011240 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011241 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011242
Richard Smithded9c2e2012-07-11 22:37:56 +000011243 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11244 return 0;
11245
11246 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11247 AssertMessage, RParenLoc, false);
11248}
11249
11250Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11251 Expr *AssertExpr,
11252 StringLiteral *AssertMessage,
11253 SourceLocation RParenLoc,
11254 bool Failed) {
11255 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11256 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011257 // In a static_assert-declaration, the constant-expression shall be a
11258 // constant expression that can be contextually converted to bool.
11259 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11260 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011261 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011262
Richard Smith902ca212011-12-14 23:32:26 +000011263 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011264 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011265 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011266 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011267 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011268
Richard Smithded9c2e2012-07-11 22:37:56 +000011269 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011270 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011271 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000011272 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011273 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011274 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011275 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011276 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011277 }
Mike Stump11289f42009-09-09 15:08:12 +000011278
Abramo Bagnaraea947882011-03-08 16:41:52 +000011279 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011280 AssertExpr, AssertMessage, RParenLoc,
11281 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011282
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011283 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011284 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011285}
Sebastian Redlf769df52009-03-24 22:27:57 +000011286
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011287/// \brief Perform semantic analysis of the given friend type declaration.
11288///
11289/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011290FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011291 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011292 TypeSourceInfo *TSInfo) {
11293 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11294
11295 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011296 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011297
Richard Smithc8239732011-10-18 21:39:00 +000011298 // C++03 [class.friend]p2:
11299 // An elaborated-type-specifier shall be used in a friend declaration
11300 // for a class.*
11301 //
11302 // * The class-key of the elaborated-type-specifier is required.
11303 if (!ActiveTemplateInstantiations.empty()) {
11304 // Do not complain about the form of friend template types during
11305 // template instantiation; we will already have complained when the
11306 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011307 } else {
11308 if (!T->isElaboratedTypeSpecifier()) {
11309 // If we evaluated the type to a record type, suggest putting
11310 // a tag in front.
11311 if (const RecordType *RT = T->getAs<RecordType>()) {
11312 RecordDecl *RD = RT->getDecl();
Richard Smithc8239732011-10-18 21:39:00 +000011313
Nick Lewycky36722d22013-02-06 05:59:33 +000011314 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smithc8239732011-10-18 21:39:00 +000011315
Nick Lewycky36722d22013-02-06 05:59:33 +000011316 Diag(TypeRange.getBegin(),
11317 getLangOpts().CPlusPlus11 ?
11318 diag::warn_cxx98_compat_unelaborated_friend_type :
11319 diag::ext_unelaborated_friend_type)
11320 << (unsigned) RD->getTagKind()
11321 << T
11322 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11323 InsertionText);
11324 } else {
11325 Diag(FriendLoc,
11326 getLangOpts().CPlusPlus11 ?
11327 diag::warn_cxx98_compat_nonclass_type_friend :
11328 diag::ext_nonclass_type_friend)
11329 << T
11330 << TypeRange;
11331 }
11332 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011333 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011334 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011335 diag::warn_cxx98_compat_enum_friend :
11336 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011337 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011338 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011339 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011340
Nick Lewycky36722d22013-02-06 05:59:33 +000011341 // C++11 [class.friend]p3:
11342 // A friend declaration that does not declare a function shall have one
11343 // of the following forms:
11344 // friend elaborated-type-specifier ;
11345 // friend simple-type-specifier ;
11346 // friend typename-specifier ;
11347 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11348 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11349 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011350
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011351 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011352 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011353 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000011354 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011355}
11356
John McCallace48cd2010-10-19 01:40:49 +000011357/// Handle a friend tag declaration where the scope specifier was
11358/// templated.
11359Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11360 unsigned TagSpec, SourceLocation TagLoc,
11361 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011362 IdentifierInfo *Name,
11363 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011364 AttributeList *Attr,
11365 MultiTemplateParamsArg TempParamLists) {
11366 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11367
11368 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011369 bool Invalid = false;
11370
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011371 if (TemplateParameterList *TemplateParams =
11372 MatchTemplateParametersToScopeSpecifier(
11373 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11374 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011375 if (TemplateParams->size() > 0) {
11376 // This is a declaration of a class template.
11377 if (Invalid)
11378 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011379
Eric Christopher6f228b52011-07-21 05:34:24 +000011380 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11381 SS, Name, NameLoc, Attr,
11382 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011383 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011384 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011385 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000011386 } else {
11387 // The "template<>" header is extraneous.
11388 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11389 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11390 isExplicitSpecialization = true;
11391 }
11392 }
11393
11394 if (Invalid) return 0;
11395
John McCallace48cd2010-10-19 01:40:49 +000011396 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011397 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011398 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011399 isAllExplicitSpecializations = false;
11400 break;
11401 }
11402 }
11403
11404 // FIXME: don't ignore attributes.
11405
11406 // If it's explicit specializations all the way down, just forget
11407 // about the template header and build an appropriate non-templated
11408 // friend. TODO: for source fidelity, remember the headers.
11409 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011410 if (SS.isEmpty()) {
11411 bool Owned = false;
11412 bool IsDependent = false;
11413 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011414 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011415 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011416 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011417 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011418 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011419 /*UnderlyingType=*/TypeResult(),
11420 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011421 }
Richard Smith649c7b062014-01-08 00:56:48 +000011422
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011423 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011424 ElaboratedTypeKeyword Keyword
11425 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011426 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011427 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011428 if (T.isNull())
11429 return 0;
11430
11431 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11432 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011433 DependentNameTypeLoc TL =
11434 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011435 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011436 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011437 TL.setNameLoc(NameLoc);
11438 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011439 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011440 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011441 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011442 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011443 }
11444
11445 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011446 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011447 Friend->setAccess(AS_public);
11448 CurContext->addDecl(Friend);
11449 return Friend;
11450 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011451
11452 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11453
11454
John McCallace48cd2010-10-19 01:40:49 +000011455
11456 // Handle the case of a templated-scope friend class. e.g.
11457 // template <class T> class A<T>::B;
11458 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011459 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11460 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011461 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11462 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11463 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011464 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011465 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011466 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011467 TL.setNameLoc(NameLoc);
11468
11469 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011470 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011471 Friend->setAccess(AS_public);
11472 Friend->setUnsupportedFriend(true);
11473 CurContext->addDecl(Friend);
11474 return Friend;
11475}
11476
11477
John McCall11083da2009-09-16 22:47:08 +000011478/// Handle a friend type declaration. This works in tandem with
11479/// ActOnTag.
11480///
11481/// Notes on friend class templates:
11482///
11483/// We generally treat friend class declarations as if they were
11484/// declaring a class. So, for example, the elaborated type specifier
11485/// in a friend declaration is required to obey the restrictions of a
11486/// class-head (i.e. no typedefs in the scope chain), template
11487/// parameters are required to match up with simple template-ids, &c.
11488/// However, unlike when declaring a template specialization, it's
11489/// okay to refer to a template specialization without an empty
11490/// template parameter declaration, e.g.
11491/// friend class A<T>::B<unsigned>;
11492/// We permit this as a special case; if there are any template
11493/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011494/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011495Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011496 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011497 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011498
11499 assert(DS.isFriendSpecified());
11500 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11501
John McCall11083da2009-09-16 22:47:08 +000011502 // Try to convert the decl specifier to a type. This works for
11503 // friend templates because ActOnTag never produces a ClassTemplateDecl
11504 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011505 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011506 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11507 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011508 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011509 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011510
Douglas Gregor6c110f32010-12-16 01:14:37 +000011511 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11512 return 0;
11513
John McCall11083da2009-09-16 22:47:08 +000011514 // This is definitely an error in C++98. It's probably meant to
11515 // be forbidden in C++0x, too, but the specification is just
11516 // poorly written.
11517 //
11518 // The problem is with declarations like the following:
11519 // template <T> friend A<T>::foo;
11520 // where deciding whether a class C is a friend or not now hinges
11521 // on whether there exists an instantiation of A that causes
11522 // 'foo' to equal C. There are restrictions on class-heads
11523 // (which we declare (by fiat) elaborated friend declarations to
11524 // be) that makes this tractable.
11525 //
11526 // FIXME: handle "template <> friend class A<T>;", which
11527 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011528 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011529 Diag(Loc, diag::err_tagless_friend_type_template)
11530 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011531 return 0;
John McCall11083da2009-09-16 22:47:08 +000011532 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011533
John McCallaa74a0c2009-08-28 07:59:38 +000011534 // C++98 [class.friend]p1: A friend of a class is a function
11535 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011536 // This is fixed in DR77, which just barely didn't make the C++03
11537 // deadline. It's also a very silly restriction that seriously
11538 // affects inner classes and which nobody else seems to implement;
11539 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011540 //
11541 // But note that we could warn about it: it's always useless to
11542 // friend one of your own members (it's not, however, worthless to
11543 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011544
John McCall11083da2009-09-16 22:47:08 +000011545 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011546 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011547 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011548 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011549 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011550 TSI,
John McCall11083da2009-09-16 22:47:08 +000011551 DS.getFriendSpecLoc());
11552 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011553 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011554
11555 if (!D)
John McCall48871652010-08-21 09:40:31 +000011556 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011557
John McCall11083da2009-09-16 22:47:08 +000011558 D->setAccess(AS_public);
11559 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011560
John McCall48871652010-08-21 09:40:31 +000011561 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011562}
11563
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011564NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11565 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011566 const DeclSpec &DS = D.getDeclSpec();
11567
11568 assert(DS.isFriendSpecified());
11569 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11570
11571 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011572 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011573
11574 // C++ [class.friend]p1
11575 // A friend of a class is a function or class....
11576 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011577 // It *doesn't* see through dependent types, which is correct
11578 // according to [temp.arg.type]p3:
11579 // If a declaration acquires a function type through a
11580 // type dependent on a template-parameter and this causes
11581 // a declaration that does not use the syntactic form of a
11582 // function declarator to have a function type, the program
11583 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011584 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011585 Diag(Loc, diag::err_unexpected_friend);
11586
11587 // It might be worthwhile to try to recover by creating an
11588 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011589 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011590 }
11591
11592 // C++ [namespace.memdef]p3
11593 // - If a friend declaration in a non-local class first declares a
11594 // class or function, the friend class or function is a member
11595 // of the innermost enclosing namespace.
11596 // - The name of the friend is not found by simple name lookup
11597 // until a matching declaration is provided in that namespace
11598 // scope (either before or after the class declaration granting
11599 // friendship).
11600 // - If a friend function is called, its name may be found by the
11601 // name lookup that considers functions from namespaces and
11602 // classes associated with the types of the function arguments.
11603 // - When looking for a prior declaration of a class or a function
11604 // declared as a friend, scopes outside the innermost enclosing
11605 // namespace scope are not considered.
11606
John McCallde3fd222010-10-12 23:13:28 +000011607 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011608 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11609 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011610 assert(Name);
11611
Douglas Gregor6c110f32010-12-16 01:14:37 +000011612 // Check for unexpanded parameter packs.
11613 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11614 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11615 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11616 return 0;
11617
John McCall07e91c02009-08-06 02:15:43 +000011618 // The context we found the declaration in, or in which we should
11619 // create the declaration.
11620 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011621 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011622 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011623 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011624
Richard Smith114394f2013-08-09 04:35:01 +000011625 // There are five cases here.
11626 // - There's no scope specifier and we're in a local class. Only look
11627 // for functions declared in the immediately-enclosing block scope.
11628 // We recover from invalid scope qualifiers as if they just weren't there.
11629 FunctionDecl *FunctionContainingLocalClass = 0;
11630 if ((SS.isInvalid() || !SS.isSet()) &&
11631 (FunctionContainingLocalClass =
11632 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11633 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011634 // If a friend declaration appears in a local class and the name
11635 // specified is an unqualified name, a prior declaration is
11636 // looked up without considering scopes that are outside the
11637 // innermost enclosing non-class scope. For a friend function
11638 // declaration, if there is no prior declaration, the program is
11639 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011640
11641 // Find the innermost enclosing non-class scope. This is the block
11642 // scope containing the local class definition (or for a nested class,
11643 // the outer local class).
11644 DCScope = S->getFnParent();
11645
11646 // Look up the function name in the scope.
11647 Previous.clear(LookupLocalFriendName);
11648 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11649
11650 if (!Previous.empty()) {
11651 // All possible previous declarations must have the same context:
11652 // either they were declared at block scope or they are members of
11653 // one of the enclosing local classes.
11654 DC = Previous.getRepresentativeDecl()->getDeclContext();
11655 } else {
11656 // This is ill-formed, but provide the context that we would have
11657 // declared the function in, if we were permitted to, for error recovery.
11658 DC = FunctionContainingLocalClass;
11659 }
Richard Smith541b38b2013-09-20 01:15:31 +000011660 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011661
11662 // C++ [class.friend]p6:
11663 // A function can be defined in a friend declaration of a class if and
11664 // only if the class is a non-local class (9.8), the function name is
11665 // unqualified, and the function has namespace scope.
11666 if (D.isFunctionDefinition()) {
11667 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11668 }
11669
11670 // - There's no scope specifier, in which case we just go to the
11671 // appropriate scope and look for a function or function template
11672 // there as appropriate.
11673 } else if (SS.isInvalid() || !SS.isSet()) {
11674 // C++11 [namespace.memdef]p3:
11675 // If the name in a friend declaration is neither qualified nor
11676 // a template-id and the declaration is a function or an
11677 // elaborated-type-specifier, the lookup to determine whether
11678 // the entity has been previously declared shall not consider
11679 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011680 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011681
John McCallf7cfb222010-10-13 05:45:15 +000011682 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011683 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011684
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011685 // Skip class contexts. If someone can cite chapter and verse
11686 // for this behavior, that would be nice --- it's what GCC and
11687 // EDG do, and it seems like a reasonable intent, but the spec
11688 // really only says that checks for unqualified existing
11689 // declarations should stop at the nearest enclosing namespace,
11690 // not that they should only consider the nearest enclosing
11691 // namespace.
11692 while (DC->isRecord())
11693 DC = DC->getParent();
11694
11695 DeclContext *LookupDC = DC;
11696 while (LookupDC->isTransparentContext())
11697 LookupDC = LookupDC->getParent();
11698
11699 while (true) {
11700 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011701
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011702 if (!Previous.empty()) {
11703 DC = LookupDC;
11704 break;
John McCallf4776592010-10-14 22:22:28 +000011705 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011706
11707 if (isTemplateId) {
11708 if (isa<TranslationUnitDecl>(LookupDC)) break;
11709 } else {
11710 if (LookupDC->isFileContext()) break;
11711 }
11712 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011713 }
11714
John McCallccbc0322010-10-13 06:22:15 +000011715 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011716
John McCallde3fd222010-10-12 23:13:28 +000011717 // - There's a non-dependent scope specifier, in which case we
11718 // compute it and do a previous lookup there for a function
11719 // or function template.
11720 } else if (!SS.getScopeRep()->isDependent()) {
11721 DC = computeDeclContext(SS);
11722 if (!DC) return 0;
11723
11724 if (RequireCompleteDeclContext(SS, DC)) return 0;
11725
11726 LookupQualifiedName(Previous, DC);
11727
11728 // Ignore things found implicitly in the wrong scope.
11729 // TODO: better diagnostics for this case. Suggesting the right
11730 // qualified scope would be nice...
11731 LookupResult::Filter F = Previous.makeFilter();
11732 while (F.hasNext()) {
11733 NamedDecl *D = F.next();
11734 if (!DC->InEnclosingNamespaceSetOf(
11735 D->getDeclContext()->getRedeclContext()))
11736 F.erase();
11737 }
11738 F.done();
11739
11740 if (Previous.empty()) {
11741 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011742 Diag(Loc, diag::err_qualified_friend_not_found)
11743 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011744 return 0;
11745 }
11746
11747 // C++ [class.friend]p1: A friend of a class is a function or
11748 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011749 if (DC->Equals(CurContext))
11750 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011751 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011752 diag::warn_cxx98_compat_friend_is_member :
11753 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011754
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011755 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011756 // C++ [class.friend]p6:
11757 // A function can be defined in a friend declaration of a class if and
11758 // only if the class is a non-local class (9.8), the function name is
11759 // unqualified, and the function has namespace scope.
11760 SemaDiagnosticBuilder DB
11761 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11762
11763 DB << SS.getScopeRep();
11764 if (DC->isFileContext())
11765 DB << FixItHint::CreateRemoval(SS.getRange());
11766 SS.clear();
11767 }
John McCallde3fd222010-10-12 23:13:28 +000011768
11769 // - There's a scope specifier that does not match any template
11770 // parameter lists, in which case we use some arbitrary context,
11771 // create a method or method template, and wait for instantiation.
11772 // - There's a scope specifier that does match some template
11773 // parameter lists, which we don't handle right now.
11774 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011775 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011776 // C++ [class.friend]p6:
11777 // A function can be defined in a friend declaration of a class if and
11778 // only if the class is a non-local class (9.8), the function name is
11779 // unqualified, and the function has namespace scope.
11780 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11781 << SS.getScopeRep();
11782 }
11783
John McCallde3fd222010-10-12 23:13:28 +000011784 DC = CurContext;
11785 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011786 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011787
John McCallf7cfb222010-10-13 05:45:15 +000011788 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011789 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011790 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11791 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11792 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011793 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011794 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11795 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011796 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011797 }
John McCall07e91c02009-08-06 02:15:43 +000011798 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011799
Douglas Gregordd847ba2011-11-03 16:37:14 +000011800 // FIXME: This is an egregious hack to cope with cases where the scope stack
11801 // does not contain the declaration context, i.e., in an out-of-line
11802 // definition of a class.
11803 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11804 if (!DCScope) {
11805 FakeDCScope.setEntity(DC);
11806 DCScope = &FakeDCScope;
11807 }
Richard Smith114394f2013-08-09 04:35:01 +000011808
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011809 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011810 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011811 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011812 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011813
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011814 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011815
Richard Smith114394f2013-08-09 04:35:01 +000011816 // If we performed typo correction, we might have added a scope specifier
11817 // and changed the decl context.
11818 DC = ND->getDeclContext();
11819
John McCall759e32b2009-08-31 22:39:49 +000011820 // Add the function declaration to the appropriate lookup tables,
11821 // adjusting the redeclarations list as necessary. We don't
11822 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011823 //
John McCall759e32b2009-08-31 22:39:49 +000011824 // Also update the scope-based lookup if the target context's
11825 // lookup context is in lexical scope.
11826 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011827 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011828 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011829 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011830 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011831 }
John McCallaa74a0c2009-08-28 07:59:38 +000011832
11833 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011834 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011835 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011836 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011837 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011838
John McCalla0a96892012-08-10 03:15:35 +000011839 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011840 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011841 } else {
11842 if (DC->isRecord()) CheckFriendAccess(ND);
11843
John McCall2c2eb122010-10-16 06:59:13 +000011844 FunctionDecl *FD;
11845 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11846 FD = FTD->getTemplatedDecl();
11847 else
11848 FD = cast<FunctionDecl>(ND);
11849
David Majnemer502b0ed2013-06-25 23:09:30 +000011850 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11851 // default argument expression, that declaration shall be a definition
11852 // and shall be the only declaration of the function or function
11853 // template in the translation unit.
11854 if (functionDeclHasDefaultArgument(FD)) {
11855 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11856 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11857 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11858 } else if (!D.isFunctionDefinition())
11859 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11860 }
11861
John McCall2c2eb122010-10-16 06:59:13 +000011862 // Mark templated-scope function declarations as unsupported.
11863 if (FD->getNumTemplateParameterLists())
11864 FrD->setUnsupportedFriend(true);
11865 }
John McCallde3fd222010-10-12 23:13:28 +000011866
John McCall48871652010-08-21 09:40:31 +000011867 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011868}
11869
John McCall48871652010-08-21 09:40:31 +000011870void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11871 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011872
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011873 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011874 if (!Fn) {
11875 Diag(DelLoc, diag::err_deleted_non_function);
11876 return;
11877 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011878
Douglas Gregorec9fd132012-01-14 16:38:05 +000011879 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011880 // Don't consider the implicit declaration we generate for explicit
11881 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000011882 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11883 Prev->getPreviousDecl()) &&
11884 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011885 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000011886 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11887 Prev->isImplicit() ? diag::note_previous_implicit_declaration
11888 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000011889 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011890 // If the declaration wasn't the first, we delete the function anyway for
11891 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011892 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011893 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011894
11895 if (Fn->isDeleted())
11896 return;
11897
11898 // See if we're deleting a function which is already known to override a
11899 // non-deleted virtual function.
11900 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11901 bool IssuedDiagnostic = false;
11902 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11903 E = MD->end_overridden_methods();
11904 I != E; ++I) {
11905 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11906 if (!IssuedDiagnostic) {
11907 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11908 IssuedDiagnostic = true;
11909 }
11910 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11911 }
11912 }
11913 }
11914
Richard Smithb63b6ee2014-01-22 01:43:19 +000011915 // C++11 [basic.start.main]p3:
11916 // A program that defines main as deleted [...] is ill-formed.
11917 if (Fn->isMain())
11918 Diag(DelLoc, diag::err_deleted_main);
11919
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011920 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011921}
Sebastian Redl4c018662009-04-27 21:33:24 +000011922
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011923void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011924 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011925
11926 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000011927 if (MD->getParent()->isDependentType()) {
11928 MD->setDefaulted();
11929 MD->setExplicitlyDefaulted();
11930 return;
11931 }
11932
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011933 CXXSpecialMember Member = getSpecialMember(MD);
11934 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000011935 if (!MD->isInvalidDecl())
11936 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011937 return;
11938 }
11939
11940 MD->setDefaulted();
11941 MD->setExplicitlyDefaulted();
11942
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011943 // If this definition appears within the record, do the checking when
11944 // the record is complete.
11945 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000011946 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011947 // Find the uninstantiated declaration that actually had the '= default'
11948 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000011949 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011950
Richard Smith3901dfe2013-03-27 00:22:47 +000011951 // If the method was defaulted on its first declaration, we will have
11952 // already performed the checking in CheckCompletedCXXClass. Such a
11953 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011954 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011955 return;
11956
Richard Smithd3b5c9082012-07-27 04:22:15 +000011957 CheckExplicitlyDefaultedSpecialMember(MD);
11958
Richard Smithbd305122012-12-11 01:14:52 +000011959 // The exception specification is needed because we are defining the
11960 // function.
11961 ResolveExceptionSpec(DefaultLoc,
11962 MD->getType()->castAs<FunctionProtoType>());
11963
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011964 if (MD->isInvalidDecl())
11965 return;
11966
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011967 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011968 case CXXDefaultConstructor:
11969 DefineImplicitDefaultConstructor(DefaultLoc,
11970 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000011971 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011972 case CXXCopyConstructor:
11973 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011974 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011975 case CXXCopyAssignment:
11976 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000011977 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011978 case CXXDestructor:
11979 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000011980 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011981 case CXXMoveConstructor:
11982 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000011983 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011984 case CXXMoveAssignment:
11985 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011986 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011987 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000011988 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011989 }
11990 } else {
11991 Diag(DefaultLoc, diag::err_default_special_members);
11992 }
11993}
11994
Sebastian Redl4c018662009-04-27 21:33:24 +000011995static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000011996 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000011997 Stmt *SubStmt = *CI;
11998 if (!SubStmt)
11999 continue;
12000 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012001 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012002 diag::err_return_in_constructor_handler);
12003 if (!isa<Expr>(SubStmt))
12004 SearchForReturnInStmt(Self, SubStmt);
12005 }
12006}
12007
12008void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12009 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12010 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12011 SearchForReturnInStmt(*this, Handler);
12012 }
12013}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012014
David Blaikie68f71a32013-01-18 23:03:15 +000012015bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012016 const CXXMethodDecl *Old) {
12017 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12018 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12019
12020 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12021
12022 // If the calling conventions match, everything is fine
12023 if (NewCC == OldCC)
12024 return false;
12025
Hans Wennborg2545efe2013-12-11 17:42:11 +000012026 // If the calling conventions mismatch because the new function is static,
12027 // suppress the calling convention mismatch error; the error about static
12028 // function override (err_static_overrides_virtual from
12029 // Sema::CheckFunctionDeclaration) is more clear.
12030 if (New->getStorageClass() == SC_Static)
12031 return false;
12032
Reid Kleckner78af0702013-08-27 23:08:25 +000012033 Diag(New->getLocation(),
12034 diag::err_conflicting_overriding_cc_attributes)
12035 << New->getDeclName() << New->getType() << Old->getType();
12036 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12037 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012038}
12039
Mike Stump11289f42009-09-09 15:08:12 +000012040bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012041 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012042 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12043 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012044
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012045 if (Context.hasSameType(NewTy, OldTy) ||
12046 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012047 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012048
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012049 // Check if the return types are covariant
12050 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012051
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012052 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012053 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12054 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012055 NewClassTy = NewPT->getPointeeType();
12056 OldClassTy = OldPT->getPointeeType();
12057 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012058 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12059 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12060 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12061 NewClassTy = NewRT->getPointeeType();
12062 OldClassTy = OldRT->getPointeeType();
12063 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012064 }
12065 }
Mike Stump11289f42009-09-09 15:08:12 +000012066
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012067 // The return types aren't either both pointers or references to a class type.
12068 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012069 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012070 diag::err_different_return_type_for_overriding_virtual_function)
12071 << New->getDeclName() << NewTy << OldTy;
12072 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012073
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012074 return true;
12075 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012076
Anders Carlssone60365b2009-12-31 18:34:24 +000012077 // C++ [class.virtual]p6:
12078 // If the return type of D::f differs from the return type of B::f, the
12079 // class type in the return type of D::f shall be complete at the point of
12080 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012081 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12082 if (!RT->isBeingDefined() &&
12083 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012084 diag::err_covariant_return_incomplete,
12085 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012086 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012087 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012088
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012089 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012090 // Check if the new class derives from the old class.
12091 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12092 Diag(New->getLocation(),
12093 diag::err_covariant_return_not_derived)
12094 << New->getDeclName() << NewTy << OldTy;
12095 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12096 return true;
12097 }
Mike Stump11289f42009-09-09 15:08:12 +000012098
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012099 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012100 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012101 diag::err_covariant_return_inaccessible_base,
12102 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12103 // FIXME: Should this point to the return type?
12104 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000012105 // FIXME: this note won't trigger for delayed access control
12106 // diagnostics, and it's impossible to get an undelayed error
12107 // here from access control during the original parse because
12108 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012109 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12110 return true;
12111 }
12112 }
Mike Stump11289f42009-09-09 15:08:12 +000012113
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012114 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012115 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012116 Diag(New->getLocation(),
12117 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012118 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012119 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12120 return true;
12121 };
Mike Stump11289f42009-09-09 15:08:12 +000012122
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012123
12124 // The new class type must have the same or less qualifiers as the old type.
12125 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12126 Diag(New->getLocation(),
12127 diag::err_covariant_return_type_class_type_more_qualified)
12128 << New->getDeclName() << NewTy << OldTy;
12129 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12130 return true;
12131 };
Mike Stump11289f42009-09-09 15:08:12 +000012132
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012133 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012134}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012135
Douglas Gregor21920e372009-12-01 17:24:26 +000012136/// \brief Mark the given method pure.
12137///
12138/// \param Method the method to be marked pure.
12139///
12140/// \param InitRange the source range that covers the "0" initializer.
12141bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012142 SourceLocation EndLoc = InitRange.getEnd();
12143 if (EndLoc.isValid())
12144 Method->setRangeEnd(EndLoc);
12145
Douglas Gregor21920e372009-12-01 17:24:26 +000012146 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12147 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012148 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012149 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012150
12151 if (!Method->isInvalidDecl())
12152 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12153 << Method->getDeclName() << InitRange;
12154 return true;
12155}
12156
Douglas Gregor926410d2012-02-21 02:22:07 +000012157/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012158static bool isStaticDataMember(const Decl *D) {
12159 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12160 return Var->isStaticDataMember();
12161
12162 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012163}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012164
John McCall1f4ee7b2009-12-19 09:28:58 +000012165/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12166/// an initializer for the out-of-line declaration 'Dcl'. The scope
12167/// is a fresh scope pushed for just this purpose.
12168///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012169/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12170/// static data member of class X, names should be looked up in the scope of
12171/// class X.
John McCall48871652010-08-21 09:40:31 +000012172void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012173 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012174 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012175
Richard Smitha2302242013-12-05 07:51:02 +000012176 // We will always have a nested name specifier here, but this declaration
12177 // might not be out of line if the specifier names the current namespace:
12178 // extern int n;
12179 // int ::n = 0;
12180 if (D->isOutOfLine())
12181 EnterDeclaratorContext(S, D->getDeclContext());
12182
Douglas Gregor926410d2012-02-21 02:22:07 +000012183 // If we are parsing the initializer for a static data member, push a
12184 // new expression evaluation context that is associated with this static
12185 // data member.
12186 if (isStaticDataMember(D))
12187 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012188}
12189
12190/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012191/// initializer for the out-of-line declaration 'D'.
12192void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012193 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012194 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012195
Douglas Gregor926410d2012-02-21 02:22:07 +000012196 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012197 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012198
Richard Smitha2302242013-12-05 07:51:02 +000012199 if (D->isOutOfLine())
12200 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012201}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012202
12203/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12204/// C++ if/switch/while/for statement.
12205/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012206DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012207 // C++ 6.4p2:
12208 // The declarator shall not specify a function or an array.
12209 // The type-specifier-seq shall not contain typedef and shall not declare a
12210 // new class or enumeration.
12211 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12212 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012213
12214 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012215 if (!Dcl)
12216 return true;
12217
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012218 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12219 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012220 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012221 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012222 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012223
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012224 return Dcl;
12225}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012226
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012227void Sema::LoadExternalVTableUses() {
12228 if (!ExternalSource)
12229 return;
12230
12231 SmallVector<ExternalVTableUse, 4> VTables;
12232 ExternalSource->ReadUsedVTables(VTables);
12233 SmallVector<VTableUse, 4> NewUses;
12234 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12235 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12236 = VTablesUsed.find(VTables[I].Record);
12237 // Even if a definition wasn't required before, it may be required now.
12238 if (Pos != VTablesUsed.end()) {
12239 if (!Pos->second && VTables[I].DefinitionRequired)
12240 Pos->second = true;
12241 continue;
12242 }
12243
12244 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12245 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12246 }
12247
12248 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12249}
12250
Douglas Gregor88d292c2010-05-13 16:44:06 +000012251void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12252 bool DefinitionRequired) {
12253 // Ignore any vtable uses in unevaluated operands or for classes that do
12254 // not have a vtable.
12255 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012256 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012257 return;
12258
Douglas Gregor88d292c2010-05-13 16:44:06 +000012259 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012260 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012261 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12262 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12263 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12264 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012265 // If we already had an entry, check to see if we are promoting this vtable
12266 // to required a definition. If so, we need to reappend to the VTableUses
12267 // list, since we may have already processed the first entry.
12268 if (DefinitionRequired && !Pos.first->second) {
12269 Pos.first->second = true;
12270 } else {
12271 // Otherwise, we can early exit.
12272 return;
12273 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012274 } else {
12275 // The Microsoft ABI requires that we perform the destructor body
12276 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12277 // the deleting destructor is emitted with the vtable, not with the
12278 // destructor definition as in the Itanium ABI.
12279 // If it has a definition, we do the check at that point instead.
12280 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12281 Class->hasUserDeclaredDestructor() &&
12282 !Class->getDestructor()->isDefined() &&
12283 !Class->getDestructor()->isDeleted()) {
12284 CheckDestructor(Class->getDestructor());
12285 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012286 }
12287
12288 // Local classes need to have their virtual members marked
12289 // immediately. For all other classes, we mark their virtual members
12290 // at the end of the translation unit.
12291 if (Class->isLocalClass())
12292 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012293 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012294 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012295}
12296
Douglas Gregor88d292c2010-05-13 16:44:06 +000012297bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012298 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012299 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012300 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012301
Douglas Gregor88d292c2010-05-13 16:44:06 +000012302 // Note: The VTableUses vector could grow as a result of marking
12303 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012304 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012305 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012306 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012307 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012308 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012309 if (!Class)
12310 continue;
12311
12312 SourceLocation Loc = VTableUses[I].second;
12313
Richard Smithd3b5c9082012-07-27 04:22:15 +000012314 bool DefineVTable = true;
12315
Douglas Gregor88d292c2010-05-13 16:44:06 +000012316 // If this class has a key function, but that key function is
12317 // defined in another translation unit, we don't need to emit the
12318 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012319 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012320 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012321 // The key function is in another translation unit.
12322 DefineVTable = false;
12323 TemplateSpecializationKind TSK =
12324 KeyFunction->getTemplateSpecializationKind();
12325 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12326 TSK != TSK_ImplicitInstantiation &&
12327 "Instantiations don't have key functions");
12328 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012329 } else if (!KeyFunction) {
12330 // If we have a class with no key function that is the subject
12331 // of an explicit instantiation declaration, suppress the
12332 // vtable; it will live with the explicit instantiation
12333 // definition.
12334 bool IsExplicitInstantiationDeclaration
12335 = Class->getTemplateSpecializationKind()
12336 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012337 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012338 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012339 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012340 if (TSK == TSK_ExplicitInstantiationDeclaration)
12341 IsExplicitInstantiationDeclaration = true;
12342 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12343 IsExplicitInstantiationDeclaration = false;
12344 break;
12345 }
12346 }
12347
12348 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012349 DefineVTable = false;
12350 }
12351
12352 // The exception specifications for all virtual members may be needed even
12353 // if we are not providing an authoritative form of the vtable in this TU.
12354 // We may choose to emit it available_externally anyway.
12355 if (!DefineVTable) {
12356 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12357 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012358 }
12359
12360 // Mark all of the virtual members of this class as referenced, so
12361 // that we can build a vtable. Then, tell the AST consumer that a
12362 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012363 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012364 MarkVirtualMembersReferenced(Loc, Class);
12365 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12366 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12367
12368 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012369 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012370 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012371 const FunctionDecl *KeyFunctionDef = 0;
12372 if (!KeyFunction ||
12373 (KeyFunction->hasBody(KeyFunctionDef) &&
12374 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012375 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12376 TSK_ExplicitInstantiationDefinition
12377 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12378 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012379 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012380 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012381 VTableUses.clear();
12382
Douglas Gregor97509692011-04-22 22:25:37 +000012383 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012384}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012385
Richard Smithd3b5c9082012-07-27 04:22:15 +000012386void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12387 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012388 for (const auto *I : RD->methods())
12389 if (I->isVirtual() && !I->isPure())
12390 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012391}
12392
Rafael Espindola5b334082010-03-26 00:36:59 +000012393void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12394 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012395 // Mark all functions which will appear in RD's vtable as used.
12396 CXXFinalOverriderMap FinalOverriders;
12397 RD->getFinalOverriders(FinalOverriders);
12398 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12399 E = FinalOverriders.end();
12400 I != E; ++I) {
12401 for (OverridingMethods::const_iterator OI = I->second.begin(),
12402 OE = I->second.end();
12403 OI != OE; ++OI) {
12404 assert(OI->second.size() > 0 && "no final overrider");
12405 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012406
Richard Smith4ff9ff92012-07-07 06:59:51 +000012407 // C++ [basic.def.odr]p2:
12408 // [...] A virtual member function is used if it is not pure. [...]
12409 if (!Overrider->isPure())
12410 MarkFunctionReferenced(Loc, Overrider);
12411 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012412 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012413
12414 // Only classes that have virtual bases need a VTT.
12415 if (RD->getNumVBases() == 0)
12416 return;
12417
Aaron Ballman574705e2014-03-13 15:41:46 +000012418 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012419 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012420 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012421 if (Base->getNumVBases() == 0)
12422 continue;
12423 MarkVirtualMembersReferenced(Loc, Base);
12424 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012425}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012426
12427/// SetIvarInitializers - This routine builds initialization ASTs for the
12428/// Objective-C implementation whose ivars need be initialized.
12429void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012430 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012431 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012432 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012433 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012434 CollectIvarsToConstructOrDestruct(OID, ivars);
12435 if (ivars.empty())
12436 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012437 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012438 for (unsigned i = 0; i < ivars.size(); i++) {
12439 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012440 if (Field->isInvalidDecl())
12441 continue;
12442
Alexis Hunt1d792652011-01-08 20:30:50 +000012443 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012444 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12445 InitializationKind InitKind =
12446 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012447
12448 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12449 ExprResult MemberInit =
12450 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012451 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012452 // Note, MemberInit could actually come back empty if no initialization
12453 // is required (e.g., because it would call a trivial default constructor)
12454 if (!MemberInit.get() || MemberInit.isInvalid())
12455 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012456
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012457 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012458 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12459 SourceLocation(),
12460 MemberInit.takeAs<Expr>(),
12461 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012462 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012463
12464 // Be sure that the destructor is accessible and is marked as referenced.
12465 if (const RecordType *RecordTy
12466 = Context.getBaseElementType(Field->getType())
12467 ->getAs<RecordType>()) {
12468 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012469 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012470 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012471 CheckDestructorAccess(Field->getLocation(), Destructor,
12472 PDiag(diag::err_access_dtor_ivar)
12473 << Context.getBaseElementType(Field->getType()));
12474 }
12475 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012476 }
12477 ObjCImplementation->setIvarInitializers(Context,
12478 AllToInit.data(), AllToInit.size());
12479 }
12480}
Alexis Hunt6118d662011-05-04 05:57:24 +000012481
Alexis Hunt27a761d2011-05-04 23:29:54 +000012482static
12483void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12484 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12485 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12486 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12487 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012488 if (Ctor->isInvalidDecl())
12489 return;
12490
Richard Smith802c4b72012-08-23 06:16:52 +000012491 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12492
12493 // Target may not be determinable yet, for instance if this is a dependent
12494 // call in an uninstantiated template.
12495 if (Target) {
12496 const FunctionDecl *FNTarget = 0;
12497 (void)Target->hasBody(FNTarget);
12498 Target = const_cast<CXXConstructorDecl*>(
12499 cast_or_null<CXXConstructorDecl>(FNTarget));
12500 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012501
12502 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12503 // Avoid dereferencing a null pointer here.
12504 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12505
12506 if (!Current.insert(Canonical))
12507 return;
12508
12509 // We know that beyond here, we aren't chaining into a cycle.
12510 if (!Target || !Target->isDelegatingConstructor() ||
12511 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012512 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012513 Current.clear();
12514 // We've hit a cycle.
12515 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12516 Current.count(TCanonical)) {
12517 // If we haven't diagnosed this cycle yet, do so now.
12518 if (!Invalid.count(TCanonical)) {
12519 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012520 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012521 << Ctor;
12522
Richard Smith802c4b72012-08-23 06:16:52 +000012523 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012524 if (TCanonical != Canonical)
12525 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12526
12527 CXXConstructorDecl *C = Target;
12528 while (C->getCanonicalDecl() != Canonical) {
Richard Smith802c4b72012-08-23 06:16:52 +000012529 const FunctionDecl *FNTarget = 0;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012530 (void)C->getTargetConstructor()->hasBody(FNTarget);
12531 assert(FNTarget && "Ctor cycle through bodiless function");
12532
Richard Smith802c4b72012-08-23 06:16:52 +000012533 C = const_cast<CXXConstructorDecl*>(
12534 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012535 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12536 }
12537 }
12538
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012539 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012540 Current.clear();
12541 } else {
12542 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12543 }
12544}
12545
12546
Alexis Hunt6118d662011-05-04 05:57:24 +000012547void Sema::CheckDelegatingCtorCycles() {
12548 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12549
Douglas Gregorbae31202011-07-27 21:57:17 +000012550 for (DelegatingCtorDeclsType::iterator
12551 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012552 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012553 I != E; ++I)
12554 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012555
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012556 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12557 CE = Invalid.end();
12558 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012559 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012560}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012561
Douglas Gregor3024f072012-04-16 07:05:22 +000012562namespace {
12563 /// \brief AST visitor that finds references to the 'this' expression.
12564 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12565 Sema &S;
12566
12567 public:
12568 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12569
12570 bool VisitCXXThisExpr(CXXThisExpr *E) {
12571 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12572 << E->isImplicit();
12573 return false;
12574 }
12575 };
12576}
12577
12578bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12579 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12580 if (!TSInfo)
12581 return false;
12582
12583 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012584 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012585 if (!ProtoTL)
12586 return false;
12587
12588 // C++11 [expr.prim.general]p3:
12589 // [The expression this] shall not appear before the optional
12590 // cv-qualifier-seq and it shall not appear within the declaration of a
12591 // static member function (although its type and value category are defined
12592 // within a static member function as they are within a non-static member
12593 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012594 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012595 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012596 FindCXXThisExpr Finder(*this);
12597
12598 // If the return type came after the cv-qualifier-seq, check it now.
12599 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012600 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012601 return true;
12602
12603 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012604 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12605 return true;
12606
12607 return checkThisInStaticMemberFunctionAttributes(Method);
12608}
12609
12610bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12611 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12612 if (!TSInfo)
12613 return false;
12614
12615 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012616 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012617 if (!ProtoTL)
12618 return false;
12619
David Blaikie6adc78e2013-02-18 22:06:02 +000012620 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012621 FindCXXThisExpr Finder(*this);
12622
Douglas Gregor3024f072012-04-16 07:05:22 +000012623 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012624 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012625 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012626 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012627 case EST_DynamicNone:
12628 case EST_MSAny:
12629 case EST_None:
12630 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012631
Douglas Gregor3024f072012-04-16 07:05:22 +000012632 case EST_ComputedNoexcept:
12633 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12634 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012635
Douglas Gregor3024f072012-04-16 07:05:22 +000012636 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012637 for (const auto &E : Proto->exceptions()) {
12638 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012639 return true;
12640 }
12641 break;
12642 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012643
12644 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012645}
12646
12647bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12648 FindCXXThisExpr Finder(*this);
12649
12650 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012651 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012652 // FIXME: This should be emitted by tblgen.
12653 Expr *Arg = 0;
12654 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012655 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012656 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012657 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012658 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012659 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012660 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012661 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012662 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012663 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012664 Arg = ETLF->getSuccessValue();
12665 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012666 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012667 Arg = STLF->getSuccessValue();
12668 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000012669 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012670 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012671 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012672 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012673 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012674 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012675 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012676 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012677 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12678 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12679 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012680 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012681
12682 if (Arg && !Finder.TraverseStmt(Arg))
12683 return true;
12684
12685 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12686 if (!Finder.TraverseStmt(Args[I]))
12687 return true;
12688 }
12689 }
12690
12691 return false;
12692}
12693
Douglas Gregor433e0532012-04-16 18:27:27 +000012694void
12695Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12696 ArrayRef<ParsedType> DynamicExceptions,
12697 ArrayRef<SourceRange> DynamicExceptionRanges,
12698 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012699 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012700 FunctionProtoType::ExtProtoInfo &EPI) {
12701 Exceptions.clear();
12702 EPI.ExceptionSpecType = EST;
12703 if (EST == EST_Dynamic) {
12704 Exceptions.reserve(DynamicExceptions.size());
12705 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12706 // FIXME: Preserve type source info.
12707 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12708
12709 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12710 collectUnexpandedParameterPacks(ET, Unexpanded);
12711 if (!Unexpanded.empty()) {
12712 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12713 UPPC_ExceptionType,
12714 Unexpanded);
12715 continue;
12716 }
12717
12718 // Check that the type is valid for an exception spec, and
12719 // drop it if not.
12720 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12721 Exceptions.push_back(ET);
12722 }
12723 EPI.NumExceptions = Exceptions.size();
12724 EPI.Exceptions = Exceptions.data();
12725 return;
12726 }
12727
12728 if (EST == EST_ComputedNoexcept) {
12729 // If an error occurred, there's no expression here.
12730 if (NoexceptExpr) {
12731 assert((NoexceptExpr->isTypeDependent() ||
12732 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12733 Context.BoolTy) &&
12734 "Parser should have made sure that the expression is boolean");
12735 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12736 EPI.ExceptionSpecType = EST_BasicNoexcept;
12737 return;
12738 }
12739
12740 if (!NoexceptExpr->isValueDependent())
12741 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012742 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012743 /*AllowFold*/ false).take();
12744 EPI.NoexceptExpr = NoexceptExpr;
12745 }
12746 return;
12747 }
12748}
12749
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012750/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12751Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12752 // Implicitly declared functions (e.g. copy constructors) are
12753 // __host__ __device__
12754 if (D->isImplicit())
12755 return CFT_HostDevice;
12756
12757 if (D->hasAttr<CUDAGlobalAttr>())
12758 return CFT_Global;
12759
12760 if (D->hasAttr<CUDADeviceAttr>()) {
12761 if (D->hasAttr<CUDAHostAttr>())
12762 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012763 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012764 }
12765
12766 return CFT_Host;
12767}
12768
12769bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12770 CUDAFunctionTarget CalleeTarget) {
12771 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12772 // Callable from the device only."
12773 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12774 return true;
12775
12776 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12777 // Callable from the host only."
12778 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12779 // Callable from the host only."
12780 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12781 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12782 return true;
12783
12784 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12785 return true;
12786
12787 return false;
12788}
John McCall5e77d762013-04-16 07:28:30 +000012789
12790/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12791///
12792MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12793 SourceLocation DeclStart,
12794 Declarator &D, Expr *BitWidth,
12795 InClassInitStyle InitStyle,
12796 AccessSpecifier AS,
12797 AttributeList *MSPropertyAttr) {
12798 IdentifierInfo *II = D.getIdentifier();
12799 if (!II) {
12800 Diag(DeclStart, diag::err_anonymous_property);
12801 return NULL;
12802 }
12803 SourceLocation Loc = D.getIdentifierLoc();
12804
12805 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12806 QualType T = TInfo->getType();
12807 if (getLangOpts().CPlusPlus) {
12808 CheckExtraCXXDefaultArguments(D);
12809
12810 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12811 UPPC_DataMemberType)) {
12812 D.setInvalidType();
12813 T = Context.IntTy;
12814 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12815 }
12816 }
12817
12818 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12819
12820 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12821 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12822 diag::err_invalid_thread)
12823 << DeclSpec::getSpecifierName(TSCS);
12824
12825 // Check to see if this name was declared as a member previously
12826 NamedDecl *PrevDecl = 0;
12827 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12828 LookupName(Previous, S);
12829 switch (Previous.getResultKind()) {
12830 case LookupResult::Found:
12831 case LookupResult::FoundUnresolvedValue:
12832 PrevDecl = Previous.getAsSingle<NamedDecl>();
12833 break;
12834
12835 case LookupResult::FoundOverloaded:
12836 PrevDecl = Previous.getRepresentativeDecl();
12837 break;
12838
12839 case LookupResult::NotFound:
12840 case LookupResult::NotFoundInCurrentInstantiation:
12841 case LookupResult::Ambiguous:
12842 break;
12843 }
12844
12845 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12846 // Maybe we will complain about the shadowed template parameter.
12847 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12848 // Just pretend that we didn't see the previous declaration.
12849 PrevDecl = 0;
12850 }
12851
12852 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12853 PrevDecl = 0;
12854
12855 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000012856 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000012857 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12858 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000012859 ProcessDeclAttributes(TUScope, NewPD, D);
12860 NewPD->setAccess(AS);
12861
12862 if (NewPD->isInvalidDecl())
12863 Record->setInvalidDecl();
12864
12865 if (D.getDeclSpec().isModulePrivateSpecified())
12866 NewPD->setModulePrivate();
12867
12868 if (NewPD->isInvalidDecl() && PrevDecl) {
12869 // Don't introduce NewFD into scope; there's already something
12870 // with the same name in the same scope.
12871 } else if (II) {
12872 PushOnScopeChains(NewPD, S);
12873 } else
12874 Record->addDecl(NewPD);
12875
12876 return NewPD;
12877}