blob: 36a1541a232faba3affd33a654f698b85a8309b9 [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
Richard Smith5b8b3db2012-02-20 23:28:05 +0000587 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000588 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000589 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000590 if (New->isConstexpr() != Old->isConstexpr()) {
591 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
592 << New << New->isConstexpr();
593 Diag(Old->getLocation(), diag::note_previous_declaration);
594 Invalid = true;
595 }
596
David Majnemer502b0ed2013-06-25 23:09:30 +0000597 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000598 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000599 // the only declaration of the function or function template in the
600 // translation unit.
601 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
602 functionDeclHasDefaultArgument(Old)) {
603 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
604 Diag(Old->getLocation(), diag::note_previous_declaration);
605 Invalid = true;
606 }
607
Douglas Gregorf40863c2010-02-12 07:32:17 +0000608 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000609 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000610
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000611 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000612}
613
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000614/// \brief Merge the exception specifications of two variable declarations.
615///
616/// This is called when there's a redeclaration of a VarDecl. The function
617/// checks if the redeclaration might have an exception specification and
618/// validates compatibility and merges the specs if necessary.
619void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
620 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000621 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000622 return;
623
624 assert(Context.hasSameType(New->getType(), Old->getType()) &&
625 "Should only be called if types are otherwise the same.");
626
627 QualType NewType = New->getType();
628 QualType OldType = Old->getType();
629
630 // We're only interested in pointers and references to functions, as well
631 // as pointers to member functions.
632 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
633 NewType = R->getPointeeType();
634 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
635 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
636 NewType = P->getPointeeType();
637 OldType = OldType->getAs<PointerType>()->getPointeeType();
638 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
639 NewType = M->getPointeeType();
640 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
641 }
642
643 if (!NewType->isFunctionProtoType())
644 return;
645
646 // There's lots of special cases for functions. For function pointers, system
647 // libraries are hopefully not as broken so that we don't need these
648 // workarounds.
649 if (CheckEquivalentExceptionSpec(
650 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
651 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
652 New->setInvalidDecl();
653 }
654}
655
Chris Lattner199abbc2008-04-08 05:04:30 +0000656/// CheckCXXDefaultArguments - Verify that the default arguments for a
657/// function declaration are well-formed according to C++
658/// [dcl.fct.default].
659void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
660 unsigned NumParams = FD->getNumParams();
661 unsigned p;
662
663 // Find first parameter with a default argument
664 for (p = 0; p < NumParams; ++p) {
665 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000666 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000667 break;
668 }
669
670 // C++ [dcl.fct.default]p4:
671 // In a given function declaration, all parameters
672 // subsequent to a parameter with a default argument shall
673 // have default arguments supplied in this or previous
674 // declarations. A default argument shall not be redefined
675 // by a later declaration (not even to the same value).
676 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000677 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000678 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000679 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000680 if (Param->isInvalidDecl())
681 /* We already complained about this parameter. */;
682 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000683 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000684 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000685 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000686 else
Mike Stump11289f42009-09-09 15:08:12 +0000687 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000688 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000689
Chris Lattner199abbc2008-04-08 05:04:30 +0000690 LastMissingDefaultArg = p;
691 }
692 }
693
694 if (LastMissingDefaultArg > 0) {
695 // Some default arguments were missing. Clear out all of the
696 // default arguments up to (and including) the last missing
697 // default argument, so that we leave the function parameters
698 // in a semantically valid state.
699 for (p = 0; p <= LastMissingDefaultArg; ++p) {
700 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000701 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000702 Param->setDefaultArg(0);
703 }
704 }
705 }
706}
Douglas Gregor556877c2008-04-13 21:30:24 +0000707
Richard Smitheb3c10c2011-10-01 02:31:28 +0000708// CheckConstexprParameterTypes - Check whether a function's parameter types
709// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000710// diagnostic and return false.
711static bool CheckConstexprParameterTypes(Sema &SemaRef,
712 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000713 unsigned ArgIndex = 0;
714 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000715 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
716 e = FT->param_type_end();
717 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000718 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
719 SourceLocation ParamLoc = PD->getLocation();
720 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000721 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000722 diag::err_constexpr_non_literal_param,
723 ArgIndex+1, PD->getSourceRange(),
724 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000725 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000726 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000727 return true;
728}
729
730/// \brief Get diagnostic %select index for tag kind for
731/// record diagnostic message.
732/// WARNING: Indexes apply to particular diagnostics only!
733///
734/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000735static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000736 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000737 case TTK_Struct: return 0;
738 case TTK_Interface: return 1;
739 case TTK_Class: return 2;
740 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000741 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000742}
743
744// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
745// the requirements of a constexpr function definition or a constexpr
746// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000747// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000748//
Richard Smith3607ffe2012-02-13 03:54:03 +0000749// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
750bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000751 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
752 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000753 // C++11 [dcl.constexpr]p4:
754 // The definition of a constexpr constructor shall satisfy the following
755 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000756 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000757 const CXXRecordDecl *RD = MD->getParent();
758 if (RD->getNumVBases()) {
759 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
760 << isa<CXXConstructorDecl>(NewFD)
761 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000762 for (const auto &I : RD->vbases())
763 Diag(I.getLocStart(),
764 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000765 return false;
766 }
Richard Smith7971b692012-01-13 04:54:00 +0000767 }
768
769 if (!isa<CXXConstructorDecl>(NewFD)) {
770 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000771 // The definition of a constexpr function shall satisfy the following
772 // constraints:
773 // - it shall not be virtual;
774 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
775 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000776 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000777
Richard Smith3607ffe2012-02-13 03:54:03 +0000778 // If it's not obvious why this function is virtual, find an overridden
779 // function which uses the 'virtual' keyword.
780 const CXXMethodDecl *WrittenVirtual = Method;
781 while (!WrittenVirtual->isVirtualAsWritten())
782 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
783 if (WrittenVirtual != Method)
784 Diag(WrittenVirtual->getLocation(),
785 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000786 return false;
787 }
788
789 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000790 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000791 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000792 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000793 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000794 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000795 }
796
Richard Smith7971b692012-01-13 04:54:00 +0000797 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000798 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000799 return false;
800
Richard Smitheb3c10c2011-10-01 02:31:28 +0000801 return true;
802}
803
804/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000805/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000806///
Richard Smithd9f663b2013-04-22 15:31:51 +0000807/// \return true if the body is OK (maybe only as an extension), false if we
808/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000809static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000810 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
811 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000812 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
813 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000814 for (const auto *DclIt : DS->decls()) {
815 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000816 case Decl::StaticAssert:
817 case Decl::Using:
818 case Decl::UsingShadow:
819 case Decl::UsingDirective:
820 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000821 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000822 // - static_assert-declarations
823 // - using-declarations,
824 // - using-directives,
825 continue;
826
827 case Decl::Typedef:
828 case Decl::TypeAlias: {
829 // - typedef declarations and alias-declarations that do not define
830 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000831 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000832 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
833 // Don't allow variably-modified types in constexpr functions.
834 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
835 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
836 << TL.getSourceRange() << TL.getType()
837 << isa<CXXConstructorDecl>(Dcl);
838 return false;
839 }
840 continue;
841 }
842
843 case Decl::Enum:
844 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000845 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000846 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000847 SemaRef.Diag(DS->getLocStart(),
848 SemaRef.getLangOpts().CPlusPlus1y
849 ? diag::warn_cxx11_compat_constexpr_type_definition
850 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000851 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000852 continue;
853
Richard Smithd9f663b2013-04-22 15:31:51 +0000854 case Decl::EnumConstant:
855 case Decl::IndirectField:
856 case Decl::ParmVar:
857 // These can only appear with other declarations which are banned in
858 // C++11 and permitted in C++1y, so ignore them.
859 continue;
860
861 case Decl::Var: {
862 // C++1y [dcl.constexpr]p3 allows anything except:
863 // a definition of a variable of non-literal type or of static or
864 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000865 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000866 if (VD->isThisDeclarationADefinition()) {
867 if (VD->isStaticLocal()) {
868 SemaRef.Diag(VD->getLocation(),
869 diag::err_constexpr_local_var_static)
870 << isa<CXXConstructorDecl>(Dcl)
871 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
872 return false;
873 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000874 if (!VD->getType()->isDependentType() &&
875 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000876 VD->getLocation(), VD->getType(),
877 diag::err_constexpr_local_var_non_literal_type,
878 isa<CXXConstructorDecl>(Dcl)))
879 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000880 if (!VD->getType()->isDependentType() &&
881 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000882 SemaRef.Diag(VD->getLocation(),
883 diag::err_constexpr_local_var_no_init)
884 << isa<CXXConstructorDecl>(Dcl);
885 return false;
886 }
887 }
888 SemaRef.Diag(VD->getLocation(),
889 SemaRef.getLangOpts().CPlusPlus1y
890 ? diag::warn_cxx11_compat_constexpr_local_var
891 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000892 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000893 continue;
894 }
895
896 case Decl::NamespaceAlias:
897 case Decl::Function:
898 // These are disallowed in C++11 and permitted in C++1y. Allow them
899 // everywhere as an extension.
900 if (!Cxx1yLoc.isValid())
901 Cxx1yLoc = DS->getLocStart();
902 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000903
904 default:
905 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
906 << isa<CXXConstructorDecl>(Dcl);
907 return false;
908 }
909 }
910
911 return true;
912}
913
914/// Check that the given field is initialized within a constexpr constructor.
915///
916/// \param Dcl The constexpr constructor being checked.
917/// \param Field The field being checked. This may be a member of an anonymous
918/// struct or union nested within the class being checked.
919/// \param Inits All declarations, including anonymous struct/union members and
920/// indirect members, for which any initialization was provided.
921/// \param Diagnosed Set to true if an error is produced.
922static void CheckConstexprCtorInitializer(Sema &SemaRef,
923 const FunctionDecl *Dcl,
924 FieldDecl *Field,
925 llvm::SmallSet<Decl*, 16> &Inits,
926 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000927 if (Field->isInvalidDecl())
928 return;
929
Douglas Gregor556e5862011-10-10 17:22:13 +0000930 if (Field->isUnnamedBitfield())
931 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000932
Richard Smithab44d5b2013-12-10 08:25:00 +0000933 // Anonymous unions with no variant members and empty anonymous structs do not
934 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
935 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000936 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000937 (Field->getType()->isUnionType()
938 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
939 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000940 return;
941
Richard Smitheb3c10c2011-10-01 02:31:28 +0000942 if (!Inits.count(Field)) {
943 if (!Diagnosed) {
944 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
945 Diagnosed = true;
946 }
947 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
948 } else if (Field->isAnonymousStructOrUnion()) {
949 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000950 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000951 // If an anonymous union contains an anonymous struct of which any member
952 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000953 if (!RD->isUnion() || Inits.count(I))
954 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000955 }
956}
957
Richard Smithd9f663b2013-04-22 15:31:51 +0000958/// Check the provided statement is allowed in a constexpr function
959/// definition.
960static bool
961CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000962 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000963 SourceLocation &Cxx1yLoc) {
964 // - its function-body shall be [...] a compound-statement that contains only
965 switch (S->getStmtClass()) {
966 case Stmt::NullStmtClass:
967 // - null statements,
968 return true;
969
970 case Stmt::DeclStmtClass:
971 // - static_assert-declarations
972 // - using-declarations,
973 // - using-directives,
974 // - typedef declarations and alias-declarations that do not define
975 // classes or enumerations,
976 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
977 return false;
978 return true;
979
980 case Stmt::ReturnStmtClass:
981 // - and exactly one return statement;
982 if (isa<CXXConstructorDecl>(Dcl)) {
983 // C++1y allows return statements in constexpr constructors.
984 if (!Cxx1yLoc.isValid())
985 Cxx1yLoc = S->getLocStart();
986 return true;
987 }
988
989 ReturnStmts.push_back(S->getLocStart());
990 return true;
991
992 case Stmt::CompoundStmtClass: {
993 // C++1y allows compound-statements.
994 if (!Cxx1yLoc.isValid())
995 Cxx1yLoc = S->getLocStart();
996
997 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +0000998 for (auto *BodyIt : CompStmt->body()) {
999 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001000 Cxx1yLoc))
1001 return false;
1002 }
1003 return true;
1004 }
1005
1006 case Stmt::AttributedStmtClass:
1007 if (!Cxx1yLoc.isValid())
1008 Cxx1yLoc = S->getLocStart();
1009 return true;
1010
1011 case Stmt::IfStmtClass: {
1012 // C++1y allows if-statements.
1013 if (!Cxx1yLoc.isValid())
1014 Cxx1yLoc = S->getLocStart();
1015
1016 IfStmt *If = cast<IfStmt>(S);
1017 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1018 Cxx1yLoc))
1019 return false;
1020 if (If->getElse() &&
1021 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1022 Cxx1yLoc))
1023 return false;
1024 return true;
1025 }
1026
1027 case Stmt::WhileStmtClass:
1028 case Stmt::DoStmtClass:
1029 case Stmt::ForStmtClass:
1030 case Stmt::CXXForRangeStmtClass:
1031 case Stmt::ContinueStmtClass:
1032 // C++1y allows all of these. We don't allow them as extensions in C++11,
1033 // because they don't make sense without variable mutation.
1034 if (!SemaRef.getLangOpts().CPlusPlus1y)
1035 break;
1036 if (!Cxx1yLoc.isValid())
1037 Cxx1yLoc = S->getLocStart();
1038 for (Stmt::child_range Children = S->children(); Children; ++Children)
1039 if (*Children &&
1040 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1041 Cxx1yLoc))
1042 return false;
1043 return true;
1044
1045 case Stmt::SwitchStmtClass:
1046 case Stmt::CaseStmtClass:
1047 case Stmt::DefaultStmtClass:
1048 case Stmt::BreakStmtClass:
1049 // C++1y allows switch-statements, and since they don't need variable
1050 // mutation, we can reasonably allow them in C++11 as an extension.
1051 if (!Cxx1yLoc.isValid())
1052 Cxx1yLoc = S->getLocStart();
1053 for (Stmt::child_range Children = S->children(); Children; ++Children)
1054 if (*Children &&
1055 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1056 Cxx1yLoc))
1057 return false;
1058 return true;
1059
1060 default:
1061 if (!isa<Expr>(S))
1062 break;
1063
1064 // C++1y allows expression-statements.
1065 if (!Cxx1yLoc.isValid())
1066 Cxx1yLoc = S->getLocStart();
1067 return true;
1068 }
1069
1070 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1071 << isa<CXXConstructorDecl>(Dcl);
1072 return false;
1073}
1074
Richard Smitheb3c10c2011-10-01 02:31:28 +00001075/// Check the body for the given constexpr function declaration only contains
1076/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1077///
1078/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001079bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001080 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001081 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001082 // The definition of a constexpr function shall satisfy the following
1083 // constraints: [...]
1084 // - its function-body shall be = delete, = default, or a
1085 // compound-statement
1086 //
Richard Smith74388b42012-02-04 00:33:54 +00001087 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001088 // In the definition of a constexpr constructor, [...]
1089 // - its function-body shall not be a function-try-block;
1090 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1091 << isa<CXXConstructorDecl>(Dcl);
1092 return false;
1093 }
1094
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001095 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001096
1097 // - its function-body shall be [...] a compound-statement that contains only
1098 // [... list of cases ...]
1099 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1100 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001101 for (auto *BodyIt : CompBody->body()) {
1102 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001103 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001104 }
1105
Richard Smithd9f663b2013-04-22 15:31:51 +00001106 if (Cxx1yLoc.isValid())
1107 Diag(Cxx1yLoc,
1108 getLangOpts().CPlusPlus1y
1109 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1110 : diag::ext_constexpr_body_invalid_stmt)
1111 << isa<CXXConstructorDecl>(Dcl);
1112
Richard Smitheb3c10c2011-10-01 02:31:28 +00001113 if (const CXXConstructorDecl *Constructor
1114 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1115 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001116 // DR1359:
1117 // - every non-variant non-static data member and base class sub-object
1118 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001119 // DR1460:
1120 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001121 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001122 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001123 if (Constructor->getNumCtorInitializers() == 0 &&
1124 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001125 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1126 return false;
1127 }
Richard Smithf368fb42011-10-10 16:38:04 +00001128 } else if (!Constructor->isDependentContext() &&
1129 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001130 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1131
1132 // Skip detailed checking if we have enough initializers, and we would
1133 // allow at most one initializer per member.
1134 bool AnyAnonStructUnionMembers = false;
1135 unsigned Fields = 0;
1136 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1137 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001138 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001139 AnyAnonStructUnionMembers = true;
1140 break;
1141 }
1142 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001143 // DR1460:
1144 // - if the class is a union-like class, but is not a union, for each of
1145 // its anonymous union members having variant members, exactly one of
1146 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001147 if (AnyAnonStructUnionMembers ||
1148 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1149 // Check initialization of non-static data members. Base classes are
1150 // always initialized so do not need to be checked. Dependent bases
1151 // might not have initializers in the member initializer list.
1152 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001153 for (const auto *I: Constructor->inits()) {
1154 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001155 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001156 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001157 Inits.insert(ID->chain_begin(), ID->chain_end());
1158 }
1159
1160 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001161 for (auto *I : RD->fields())
1162 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001163 if (Diagnosed)
1164 return false;
1165 }
1166 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001167 } else {
1168 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001169 // C++1y doesn't require constexpr functions to contain a 'return'
1170 // statement. We still do, unless the return type is void, because
1171 // otherwise if there's no return statement, the function cannot
1172 // be used in a core constant expression.
Alp Toker314cc812014-01-25 16:55:45 +00001173 bool OK = getLangOpts().CPlusPlus1y && Dcl->getReturnType()->isVoidType();
Richard Smithd9f663b2013-04-22 15:31:51 +00001174 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001175 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1176 : diag::err_constexpr_body_no_return);
1177 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001178 }
1179 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001180 Diag(ReturnStmts.back(),
1181 getLangOpts().CPlusPlus1y
1182 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1183 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001184 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1185 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001186 }
1187 }
1188
Richard Smith74388b42012-02-04 00:33:54 +00001189 // C++11 [dcl.constexpr]p5:
1190 // if no function argument values exist such that the function invocation
1191 // substitution would produce a constant expression, the program is
1192 // ill-formed; no diagnostic required.
1193 // C++11 [dcl.constexpr]p3:
1194 // - every constructor call and implicit conversion used in initializing the
1195 // return value shall be one of those allowed in a constant expression.
1196 // C++11 [dcl.constexpr]p4:
1197 // - every constructor involved in initializing non-static data members and
1198 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001199 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001200 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001201 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001202 << isa<CXXConstructorDecl>(Dcl);
1203 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1204 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001205 // Don't return false here: we allow this for compatibility in
1206 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001207 }
1208
Richard Smitheb3c10c2011-10-01 02:31:28 +00001209 return true;
1210}
1211
Douglas Gregor61956c42008-10-31 09:07:45 +00001212/// isCurrentClassName - Determine whether the identifier II is the
1213/// name of the class type currently being defined. In the case of
1214/// nested classes, this will only return true if II is the name of
1215/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001216bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1217 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001218 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001219
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001220 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001221 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001222 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001223 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1224 } else
1225 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1226
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001227 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001228 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001229 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001230}
1231
Richard Smithfb8b7b92013-10-15 00:00:26 +00001232/// \brief Determine whether the identifier II is a typo for the name of
1233/// the class type currently being defined. If so, update it to the identifier
1234/// that should have been used.
1235bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1236 assert(getLangOpts().CPlusPlus && "No class names in C!");
1237
1238 if (!getLangOpts().SpellChecking)
1239 return false;
1240
1241 CXXRecordDecl *CurDecl;
1242 if (SS && SS->isSet() && !SS->isInvalid()) {
1243 DeclContext *DC = computeDeclContext(*SS, true);
1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1245 } else
1246 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1247
1248 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1249 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1250 < II->getLength()) {
1251 II = CurDecl->getIdentifier();
1252 return true;
1253 }
1254
1255 return false;
1256}
1257
Douglas Gregordc974572012-11-10 07:24:09 +00001258/// \brief Determine whether the given class is a base class of the given
1259/// class, including looking at dependent bases.
1260static bool findCircularInheritance(const CXXRecordDecl *Class,
1261 const CXXRecordDecl *Current) {
1262 SmallVector<const CXXRecordDecl*, 8> Queue;
1263
1264 Class = Class->getCanonicalDecl();
1265 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001266 for (const auto &I : Current->bases()) {
1267 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001268 if (!Base)
1269 continue;
1270
1271 Base = Base->getDefinition();
1272 if (!Base)
1273 continue;
1274
1275 if (Base->getCanonicalDecl() == Class)
1276 return true;
1277
1278 Queue.push_back(Base);
1279 }
1280
1281 if (Queue.empty())
1282 return false;
1283
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001284 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001285 }
1286
1287 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001288}
1289
Mike Stump11289f42009-09-09 15:08:12 +00001290/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001291///
1292/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1293/// and returns NULL otherwise.
1294CXXBaseSpecifier *
1295Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1296 SourceRange SpecifierRange,
1297 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001298 TypeSourceInfo *TInfo,
1299 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001300 QualType BaseType = TInfo->getType();
1301
Douglas Gregor463421d2009-03-03 04:44:36 +00001302 // C++ [class.union]p1:
1303 // A union shall not have base classes.
1304 if (Class->isUnion()) {
1305 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1306 << SpecifierRange;
1307 return 0;
1308 }
1309
Douglas Gregor752a5952011-01-03 22:36:02 +00001310 if (EllipsisLoc.isValid() &&
1311 !TInfo->getType()->containsUnexpandedParameterPack()) {
1312 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1313 << TInfo->getTypeLoc().getSourceRange();
1314 EllipsisLoc = SourceLocation();
1315 }
Douglas Gregor62004702012-11-10 01:18:17 +00001316
1317 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1318
1319 if (BaseType->isDependentType()) {
1320 // Make sure that we don't have circular inheritance among our dependent
1321 // bases. For non-dependent bases, the check for completeness below handles
1322 // this.
1323 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1324 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1325 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001326 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001327 Diag(BaseLoc, diag::err_circular_inheritance)
1328 << BaseType << Context.getTypeDeclType(Class);
1329
1330 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1331 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1332 << BaseType;
1333
1334 return 0;
1335 }
1336 }
1337
Mike Stump11289f42009-09-09 15:08:12 +00001338 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001339 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001340 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001341 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001342
1343 // Base specifiers must be record types.
1344 if (!BaseType->isRecordType()) {
1345 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1346 return 0;
1347 }
1348
1349 // C++ [class.union]p1:
1350 // A union shall not be used as a base class.
1351 if (BaseType->isUnionType()) {
1352 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1353 return 0;
1354 }
1355
1356 // C++ [class.derived]p2:
1357 // The class-name in a base-specifier shall not be an incompletely
1358 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001359 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001360 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001361 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001362 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001363 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001364
Eli Friedmanc96d4962009-08-15 21:55:26 +00001365 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001366 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001367 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001368 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001369 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001370 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001371 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001372
David Majnemer9b1754d2013-11-02 12:00:36 +00001373 // A class which contains a flexible array member is not suitable for use as a
1374 // base class:
1375 // - If the layout determines that a base comes before another base,
1376 // the flexible array member would index into the subsequent base.
1377 // - If the layout determines that base comes before the derived class,
1378 // the flexible array member would index into the derived class.
1379 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1380 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1381 << CXXBaseDecl->getDeclName();
1382 return 0;
1383 }
1384
Anders Carlsson65c76d32011-03-25 14:55:14 +00001385 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001386 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001387 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001388 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001389 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001390 << CXXBaseDecl->getDeclName()
1391 << FA->isSpelledAsSealed();
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001392 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1393 << CXXBaseDecl->getDeclName();
1394 return 0;
1395 }
1396
John McCall3696dcb2010-08-17 07:23:57 +00001397 if (BaseDecl->isInvalidDecl())
1398 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001399
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001400 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001401 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001402 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001403 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001404}
1405
Douglas Gregor556877c2008-04-13 21:30:24 +00001406/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1407/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001408/// example:
1409/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001410/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001411BaseResult
John McCall48871652010-08-21 09:40:31 +00001412Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001413 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001414 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001415 ParsedType basetype, SourceLocation BaseLoc,
1416 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001417 if (!classdecl)
1418 return true;
1419
Douglas Gregorc40290e2009-03-09 23:48:35 +00001420 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001421 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001422 if (!Class)
1423 return true;
1424
Richard Smith4c96e992013-02-19 23:47:15 +00001425 // We do not support any C++11 attributes on base-specifiers yet.
1426 // Diagnose any attributes we see.
1427 if (!Attributes.empty()) {
1428 for (AttributeList *Attr = Attributes.getList(); Attr;
1429 Attr = Attr->getNext()) {
1430 if (Attr->isInvalid() ||
1431 Attr->getKind() == AttributeList::IgnoredAttribute)
1432 continue;
1433 Diag(Attr->getLoc(),
1434 Attr->getKind() == AttributeList::UnknownAttribute
1435 ? diag::warn_unknown_attribute_ignored
1436 : diag::err_base_specifier_attribute)
1437 << Attr->getName();
1438 }
1439 }
1440
Nick Lewycky19b9f952010-07-26 16:56:01 +00001441 TypeSourceInfo *TInfo = 0;
1442 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001443
Douglas Gregor752a5952011-01-03 22:36:02 +00001444 if (EllipsisLoc.isInvalid() &&
1445 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001446 UPPC_BaseType))
1447 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001448
Douglas Gregor463421d2009-03-03 04:44:36 +00001449 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001450 Virtual, Access, TInfo,
1451 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001452 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001453 else
1454 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001455
Douglas Gregor463421d2009-03-03 04:44:36 +00001456 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001457}
Douglas Gregor556877c2008-04-13 21:30:24 +00001458
Douglas Gregor463421d2009-03-03 04:44:36 +00001459/// \brief Performs the actual work of attaching the given base class
1460/// specifiers to a C++ class.
1461bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1462 unsigned NumBases) {
1463 if (NumBases == 0)
1464 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001465
1466 // Used to keep track of which base types we have already seen, so
1467 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001468 // that the key is always the unqualified canonical type of the base
1469 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001470 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1471
1472 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001473 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001474 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001475 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001476 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001477 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001478 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001479
1480 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1481 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001482 // C++ [class.mi]p3:
1483 // A class shall not be specified as a direct base class of a
1484 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001485 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001486 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001487 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001488 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001489
1490 // Delete the duplicate base class specifier; we're going to
1491 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001492 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001493
1494 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001495 } else {
1496 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001497 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001498 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001499 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1500 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1501 if (Class->isInterface() &&
1502 (!RD->isInterface() ||
1503 KnownBase->getAccessSpecifier() != AS_public)) {
1504 // The Microsoft extension __interface does not permit bases that
1505 // are not themselves public interfaces.
1506 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1507 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1508 << RD->getSourceRange();
1509 Invalid = true;
1510 }
1511 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001512 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001513 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001514 }
1515 }
1516
1517 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001518 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001519
1520 // Delete the remaining (good) base class specifiers, since their
1521 // data has been copied into the CXXRecordDecl.
1522 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001523 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001524
1525 return Invalid;
1526}
1527
1528/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1529/// class, after checking whether there are any duplicate base
1530/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001531void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001532 unsigned NumBases) {
1533 if (!ClassDecl || !Bases || !NumBases)
1534 return;
1535
1536 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001537 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001538}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001539
Douglas Gregor36d1b142009-10-06 17:59:45 +00001540/// \brief Determine whether the type \p Derived is a C++ class that is
1541/// derived from the type \p Base.
1542bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001543 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001544 return false;
John McCalle78aac42010-03-10 03:28:59 +00001545
Douglas Gregor45bb4832013-03-26 23:36:30 +00001546 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001547 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001548 return false;
1549
Douglas Gregor45bb4832013-03-26 23:36:30 +00001550 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001551 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001552 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001553
1554 // If either the base or the derived type is invalid, don't try to
1555 // check whether one is derived from the other.
1556 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1557 return false;
1558
John McCall67da35c2010-02-04 22:26:26 +00001559 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1560 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001561}
1562
1563/// \brief Determine whether the type \p Derived is a C++ class that is
1564/// derived from the type \p Base.
1565bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001566 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001567 return false;
1568
Douglas Gregor45bb4832013-03-26 23:36:30 +00001569 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001570 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001571 return false;
1572
Douglas Gregor45bb4832013-03-26 23:36:30 +00001573 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001574 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001575 return false;
1576
Douglas Gregor36d1b142009-10-06 17:59:45 +00001577 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1578}
1579
Anders Carlssona70cff62010-04-24 19:06:50 +00001580void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001581 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001582 assert(BasePathArray.empty() && "Base path array must be empty!");
1583 assert(Paths.isRecordingPaths() && "Must record paths!");
1584
1585 const CXXBasePath &Path = Paths.front();
1586
1587 // We first go backward and check if we have a virtual base.
1588 // FIXME: It would be better if CXXBasePath had the base specifier for
1589 // the nearest virtual base.
1590 unsigned Start = 0;
1591 for (unsigned I = Path.size(); I != 0; --I) {
1592 if (Path[I - 1].Base->isVirtual()) {
1593 Start = I - 1;
1594 break;
1595 }
1596 }
1597
1598 // Now add all bases.
1599 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001600 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001601}
1602
Douglas Gregor88d292c2010-05-13 16:44:06 +00001603/// \brief Determine whether the given base path includes a virtual
1604/// base class.
John McCallcf142162010-08-07 06:22:56 +00001605bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1606 for (CXXCastPath::const_iterator B = BasePath.begin(),
1607 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001608 B != BEnd; ++B)
1609 if ((*B)->isVirtual())
1610 return true;
1611
1612 return false;
1613}
1614
Douglas Gregor36d1b142009-10-06 17:59:45 +00001615/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1616/// conversion (where Derived and Base are class types) is
1617/// well-formed, meaning that the conversion is unambiguous (and
1618/// that all of the base classes are accessible). Returns true
1619/// and emits a diagnostic if the code is ill-formed, returns false
1620/// otherwise. Loc is the location where this routine should point to
1621/// if there is an error, and Range is the source range to highlight
1622/// if there is an error.
1623bool
1624Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001625 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001626 unsigned AmbigiousBaseConvID,
1627 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001628 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001629 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001630 // First, determine whether the path from Derived to Base is
1631 // ambiguous. This is slightly more expensive than checking whether
1632 // the Derived to Base conversion exists, because here we need to
1633 // explore multiple paths to determine if there is an ambiguity.
1634 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1635 /*DetectVirtual=*/false);
1636 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1637 assert(DerivationOkay &&
1638 "Can only be used with a derived-to-base conversion");
1639 (void)DerivationOkay;
1640
1641 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001642 if (InaccessibleBaseID) {
1643 // Check that the base class can be accessed.
1644 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1645 InaccessibleBaseID)) {
1646 case AR_inaccessible:
1647 return true;
1648 case AR_accessible:
1649 case AR_dependent:
1650 case AR_delayed:
1651 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001652 }
John McCall5b0829a2010-02-10 09:31:12 +00001653 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001654
1655 // Build a base path if necessary.
1656 if (BasePath)
1657 BuildBasePathArray(Paths, *BasePath);
1658 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001659 }
1660
David Majnemer626032f2013-06-22 06:43:58 +00001661 if (AmbigiousBaseConvID) {
1662 // We know that the derived-to-base conversion is ambiguous, and
1663 // we're going to produce a diagnostic. Perform the derived-to-base
1664 // search just one more time to compute all of the possible paths so
1665 // that we can print them out. This is more expensive than any of
1666 // the previous derived-to-base checks we've done, but at this point
1667 // performance isn't as much of an issue.
1668 Paths.clear();
1669 Paths.setRecordingPaths(true);
1670 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1671 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1672 (void)StillOkay;
1673
1674 // Build up a textual representation of the ambiguous paths, e.g.,
1675 // D -> B -> A, that will be used to illustrate the ambiguous
1676 // conversions in the diagnostic. We only print one of the paths
1677 // to each base class subobject.
1678 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1679
1680 Diag(Loc, AmbigiousBaseConvID)
1681 << Derived << Base << PathDisplayStr << Range << Name;
1682 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001683 return true;
1684}
1685
1686bool
1687Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001688 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001689 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001690 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001691 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001692 IgnoreAccess ? 0
1693 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001694 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001695 Loc, Range, DeclarationName(),
1696 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001697}
1698
1699
1700/// @brief Builds a string representing ambiguous paths from a
1701/// specific derived class to different subobjects of the same base
1702/// class.
1703///
1704/// This function builds a string that can be used in error messages
1705/// to show the different paths that one can take through the
1706/// inheritance hierarchy to go from the derived class to different
1707/// subobjects of a base class. The result looks something like this:
1708/// @code
1709/// struct D -> struct B -> struct A
1710/// struct D -> struct C -> struct A
1711/// @endcode
1712std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1713 std::string PathDisplayStr;
1714 std::set<unsigned> DisplayedPaths;
1715 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1716 Path != Paths.end(); ++Path) {
1717 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1718 // We haven't displayed a path to this particular base
1719 // class subobject yet.
1720 PathDisplayStr += "\n ";
1721 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1722 for (CXXBasePath::const_iterator Element = Path->begin();
1723 Element != Path->end(); ++Element)
1724 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1725 }
1726 }
1727
1728 return PathDisplayStr;
1729}
1730
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001731//===----------------------------------------------------------------------===//
1732// C++ class member Handling
1733//===----------------------------------------------------------------------===//
1734
Abramo Bagnarad7340582010-06-05 05:09:32 +00001735/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001736bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1737 SourceLocation ASLoc,
1738 SourceLocation ColonLoc,
1739 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001740 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001741 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001742 ASLoc, ColonLoc);
1743 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001744 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001745}
1746
Richard Smith18f07db2012-08-06 03:25:17 +00001747/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001748void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001749 if (D->isInvalidDecl())
1750 return;
1751
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001752 // We only care about "override" and "final" declarations.
1753 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1754 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001755
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001756 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001757
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001758 // We can't check dependent instance methods.
1759 if (MD && MD->isInstance() &&
1760 (MD->getParent()->hasAnyDependentBases() ||
1761 MD->getType()->isDependentType()))
1762 return;
1763
1764 if (MD && !MD->isVirtual()) {
1765 // If we have a non-virtual method, check if if hides a virtual method.
1766 // (In that case, it's most likely the method has the wrong type.)
1767 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1768 FindHiddenVirtualMethods(MD, OverloadedMethods);
1769
1770 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001771 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1772 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001773 diag::override_keyword_hides_virtual_member_function)
1774 << "override" << (OverloadedMethods.size() > 1);
1775 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001776 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001777 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001778 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1779 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001780 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001781 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1782 MD->setInvalidDecl();
1783 return;
1784 }
1785 // Fall through into the general case diagnostic.
1786 // FIXME: We might want to attempt typo correction here.
1787 }
1788
1789 if (!MD || !MD->isVirtual()) {
1790 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1791 Diag(OA->getLocation(),
1792 diag::override_keyword_only_allowed_on_virtual_member_functions)
1793 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1794 D->dropAttr<OverrideAttr>();
1795 }
1796 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1797 Diag(FA->getLocation(),
1798 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001799 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1800 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001801 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001802 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001803 return;
1804 }
Richard Smith18f07db2012-08-06 03:25:17 +00001805
Richard Smith18f07db2012-08-06 03:25:17 +00001806 // C++11 [class.virtual]p5:
1807 // If a virtual function is marked with the virt-specifier override and
1808 // does not override a member function of a base class, the program is
1809 // ill-formed.
1810 bool HasOverriddenMethods =
1811 MD->begin_overridden_methods() != MD->end_overridden_methods();
1812 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1813 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1814 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001815}
1816
Richard Smith18f07db2012-08-06 03:25:17 +00001817/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001818/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001819/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001820bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1821 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001822 FinalAttr *FA = Old->getAttr<FinalAttr>();
1823 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001824 return false;
1825
1826 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001827 << New->getDeclName()
1828 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001829 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1830 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001831}
1832
Daniel Jasper0baec5492012-06-06 08:32:04 +00001833static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001834 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1835 // FIXME: Destruction of ObjC lifetime types has side-effects.
1836 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1837 return !RD->isCompleteDefinition() ||
1838 !RD->hasTrivialDefaultConstructor() ||
1839 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001840 return false;
1841}
1842
John McCall5e77d762013-04-16 07:28:30 +00001843static AttributeList *getMSPropertyAttr(AttributeList *list) {
1844 for (AttributeList* it = list; it != 0; it = it->getNext())
1845 if (it->isDeclspecPropertyAttribute())
1846 return it;
1847 return 0;
1848}
1849
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001850/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1851/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001852/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001853/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1854/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001855NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001856Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001857 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001858 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001859 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001860 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001861 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1862 DeclarationName Name = NameInfo.getName();
1863 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001864
1865 // For anonymous bitfields, the location should point to the type.
1866 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001867 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001868
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001869 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001870
John McCallb1cd7da2010-06-04 08:34:12 +00001871 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001872 assert(!DS.isFriendSpecified());
1873
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001874 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001875
John McCalldb632ac2012-09-25 07:32:39 +00001876 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1877 // The Microsoft extension __interface only permits public member functions
1878 // and prohibits constructors, destructors, operators, non-public member
1879 // functions, static methods and data members.
1880 unsigned InvalidDecl;
1881 bool ShowDeclName = true;
1882 if (!isFunc)
1883 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1884 else if (AS != AS_public)
1885 InvalidDecl = 2;
1886 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1887 InvalidDecl = 3;
1888 else switch (Name.getNameKind()) {
1889 case DeclarationName::CXXConstructorName:
1890 InvalidDecl = 4;
1891 ShowDeclName = false;
1892 break;
1893
1894 case DeclarationName::CXXDestructorName:
1895 InvalidDecl = 5;
1896 ShowDeclName = false;
1897 break;
1898
1899 case DeclarationName::CXXOperatorName:
1900 case DeclarationName::CXXConversionFunctionName:
1901 InvalidDecl = 6;
1902 break;
1903
1904 default:
1905 InvalidDecl = 0;
1906 break;
1907 }
1908
1909 if (InvalidDecl) {
1910 if (ShowDeclName)
1911 Diag(Loc, diag::err_invalid_member_in_interface)
1912 << (InvalidDecl-1) << Name;
1913 else
1914 Diag(Loc, diag::err_invalid_member_in_interface)
1915 << (InvalidDecl-1) << "";
1916 return 0;
1917 }
1918 }
1919
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001920 // C++ 9.2p6: A member shall not be declared to have automatic storage
1921 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001922 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1923 // data members and cannot be applied to names declared const or static,
1924 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001925 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001926 case DeclSpec::SCS_unspecified:
1927 case DeclSpec::SCS_typedef:
1928 case DeclSpec::SCS_static:
1929 break;
1930 case DeclSpec::SCS_mutable:
1931 if (isFunc) {
1932 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001933
Richard Smithb4a9e862013-04-12 22:46:28 +00001934 // FIXME: It would be nicer if the keyword was ignored only for this
1935 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001936 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001937 }
1938 break;
1939 default:
1940 Diag(DS.getStorageClassSpecLoc(),
1941 diag::err_storageclass_invalid_for_member);
1942 D.getMutableDeclSpec().ClearStorageClassSpecs();
1943 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001944 }
1945
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001946 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1947 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001948 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001949
David Blaikie35506f82013-01-30 01:22:18 +00001950 if (DS.isConstexprSpecified() && isInstField) {
1951 SemaDiagnosticBuilder B =
1952 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1953 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1954 if (InitStyle == ICIS_NoInit) {
1955 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1956 D.getMutableDeclSpec().ClearConstexprSpec();
1957 const char *PrevSpec;
1958 unsigned DiagID;
1959 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1960 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001961 (void)Failed;
David Blaikie35506f82013-01-30 01:22:18 +00001962 assert(!Failed && "Making a constexpr member const shouldn't fail");
1963 } else {
1964 B << 1;
1965 const char *PrevSpec;
1966 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001967 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001968 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1969 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001970 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001971 "This is the only DeclSpec that should fail to be applied");
1972 B << 1;
1973 } else {
1974 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1975 isInstField = false;
1976 }
1977 }
1978 }
1979
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001980 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001981 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001982 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001983
1984 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00001985 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001986 Diag(Loc, diag::err_bad_variable_name)
1987 << Name;
1988 return 0;
1989 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001990
Benjamin Kramer365082d2012-05-19 16:34:46 +00001991 IdentifierInfo *II = Name.getAsIdentifierInfo();
1992
Douglas Gregor7c26c042011-09-21 14:40:46 +00001993 // Member field could not be with "template" keyword.
1994 // So TemplateParameterLists should be empty in this case.
1995 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001996 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00001997 if (TemplateParams->size()) {
1998 // There is no such thing as a member field template.
1999 Diag(D.getIdentifierLoc(), diag::err_template_member)
2000 << II
2001 << SourceRange(TemplateParams->getTemplateLoc(),
2002 TemplateParams->getRAngleLoc());
2003 } else {
2004 // There is an extraneous 'template<>' for this member.
2005 Diag(TemplateParams->getTemplateLoc(),
2006 diag::err_template_member_noparams)
2007 << II
2008 << SourceRange(TemplateParams->getTemplateLoc(),
2009 TemplateParams->getRAngleLoc());
2010 }
2011 return 0;
2012 }
2013
Douglas Gregora007d362010-10-13 22:19:53 +00002014 if (SS.isSet() && !SS.isInvalid()) {
2015 // The user provided a superfluous scope specifier inside a class
2016 // definition:
2017 //
2018 // class X {
2019 // int X::member;
2020 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002021 if (DeclContext *DC = computeDeclContext(SS, false))
2022 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002023 else
2024 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2025 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002026
Douglas Gregora007d362010-10-13 22:19:53 +00002027 SS.clear();
2028 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002029
John McCall5e77d762013-04-16 07:28:30 +00002030 AttributeList *MSPropertyAttr =
2031 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002032 if (MSPropertyAttr) {
2033 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2034 BitWidth, InitStyle, AS, MSPropertyAttr);
2035 if (!Member)
2036 return 0;
2037 isInstField = false;
2038 } else {
2039 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2040 BitWidth, InitStyle, AS);
2041 assert(Member && "HandleField never returns null");
2042 }
2043 } else {
2044 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2045
2046 Member = HandleDeclarator(S, D, TemplateParameterLists);
2047 if (!Member)
2048 return 0;
2049
2050 // Non-instance-fields can't have a bitfield.
2051 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002052 if (Member->isInvalidDecl()) {
2053 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002054 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002055 // C++ 9.6p3: A bit-field shall not be a static member.
2056 // "static member 'A' cannot be a bit-field"
2057 Diag(Loc, diag::err_static_not_bitfield)
2058 << Name << BitWidth->getSourceRange();
2059 } else if (isa<TypedefDecl>(Member)) {
2060 // "typedef member 'x' cannot be a bit-field"
2061 Diag(Loc, diag::err_typedef_not_bitfield)
2062 << Name << BitWidth->getSourceRange();
2063 } else {
2064 // A function typedef ("typedef int f(); f a;").
2065 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2066 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002067 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002068 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002069 }
Mike Stump11289f42009-09-09 15:08:12 +00002070
Chris Lattnerd26760a2009-03-05 23:01:03 +00002071 BitWidth = 0;
2072 Member->setInvalidDecl();
2073 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002074
2075 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002076
Larisse Voufo39a1e502013-08-06 01:03:05 +00002077 // If we have declared a member function template or static data member
2078 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002079 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2080 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002081 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2082 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002083 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002084
Richard Smith18f07db2012-08-06 03:25:17 +00002085 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002086 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002087 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002088 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2089 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002090
Douglas Gregorf2f08062011-03-08 17:10:18 +00002091 if (VS.getLastLocation().isValid()) {
2092 // Update the end location of a method that has a virt-specifiers.
2093 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2094 MD->setRangeEnd(VS.getLastLocation());
2095 }
Richard Smith18f07db2012-08-06 03:25:17 +00002096
Anders Carlssonc87f8612011-01-20 06:29:02 +00002097 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002098
Douglas Gregor92751d42008-11-17 22:58:34 +00002099 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002100
Daniel Jasper0baec5492012-06-06 08:32:04 +00002101 if (isInstField) {
2102 FieldDecl *FD = cast<FieldDecl>(Member);
2103 FieldCollector->Add(FD);
2104
2105 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2106 FD->getLocation())
2107 != DiagnosticsEngine::Ignored) {
2108 // Remember all explicit private FieldDecls that have a name, no side
2109 // effects and are not part of a dependent type declaration.
2110 if (!FD->isImplicit() && FD->getDeclName() &&
2111 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002112 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002113 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002114 !InitializationHasSideEffects(*FD))
2115 UnusedPrivateFields.insert(FD);
2116 }
2117 }
2118
John McCall48871652010-08-21 09:40:31 +00002119 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002120}
2121
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002122namespace {
2123 class UninitializedFieldVisitor
2124 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2125 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002126 // List of Decls to generate a warning on. Also remove Decls that become
2127 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002128 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002129 // If non-null, add a note to the warning pointing back to the constructor.
2130 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002131 public:
2132 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002133 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002134 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002135 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002136 : Inherited(S.Context), S(S), Decls(Decls),
2137 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002138
Richard Trieufd687772013-09-16 20:46:50 +00002139 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002140 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2141 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002142
Richard Trieu1bc22c12013-09-13 03:20:53 +00002143 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2144 // or union.
2145 MemberExpr *FieldME = ME;
2146
2147 Expr *Base = ME;
2148 while (isa<MemberExpr>(Base)) {
2149 ME = cast<MemberExpr>(Base);
2150
2151 if (isa<VarDecl>(ME->getMemberDecl()))
2152 return;
2153
2154 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2155 if (!FD->isAnonymousStructOrUnion())
2156 FieldME = ME;
2157
2158 Base = ME->getBase();
2159 }
2160
Richard Trieufd687772013-09-16 20:46:50 +00002161 if (!isa<CXXThisExpr>(Base))
2162 return;
2163
Richard Trieu406e65c2013-09-20 03:03:06 +00002164 ValueDecl* FoundVD = FieldME->getMemberDecl();
2165
Richard Trieuef64e942013-10-25 00:56:00 +00002166 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002167 return;
2168
Richard Trieuef64e942013-10-25 00:56:00 +00002169 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002170
Richard Trieuef64e942013-10-25 00:56:00 +00002171 // Prevent double warnings on use of unbounded references.
2172 if (IsReference != CheckReferenceOnly)
2173 return;
2174
2175 unsigned diag = IsReference
2176 ? diag::warn_reference_field_is_uninit
2177 : diag::warn_field_is_uninit;
2178 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2179 if (Constructor)
2180 S.Diag(Constructor->getLocation(),
2181 diag::note_uninit_in_this_constructor)
2182 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2183
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002184 }
2185
2186 void HandleValue(Expr *E) {
2187 E = E->IgnoreParens();
2188
2189 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002190 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002191 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002192 }
2193
2194 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2195 HandleValue(CO->getTrueExpr());
2196 HandleValue(CO->getFalseExpr());
2197 return;
2198 }
2199
2200 if (BinaryConditionalOperator *BCO =
2201 dyn_cast<BinaryConditionalOperator>(E)) {
2202 HandleValue(BCO->getCommon());
2203 HandleValue(BCO->getFalseExpr());
2204 return;
2205 }
2206
2207 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2208 switch (BO->getOpcode()) {
2209 default:
2210 return;
2211 case(BO_PtrMemD):
2212 case(BO_PtrMemI):
2213 HandleValue(BO->getLHS());
2214 return;
2215 case(BO_Comma):
2216 HandleValue(BO->getRHS());
2217 return;
2218 }
2219 }
2220 }
2221
Richard Trieu1bc22c12013-09-13 03:20:53 +00002222 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002223 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002224 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002225
2226 Inherited::VisitMemberExpr(ME);
2227 }
2228
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002229 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2230 if (E->getCastKind() == CK_LValueToRValue)
2231 HandleValue(E->getSubExpr());
2232
2233 Inherited::VisitImplicitCastExpr(E);
2234 }
2235
Richard Trieu1bc22c12013-09-13 03:20:53 +00002236 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002237 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002238 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2239 if (ICE->getCastKind() == CK_NoOp)
2240 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002241 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002242
2243 Inherited::VisitCXXConstructExpr(E);
2244 }
2245
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002246 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2247 Expr *Callee = E->getCallee();
2248 if (isa<MemberExpr>(Callee))
2249 HandleValue(Callee);
2250
2251 Inherited::VisitCXXMemberCallExpr(E);
2252 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002253
2254 void VisitBinaryOperator(BinaryOperator *E) {
2255 // If a field assignment is detected, remove the field from the
2256 // uninitiailized field set.
2257 if (E->getOpcode() == BO_Assign)
2258 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2259 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002260 if (!FD->getType()->isReferenceType())
2261 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002262
2263 Inherited::VisitBinaryOperator(E);
2264 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002265 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002266 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002267 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2268 const CXXConstructorDecl *Constructor) {
2269 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002270 return;
2271
Richard Trieuef64e942013-10-25 00:56:00 +00002272 if (!E)
2273 return;
2274
2275 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2276 E = Default->getExpr();
2277 if (!E)
2278 return;
2279 // In class initializers will point to the constructor.
2280 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2281 } else {
2282 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2283 }
2284 }
2285
2286 // Diagnose value-uses of fields to initialize themselves, e.g.
2287 // foo(foo)
2288 // where foo is not also a parameter to the constructor.
2289 // Also diagnose across field uninitialized use such as
2290 // x(y), y(x)
2291 // TODO: implement -Wuninitialized and fold this into that framework.
2292 static void DiagnoseUninitializedFields(
2293 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2294
2295 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2296 Constructor->getLocation())
2297 == DiagnosticsEngine::Ignored) {
2298 return;
2299 }
2300
2301 if (Constructor->isInvalidDecl())
2302 return;
2303
2304 const CXXRecordDecl *RD = Constructor->getParent();
2305
2306 // Holds fields that are uninitialized.
2307 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2308
2309 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002310 for (auto *I : RD->decls()) {
2311 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002312 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002313 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002314 UninitializedFields.insert(IFD->getAnonField());
2315 }
2316 }
2317
Aaron Ballman0ad78302014-03-13 17:34:31 +00002318 for (const auto *FieldInit : Constructor->inits()) {
2319 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002320
2321 CheckInitExprContainsUninitializedFields(
2322 SemaRef, InitExpr, UninitializedFields, Constructor);
2323
Aaron Ballman0ad78302014-03-13 17:34:31 +00002324 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002325 UninitializedFields.erase(Field);
2326 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002327 }
2328} // namespace
2329
Richard Smith74108172014-01-17 03:11:34 +00002330/// \brief Enter a new C++ default initializer scope. After calling this, the
2331/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2332/// parsing or instantiating the initializer failed.
2333void Sema::ActOnStartCXXInClassMemberInitializer() {
2334 // Create a synthetic function scope to represent the call to the constructor
2335 // that notionally surrounds a use of this initializer.
2336 PushFunctionScope();
2337}
2338
2339/// \brief This is invoked after parsing an in-class initializer for a
2340/// non-static C++ class member, and after instantiating an in-class initializer
2341/// in a class template. Such actions are deferred until the class is complete.
2342void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2343 SourceLocation InitLoc,
2344 Expr *InitExpr) {
2345 // Pop the notional constructor scope we created earlier.
2346 PopFunctionScopeInfo(0, D);
2347
Richard Smith938f40b2011-06-11 17:19:42 +00002348 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002349 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2350 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002351
2352 if (!InitExpr) {
2353 FD->setInvalidDecl();
2354 FD->removeInClassInitializer();
2355 return;
2356 }
2357
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002358 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2359 FD->setInvalidDecl();
2360 FD->removeInClassInitializer();
2361 return;
2362 }
2363
Richard Smith938f40b2011-06-11 17:19:42 +00002364 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002365 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002366 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002367 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002368 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002369 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002370 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2371 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002372 if (Init.isInvalid()) {
2373 FD->setInvalidDecl();
2374 return;
2375 }
Richard Smith938f40b2011-06-11 17:19:42 +00002376 }
2377
Richard Smith945f8d32013-01-14 22:39:08 +00002378 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002379 // The initialization of each base and member constitutes a
2380 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002381 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002382 if (Init.isInvalid()) {
2383 FD->setInvalidDecl();
2384 return;
2385 }
2386
2387 InitExpr = Init.release();
2388
2389 FD->setInClassInitializer(InitExpr);
2390}
2391
Douglas Gregor15e77a22009-12-31 09:10:24 +00002392/// \brief Find the direct and/or virtual base specifiers that
2393/// correspond to the given base type, for use in base initialization
2394/// within a constructor.
2395static bool FindBaseInitializer(Sema &SemaRef,
2396 CXXRecordDecl *ClassDecl,
2397 QualType BaseType,
2398 const CXXBaseSpecifier *&DirectBaseSpec,
2399 const CXXBaseSpecifier *&VirtualBaseSpec) {
2400 // First, check for a direct base class.
2401 DirectBaseSpec = 0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002402 for (const auto &Base : ClassDecl->bases()) {
2403 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002404 // We found a direct base of this type. That's what we're
2405 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002406 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002407 break;
2408 }
2409 }
2410
2411 // Check for a virtual base class.
2412 // FIXME: We might be able to short-circuit this if we know in advance that
2413 // there are no virtual bases.
2414 VirtualBaseSpec = 0;
2415 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2416 // We haven't found a base yet; search the class hierarchy for a
2417 // virtual base class.
2418 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2419 /*DetectVirtual=*/false);
2420 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2421 BaseType, Paths)) {
2422 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2423 Path != Paths.end(); ++Path) {
2424 if (Path->back().Base->isVirtual()) {
2425 VirtualBaseSpec = Path->back().Base;
2426 break;
2427 }
2428 }
2429 }
2430 }
2431
2432 return DirectBaseSpec || VirtualBaseSpec;
2433}
2434
Sebastian Redla74948d2011-09-24 17:48:25 +00002435/// \brief Handle a C++ member initializer using braced-init-list syntax.
2436MemInitResult
2437Sema::ActOnMemInitializer(Decl *ConstructorD,
2438 Scope *S,
2439 CXXScopeSpec &SS,
2440 IdentifierInfo *MemberOrBase,
2441 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002442 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002443 SourceLocation IdLoc,
2444 Expr *InitList,
2445 SourceLocation EllipsisLoc) {
2446 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002447 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002448 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002449}
2450
2451/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002452MemInitResult
John McCall48871652010-08-21 09:40:31 +00002453Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002454 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002455 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002456 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002457 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002458 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002459 SourceLocation IdLoc,
2460 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002461 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002462 SourceLocation RParenLoc,
2463 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002464 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002465 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002466 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002467 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002468}
2469
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002470namespace {
2471
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002472// Callback to only accept typo corrections that can be a valid C++ member
2473// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002474class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002475public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002476 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2477 : ClassDecl(ClassDecl) {}
2478
Craig Toppera798a9d2014-03-02 09:32:10 +00002479 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002480 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2481 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2482 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002483 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002484 }
2485 return false;
2486 }
2487
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002488private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002489 CXXRecordDecl *ClassDecl;
2490};
2491
2492}
2493
Sebastian Redla74948d2011-09-24 17:48:25 +00002494/// \brief Handle a C++ member initializer.
2495MemInitResult
2496Sema::BuildMemInitializer(Decl *ConstructorD,
2497 Scope *S,
2498 CXXScopeSpec &SS,
2499 IdentifierInfo *MemberOrBase,
2500 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002501 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002502 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002503 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002504 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002505 if (!ConstructorD)
2506 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002507
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002508 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002509
2510 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002511 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002512 if (!Constructor) {
2513 // The user wrote a constructor initializer on a function that is
2514 // not a C++ constructor. Ignore the error for now, because we may
2515 // have more member initializers coming; we'll diagnose it just
2516 // once in ActOnMemInitializers.
2517 return true;
2518 }
2519
2520 CXXRecordDecl *ClassDecl = Constructor->getParent();
2521
2522 // C++ [class.base.init]p2:
2523 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002524 // constructor's class and, if not found in that scope, are looked
2525 // up in the scope containing the constructor's definition.
2526 // [Note: if the constructor's class contains a member with the
2527 // same name as a direct or virtual base class of the class, a
2528 // mem-initializer-id naming the member or base class and composed
2529 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002530 // mem-initializer-id for the hidden base class may be specified
2531 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002532 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002533 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002534 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002535 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002536 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002537 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002538 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2539 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002540 if (EllipsisLoc.isValid())
2541 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002542 << MemberOrBase
2543 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002544
Sebastian Redla9351792012-02-11 23:51:47 +00002545 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002546 }
Francois Pichetd583da02010-12-04 09:14:42 +00002547 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002548 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002549 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002550 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002551 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002552
2553 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002554 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002555 } else if (DS.getTypeSpecType() == TST_decltype) {
2556 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002557 } else {
2558 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2559 LookupParsedName(R, S, &SS);
2560
2561 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2562 if (!TyD) {
2563 if (R.isAmbiguous()) return true;
2564
John McCallda6841b2010-04-09 19:01:14 +00002565 // We don't want access-control diagnostics here.
2566 R.suppressDiagnostics();
2567
Douglas Gregora3b624a2010-01-19 06:46:48 +00002568 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2569 bool NotUnknownSpecialization = false;
2570 DeclContext *DC = computeDeclContext(SS, false);
2571 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2572 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2573
2574 if (!NotUnknownSpecialization) {
2575 // When the scope specifier can refer to a member of an unknown
2576 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002577 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2578 SS.getWithLocInContext(Context),
2579 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002580 if (BaseType.isNull())
2581 return true;
2582
Douglas Gregora3b624a2010-01-19 06:46:48 +00002583 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002584 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002585 }
2586 }
2587
Douglas Gregor15e77a22009-12-31 09:10:24 +00002588 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002589 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002590 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002591 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002592 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00002593 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002594 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002595 // We have found a non-static data member with a similar
2596 // name to what was typed; complain and initialize that
2597 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002598 diagnoseTypo(Corr,
2599 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2600 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002601 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002602 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002603 const CXXBaseSpecifier *DirectBaseSpec;
2604 const CXXBaseSpecifier *VirtualBaseSpec;
2605 if (FindBaseInitializer(*this, ClassDecl,
2606 Context.getTypeDeclType(Type),
2607 DirectBaseSpec, VirtualBaseSpec)) {
2608 // We have found a direct or virtual base class with a
2609 // similar name to what was typed; complain and initialize
2610 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002611 diagnoseTypo(Corr,
2612 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2613 << MemberOrBase << false,
2614 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002615
Richard Smithf9b15102013-08-17 00:46:16 +00002616 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2617 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002618 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002619 diag::note_base_class_specified_here)
2620 << BaseSpec->getType()
2621 << BaseSpec->getSourceRange();
2622
Douglas Gregor15e77a22009-12-31 09:10:24 +00002623 TyD = Type;
2624 }
2625 }
2626 }
2627
Douglas Gregora3b624a2010-01-19 06:46:48 +00002628 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002629 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002630 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002631 return true;
2632 }
John McCallb5a0d312009-12-21 10:41:20 +00002633 }
2634
Douglas Gregora3b624a2010-01-19 06:46:48 +00002635 if (BaseType.isNull()) {
2636 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002637 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002638 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002639 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2640 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002641 }
2642 }
Mike Stump11289f42009-09-09 15:08:12 +00002643
John McCallbcd03502009-12-07 02:54:59 +00002644 if (!TInfo)
2645 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002646
Sebastian Redla9351792012-02-11 23:51:47 +00002647 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002648}
2649
Chandler Carruth599deef2011-09-03 01:14:15 +00002650/// Checks a member initializer expression for cases where reference (or
2651/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002652static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2653 Expr *Init,
2654 SourceLocation IdLoc) {
2655 QualType MemberTy = Member->getType();
2656
2657 // We only handle pointers and references currently.
2658 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2659 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2660 return;
2661
2662 const bool IsPointer = MemberTy->isPointerType();
2663 if (IsPointer) {
2664 if (const UnaryOperator *Op
2665 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2666 // The only case we're worried about with pointers requires taking the
2667 // address.
2668 if (Op->getOpcode() != UO_AddrOf)
2669 return;
2670
2671 Init = Op->getSubExpr();
2672 } else {
2673 // We only handle address-of expression initializers for pointers.
2674 return;
2675 }
2676 }
2677
Richard Smithe3b28bc2013-06-12 21:51:50 +00002678 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002679 // We only warn when referring to a non-reference parameter declaration.
2680 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2681 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002682 return;
2683
2684 S.Diag(Init->getExprLoc(),
2685 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2686 : diag::warn_bind_ref_member_to_parameter)
2687 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002688 } else {
2689 // Other initializers are fine.
2690 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002691 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002692
2693 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2694 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002695}
2696
John McCallfaf5fb42010-08-26 23:41:50 +00002697MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002698Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002699 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002700 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2701 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2702 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002703 "Member must be a FieldDecl or IndirectFieldDecl");
2704
Sebastian Redla9351792012-02-11 23:51:47 +00002705 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002706 return true;
2707
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002708 if (Member->isInvalidDecl())
2709 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002710
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002711 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002712 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002713 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002714 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002715 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002716 } else {
2717 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002718 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002719 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002720
Sebastian Redla9351792012-02-11 23:51:47 +00002721 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002722
Sebastian Redla9351792012-02-11 23:51:47 +00002723 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002724 // Can't check initialization for a member of dependent type or when
2725 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002726 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002727 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002728 bool InitList = false;
2729 if (isa<InitListExpr>(Init)) {
2730 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002731 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002732 }
2733
Chandler Carruthd44c3102010-12-06 09:23:57 +00002734 // Initialize the member.
2735 InitializedEntity MemberEntity =
2736 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2737 : InitializedEntity::InitializeMember(IndirectMember, 0);
2738 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002739 InitList ? InitializationKind::CreateDirectList(IdLoc)
2740 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2741 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002742
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002743 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2744 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002745 if (MemberInit.isInvalid())
2746 return true;
2747
Richard Smith736a9472013-06-12 20:42:33 +00002748 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2749
Richard Smith945f8d32013-01-14 22:39:08 +00002750 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002751 // The initialization of each base and member constitutes a
2752 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002753 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002754 if (MemberInit.isInvalid())
2755 return true;
2756
Richard Smithd59b8322012-12-19 01:39:02 +00002757 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002758 }
2759
Chandler Carruthd44c3102010-12-06 09:23:57 +00002760 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002761 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2762 InitRange.getBegin(), Init,
2763 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002764 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002765 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2766 InitRange.getBegin(), Init,
2767 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002768 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002769}
2770
John McCallfaf5fb42010-08-26 23:41:50 +00002771MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002772Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002773 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002774 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002775 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002776 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002777 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002778 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002779
Sebastian Redl0501c632012-02-12 16:37:36 +00002780 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002781 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002782 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2783 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002784 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002785 }
2786
Sebastian Redla9351792012-02-11 23:51:47 +00002787 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002788 // Initialize the object.
2789 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2790 QualType(ClassDecl->getTypeForDecl(), 0));
2791 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002792 InitList ? InitializationKind::CreateDirectList(NameLoc)
2793 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2794 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002795 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002796 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002797 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002798 if (DelegationInit.isInvalid())
2799 return true;
2800
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002801 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2802 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002803
Richard Smith945f8d32013-01-14 22:39:08 +00002804 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002805 // The initialization of each base and member constitutes a
2806 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002807 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2808 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002809 if (DelegationInit.isInvalid())
2810 return true;
2811
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002812 // If we are in a dependent context, template instantiation will
2813 // perform this type-checking again. Just save the arguments that we
2814 // received in a ParenListExpr.
2815 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2816 // of the information that we have about the base
2817 // initializer. However, deconstructing the ASTs is a dicey process,
2818 // and this approach is far more likely to get the corner cases right.
2819 if (CurContext->isDependentContext())
2820 DelegationInit = Owned(Init);
2821
Sebastian Redla9351792012-02-11 23:51:47 +00002822 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002823 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002824 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002825}
2826
2827MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002828Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002829 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002830 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002831 SourceLocation BaseLoc
2832 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002833
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002834 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2835 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2836 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2837
2838 // C++ [class.base.init]p2:
2839 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002840 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002841 // of that class, the mem-initializer is ill-formed. A
2842 // mem-initializer-list can initialize a base class using any
2843 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002844 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002845
Sebastian Redla9351792012-02-11 23:51:47 +00002846 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002847 if (EllipsisLoc.isValid()) {
2848 // This is a pack expansion.
2849 if (!BaseType->containsUnexpandedParameterPack()) {
2850 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002851 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002852
Douglas Gregor44e7df62011-01-04 00:32:56 +00002853 EllipsisLoc = SourceLocation();
2854 }
2855 } else {
2856 // Check for any unexpanded parameter packs.
2857 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2858 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002859
Sebastian Redla9351792012-02-11 23:51:47 +00002860 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002861 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002862 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002863
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002864 // Check for direct and virtual base classes.
2865 const CXXBaseSpecifier *DirectBaseSpec = 0;
2866 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2867 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002868 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2869 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002870 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002871
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002872 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2873 VirtualBaseSpec);
2874
2875 // C++ [base.class.init]p2:
2876 // Unless the mem-initializer-id names a nonstatic data member of the
2877 // constructor's class or a direct or virtual base of that class, the
2878 // mem-initializer is ill-formed.
2879 if (!DirectBaseSpec && !VirtualBaseSpec) {
2880 // If the class has any dependent bases, then it's possible that
2881 // one of those types will resolve to the same type as
2882 // BaseType. Therefore, just treat this as a dependent base
2883 // class initialization. FIXME: Should we try to check the
2884 // initialization anyway? It seems odd.
2885 if (ClassDecl->hasAnyDependentBases())
2886 Dependent = true;
2887 else
2888 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2889 << BaseType << Context.getTypeDeclType(ClassDecl)
2890 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2891 }
2892 }
2893
2894 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002895 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002896
Sebastian Redla74948d2011-09-24 17:48:25 +00002897 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2898 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002899 InitRange.getBegin(), Init,
2900 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002901 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002902
2903 // C++ [base.class.init]p2:
2904 // If a mem-initializer-id is ambiguous because it designates both
2905 // a direct non-virtual base class and an inherited virtual base
2906 // class, the mem-initializer is ill-formed.
2907 if (DirectBaseSpec && VirtualBaseSpec)
2908 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002909 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002910
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002911 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002912 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002913 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002914
2915 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002916 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002917 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002918 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002919 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002920 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002921 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002922
2923 InitializedEntity BaseEntity =
2924 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2925 InitializationKind Kind =
2926 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2927 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2928 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002929 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2930 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002931 if (BaseInit.isInvalid())
2932 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002933
Richard Smith945f8d32013-01-14 22:39:08 +00002934 // C++11 [class.base.init]p7:
2935 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002936 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002937 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002938 if (BaseInit.isInvalid())
2939 return true;
2940
2941 // If we are in a dependent context, template instantiation will
2942 // perform this type-checking again. Just save the arguments that we
2943 // received in a ParenListExpr.
2944 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2945 // of the information that we have about the base
2946 // initializer. However, deconstructing the ASTs is a dicey process,
2947 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002948 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002949 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002950
Alexis Hunt1d792652011-01-08 20:30:50 +00002951 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002952 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002953 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002954 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002955 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002956}
2957
Sebastian Redl22653ba2011-08-30 19:58:05 +00002958// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002959static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2960 if (T.isNull()) T = E->getType();
2961 QualType TargetType = SemaRef.BuildReferenceType(
2962 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002963 SourceLocation ExprLoc = E->getLocStart();
2964 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2965 TargetType, ExprLoc);
2966
2967 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2968 SourceRange(ExprLoc, ExprLoc),
2969 E->getSourceRange()).take();
2970}
2971
Anders Carlsson1b00e242010-04-23 03:10:23 +00002972/// ImplicitInitializerKind - How an implicit base or member initializer should
2973/// initialize its base or member.
2974enum ImplicitInitializerKind {
2975 IIK_Default,
2976 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002977 IIK_Move,
2978 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002979};
2980
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002981static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002982BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002983 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002984 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002985 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002986 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002987 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002988 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2989 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002990
John McCalldadc5752010-08-24 06:29:42 +00002991 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002992
2993 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00002994 case IIK_Inherit: {
2995 const CXXRecordDecl *Inherited =
2996 Constructor->getInheritedConstructor()->getParent();
2997 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2998 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2999 // C++11 [class.inhctor]p8:
3000 // Each expression in the expression-list is of the form
3001 // static_cast<T&&>(p), where p is the name of the corresponding
3002 // constructor parameter and T is the declared type of p.
3003 SmallVector<Expr*, 16> Args;
3004 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3005 ParmVarDecl *PD = Constructor->getParamDecl(I);
3006 ExprResult ArgExpr =
3007 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3008 VK_LValue, SourceLocation());
3009 if (ArgExpr.isInvalid())
3010 return true;
3011 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3012 }
3013
3014 InitializationKind InitKind = InitializationKind::CreateDirect(
3015 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003016 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003017 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3018 break;
3019 }
3020 }
3021 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003022 case IIK_Default: {
3023 InitializationKind InitKind
3024 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003025 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3026 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003027 break;
3028 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003029
Sebastian Redl22653ba2011-08-30 19:58:05 +00003030 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003031 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003032 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003033 ParmVarDecl *Param = Constructor->getParamDecl(0);
3034 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003035
Anders Carlsson1b00e242010-04-23 03:10:23 +00003036 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003037 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003038 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003039 Constructor->getLocation(), ParamType,
3040 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003041
Eli Friedmanfa0df832012-02-02 03:46:19 +00003042 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3043
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003044 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003045 QualType ArgTy =
3046 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3047 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003048
Sebastian Redl22653ba2011-08-30 19:58:05 +00003049 if (Moving) {
3050 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3051 }
3052
John McCallcf142162010-08-07 06:22:56 +00003053 CXXCastPath BasePath;
3054 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003055 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3056 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003057 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003058 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003059
Anders Carlsson1b00e242010-04-23 03:10:23 +00003060 InitializationKind InitKind
3061 = InitializationKind::CreateDirect(Constructor->getLocation(),
3062 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003063 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3064 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003065 break;
3066 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003067 }
John McCallb268a282010-08-23 23:25:46 +00003068
Douglas Gregora40433a2010-12-07 00:41:46 +00003069 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003070 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003071 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003072
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003073 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003074 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003075 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3076 SourceLocation()),
3077 BaseSpec->isVirtual(),
3078 SourceLocation(),
3079 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003080 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003081 SourceLocation());
3082
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003083 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003084}
3085
Sebastian Redl22653ba2011-08-30 19:58:05 +00003086static bool RefersToRValueRef(Expr *MemRef) {
3087 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3088 return Referenced->getType()->isRValueReferenceType();
3089}
3090
Anders Carlsson3c1db572010-04-23 02:15:47 +00003091static bool
3092BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003093 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003094 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003095 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003096 if (Field->isInvalidDecl())
3097 return true;
3098
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003099 SourceLocation Loc = Constructor->getLocation();
3100
Sebastian Redl22653ba2011-08-30 19:58:05 +00003101 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3102 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003103 ParmVarDecl *Param = Constructor->getParamDecl(0);
3104 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003105
3106 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003107 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3108 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003109
Anders Carlsson423f5d82010-04-23 16:04:08 +00003110 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003111 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003112 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003113 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003114
Eli Friedmanfa0df832012-02-02 03:46:19 +00003115 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3116
Sebastian Redl22653ba2011-08-30 19:58:05 +00003117 if (Moving) {
3118 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3119 }
3120
Douglas Gregor94f9a482010-05-05 05:51:00 +00003121 // Build a reference to this field within the parameter.
3122 CXXScopeSpec SS;
3123 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3124 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003125 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3126 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003127 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003128 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003129 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003130 ParamType, Loc,
3131 /*IsArrow=*/false,
3132 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003133 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00003134 /*FirstQualifierInScope=*/0,
3135 MemberLookup,
3136 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003137 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003138 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003139
3140 // C++11 [class.copy]p15:
3141 // - if a member m has rvalue reference type T&&, it is direct-initialized
3142 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003143 if (RefersToRValueRef(CtorArg.get())) {
3144 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003145 }
3146
Douglas Gregor94f9a482010-05-05 05:51:00 +00003147 // When the field we are copying is an array, create index variables for
3148 // each dimension of the array. We use these index variables to subscript
3149 // the source array, and other clients (e.g., CodeGen) will perform the
3150 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003151 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003152 QualType BaseType = Field->getType();
3153 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003154 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003155 while (const ConstantArrayType *Array
3156 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003157 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003158 // Create the iteration variable for this array index.
3159 IdentifierInfo *IterationVarName = 0;
3160 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003161 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003162 llvm::raw_svector_ostream OS(Str);
3163 OS << "__i" << IndexVariables.size();
3164 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3165 }
3166 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003167 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003168 IterationVarName, SizeType,
3169 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003170 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003171 IndexVariables.push_back(IterationVar);
3172
3173 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003174 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003175 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003176 assert(!IterationVarRef.isInvalid() &&
3177 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003178 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3179 assert(!IterationVarRef.isInvalid() &&
3180 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003181
Douglas Gregor94f9a482010-05-05 05:51:00 +00003182 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003183 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003184 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003185 Loc);
3186 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003187 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003188
Douglas Gregor94f9a482010-05-05 05:51:00 +00003189 BaseType = Array->getElementType();
3190 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003191
3192 // The array subscript expression is an lvalue, which is wrong for moving.
3193 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003194 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003195
Douglas Gregor94f9a482010-05-05 05:51:00 +00003196 // Construct the entity that we will be initializing. For an array, this
3197 // will be first element in the array, which may require several levels
3198 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003199 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003200 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003201 if (Indirect)
3202 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3203 else
3204 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003205 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3206 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3207 0,
3208 Entities.back()));
3209
3210 // Direct-initialize to use the copy constructor.
3211 InitializationKind InitKind =
3212 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3213
Sebastian Redle9c4e842011-09-04 18:14:28 +00003214 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003215 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003216
John McCalldadc5752010-08-24 06:29:42 +00003217 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003218 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003219 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003220 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003221 if (MemberInit.isInvalid())
3222 return true;
3223
Douglas Gregor493627b2011-08-10 15:22:55 +00003224 if (Indirect) {
3225 assert(IndexVariables.size() == 0 &&
3226 "Indirect field improperly initialized");
3227 CXXMemberInit
3228 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3229 Loc, Loc,
3230 MemberInit.takeAs<Expr>(),
3231 Loc);
3232 } else
3233 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3234 Loc, MemberInit.takeAs<Expr>(),
3235 Loc,
3236 IndexVariables.data(),
3237 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003238 return false;
3239 }
3240
Richard Smithc2bc61b2013-03-18 21:12:30 +00003241 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3242 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003243
Anders Carlsson3c1db572010-04-23 02:15:47 +00003244 QualType FieldBaseElementType =
3245 SemaRef.Context.getBaseElementType(Field->getType());
3246
Anders Carlsson3c1db572010-04-23 02:15:47 +00003247 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003248 InitializedEntity InitEntity
3249 = Indirect? InitializedEntity::InitializeMember(Indirect)
3250 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003251 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003252 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003253
3254 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3255 ExprResult MemberInit =
3256 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003257
Douglas Gregora40433a2010-12-07 00:41:46 +00003258 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003259 if (MemberInit.isInvalid())
3260 return true;
3261
Douglas Gregor493627b2011-08-10 15:22:55 +00003262 if (Indirect)
3263 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3264 Indirect, Loc,
3265 Loc,
3266 MemberInit.get(),
3267 Loc);
3268 else
3269 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3270 Field, Loc, Loc,
3271 MemberInit.get(),
3272 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003273 return false;
3274 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003275
Alexis Hunt8b455182011-05-17 00:19:05 +00003276 if (!Field->getParent()->isUnion()) {
3277 if (FieldBaseElementType->isReferenceType()) {
3278 SemaRef.Diag(Constructor->getLocation(),
3279 diag::err_uninitialized_member_in_ctor)
3280 << (int)Constructor->isImplicit()
3281 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3282 << 0 << Field->getDeclName();
3283 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3284 return true;
3285 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003286
Alexis Hunt8b455182011-05-17 00:19:05 +00003287 if (FieldBaseElementType.isConstQualified()) {
3288 SemaRef.Diag(Constructor->getLocation(),
3289 diag::err_uninitialized_member_in_ctor)
3290 << (int)Constructor->isImplicit()
3291 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3292 << 1 << Field->getDeclName();
3293 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3294 return true;
3295 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003296 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003297
David Blaikiebbafb8a2012-03-11 07:00:24 +00003298 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003299 FieldBaseElementType->isObjCRetainableType() &&
3300 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3301 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003302 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003303 // Default-initialize Objective-C pointers to NULL.
3304 CXXMemberInit
3305 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3306 Loc, Loc,
3307 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3308 Loc);
3309 return false;
3310 }
3311
Anders Carlsson3c1db572010-04-23 02:15:47 +00003312 // Nothing to initialize.
3313 CXXMemberInit = 0;
3314 return false;
3315}
John McCallbc83b3f2010-05-20 23:23:51 +00003316
3317namespace {
3318struct BaseAndFieldInfo {
3319 Sema &S;
3320 CXXConstructorDecl *Ctor;
3321 bool AnyErrorsInInits;
3322 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003323 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003324 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003325 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003326
3327 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3328 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003329 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3330 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003331 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003332 else if (Generated && Ctor->isMoveConstructor())
3333 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003334 else if (Ctor->getInheritedConstructor())
3335 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003336 else
3337 IIK = IIK_Default;
3338 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003339
3340 bool isImplicitCopyOrMove() const {
3341 switch (IIK) {
3342 case IIK_Copy:
3343 case IIK_Move:
3344 return true;
3345
3346 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003347 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003348 return false;
3349 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003350
3351 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003352 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003353
3354 bool addFieldInitializer(CXXCtorInitializer *Init) {
3355 AllToInit.push_back(Init);
3356
3357 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003358 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003359 S.UnusedPrivateFields.remove(Init->getAnyMember());
3360
3361 return false;
3362 }
John McCallbc83b3f2010-05-20 23:23:51 +00003363
Richard Smithab44d5b2013-12-10 08:25:00 +00003364 bool isInactiveUnionMember(FieldDecl *Field) {
3365 RecordDecl *Record = Field->getParent();
3366 if (!Record->isUnion())
3367 return false;
3368
Richard Smith8d183852013-12-10 20:56:03 +00003369 if (FieldDecl *Active =
3370 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003371 return Active != Field->getCanonicalDecl();
3372
3373 // In an implicit copy or move constructor, ignore any in-class initializer.
3374 if (isImplicitCopyOrMove())
3375 return true;
3376
3377 // If there's no explicit initialization, the field is active only if it
3378 // has an in-class initializer...
3379 if (Field->hasInClassInitializer())
3380 return false;
3381 // ... or it's an anonymous struct or union whose class has an in-class
3382 // initializer.
3383 if (!Field->isAnonymousStructOrUnion())
3384 return true;
3385 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3386 return !FieldRD->hasInClassInitializer();
3387 }
3388
3389 /// \brief Determine whether the given field is, or is within, a union member
3390 /// that is inactive (because there was an initializer given for a different
3391 /// member of the union, or because the union was not initialized at all).
3392 bool isWithinInactiveUnionMember(FieldDecl *Field,
3393 IndirectFieldDecl *Indirect) {
3394 if (!Indirect)
3395 return isInactiveUnionMember(Field);
3396
Aaron Ballman29c94602014-03-07 18:36:15 +00003397 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003398 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003399 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003400 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003401 }
3402 return false;
3403 }
3404};
Richard Smithc94ec842011-09-19 13:34:43 +00003405}
3406
Douglas Gregor10f939c2011-11-02 23:04:16 +00003407/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3408/// array type.
3409static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3410 if (T->isIncompleteArrayType())
3411 return true;
3412
3413 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3414 if (!ArrayT->getSize())
3415 return true;
3416
3417 T = ArrayT->getElementType();
3418 }
3419
3420 return false;
3421}
3422
Richard Smith938f40b2011-06-11 17:19:42 +00003423static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003424 FieldDecl *Field,
3425 IndirectFieldDecl *Indirect = 0) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003426 if (Field->isInvalidDecl())
3427 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003428
Chandler Carruth139e9622010-06-30 02:59:29 +00003429 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0a8cfc72012-08-07 21:30:42 +00003430 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3431 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003432
Richard Smithab44d5b2013-12-10 08:25:00 +00003433 // C++11 [class.base.init]p8:
3434 // if the entity is a non-static data member that has a
3435 // brace-or-equal-initializer and either
3436 // -- the constructor's class is a union and no other variant member of that
3437 // union is designated by a mem-initializer-id or
3438 // -- the constructor's class is not a union, and, if the entity is a member
3439 // of an anonymous union, no other member of that union is designated by
3440 // a mem-initializer-id,
3441 // the entity is initialized as specified in [dcl.init].
3442 //
3443 // We also apply the same rules to handle anonymous structs within anonymous
3444 // unions.
3445 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3446 return false;
3447
Douglas Gregor7db3e952011-11-28 20:03:15 +00003448 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003449 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3450 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003451 CXXCtorInitializer *Init;
3452 if (Indirect)
3453 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3454 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003455 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003456 SourceLocation());
3457 else
3458 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3459 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003460 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003461 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003462 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003463 }
3464
Douglas Gregor10f939c2011-11-02 23:04:16 +00003465 // Don't initialize incomplete or zero-length arrays.
3466 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3467 return false;
3468
John McCallbc83b3f2010-05-20 23:23:51 +00003469 // Don't try to build an implicit initializer if there were semantic
3470 // errors in any of the initializers (and therefore we might be
3471 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003472 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003473 return false;
3474
Alexis Hunt1d792652011-01-08 20:30:50 +00003475 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003476 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3477 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003478 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003479
Richard Smith0a8cfc72012-08-07 21:30:42 +00003480 if (!Init)
3481 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003482
Richard Smith0a8cfc72012-08-07 21:30:42 +00003483 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003484}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003485
3486bool
3487Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3488 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003489 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003490 Constructor->setNumCtorInitializers(1);
3491 CXXCtorInitializer **initializer =
3492 new (Context) CXXCtorInitializer*[1];
3493 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3494 Constructor->setCtorInitializers(initializer);
3495
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003496 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003497 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003498 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3499 }
3500
Alexis Hunte2622992011-05-05 00:05:47 +00003501 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003502
Alexis Hunt61bc1732011-05-01 07:04:31 +00003503 return false;
3504}
Douglas Gregor493627b2011-08-10 15:22:55 +00003505
David Blaikie3fc2f912013-01-17 05:26:25 +00003506bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3507 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003508 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003509 // Just store the initializers as written, they will be checked during
3510 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003511 if (!Initializers.empty()) {
3512 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003513 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003514 new (Context) CXXCtorInitializer*[Initializers.size()];
3515 memcpy(baseOrMemberInitializers, Initializers.data(),
3516 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003517 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003518 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003519
3520 // Let template instantiation know whether we had errors.
3521 if (AnyErrors)
3522 Constructor->setInvalidDecl();
3523
Anders Carlssondb0a9652010-04-02 06:26:44 +00003524 return false;
3525 }
3526
John McCallbc83b3f2010-05-20 23:23:51 +00003527 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003528
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003529 // We need to build the initializer AST according to order of construction
3530 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003531 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003532 if (!ClassDecl)
3533 return true;
3534
Eli Friedman9cf6b592009-11-09 19:20:36 +00003535 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003536
David Blaikie3fc2f912013-01-17 05:26:25 +00003537 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003538 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003539
Anders Carlssondb0a9652010-04-02 06:26:44 +00003540 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003541 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003542 else {
Francois Pichetd583da02010-12-04 09:14:42 +00003543 Info.AllBaseFields[Member->getAnyMember()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003544
3545 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003546 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003547 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003548 if (FD && FD->getParent()->isUnion())
3549 Info.ActiveUnionMember.insert(std::make_pair(
3550 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3551 }
3552 } else if (FieldDecl *FD = Member->getMember()) {
3553 if (FD->getParent()->isUnion())
3554 Info.ActiveUnionMember.insert(std::make_pair(
3555 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3556 }
3557 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003558 }
3559
Anders Carlsson43c64af2010-04-21 19:52:01 +00003560 // Keep track of the direct virtual bases.
3561 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003562 for (auto &I : ClassDecl->bases()) {
3563 if (I.isVirtual())
3564 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003565 }
3566
Anders Carlssondb0a9652010-04-02 06:26:44 +00003567 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003568 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003569 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003570 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003571 // [class.base.init]p7, per DR257:
3572 // A mem-initializer where the mem-initializer-id names a virtual base
3573 // class is ignored during execution of a constructor of any class that
3574 // is not the most derived class.
3575 if (ClassDecl->isAbstract()) {
3576 // FIXME: Provide a fixit to remove the base specifier. This requires
3577 // tracking the location of the associated comma for a base specifier.
3578 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003579 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003580 DiagnoseAbstractType(ClassDecl);
3581 }
3582
John McCallbc83b3f2010-05-20 23:23:51 +00003583 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003584 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3585 // [class.base.init]p8, per DR257:
3586 // If a given [...] base class is not named by a mem-initializer-id
3587 // [...] and the entity is not a virtual base class of an abstract
3588 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003589 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003590 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003591 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003592 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003593 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003594 HadError = true;
3595 continue;
3596 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003597
John McCallbc83b3f2010-05-20 23:23:51 +00003598 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003599 }
3600 }
Mike Stump11289f42009-09-09 15:08:12 +00003601
John McCallbc83b3f2010-05-20 23:23:51 +00003602 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003603 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003604 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003605 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003606 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003607
Alexis Hunt1d792652011-01-08 20:30:50 +00003608 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003609 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003610 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003611 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003612 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003613 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003614 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003615 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003616 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003617 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003618 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003619
John McCallbc83b3f2010-05-20 23:23:51 +00003620 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003621 }
3622 }
Mike Stump11289f42009-09-09 15:08:12 +00003623
John McCallbc83b3f2010-05-20 23:23:51 +00003624 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003625 for (auto *Mem : ClassDecl->decls()) {
3626 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003627 // C++ [class.bit]p2:
3628 // A declaration for a bit-field that omits the identifier declares an
3629 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3630 // initialized.
3631 if (F->isUnnamedBitfield())
3632 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003633
Sebastian Redl22653ba2011-08-30 19:58:05 +00003634 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003635 // handle anonymous struct/union fields based on their individual
3636 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003637 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003638 continue;
3639
3640 if (CollectFieldInitializer(*this, Info, F))
3641 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003642 continue;
3643 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003644
3645 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003646 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003647 continue;
3648
Aaron Ballman629afae2014-03-07 19:56:05 +00003649 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003650 if (F->getType()->isIncompleteArrayType()) {
3651 assert(ClassDecl->hasFlexibleArrayMember() &&
3652 "Incomplete array type is not valid");
3653 continue;
3654 }
3655
Douglas Gregor493627b2011-08-10 15:22:55 +00003656 // Initialize each field of an anonymous struct individually.
3657 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3658 HadError = true;
3659
3660 continue;
3661 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003662 }
Mike Stump11289f42009-09-09 15:08:12 +00003663
David Blaikie3fc2f912013-01-17 05:26:25 +00003664 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003665 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003666 Constructor->setNumCtorInitializers(NumInitializers);
3667 CXXCtorInitializer **baseOrMemberInitializers =
3668 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003669 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003670 NumInitializers * sizeof(CXXCtorInitializer*));
3671 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003672
John McCalla6309952010-03-16 21:39:52 +00003673 // Constructors implicitly reference the base and member
3674 // destructors.
3675 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3676 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003677 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003678
3679 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003680}
3681
David Blaikieb61b8152013-01-17 08:49:22 +00003682static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003683 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003684 const RecordDecl *RD = RT->getDecl();
3685 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003686 for (auto *Field : RD->fields())
3687 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003688 return;
3689 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003690 }
David Blaikieb61b8152013-01-17 08:49:22 +00003691 IdealInits.push_back(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003692}
3693
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003694static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3695 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003696}
3697
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003698static const void *GetKeyForMember(ASTContext &Context,
3699 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003700 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003701 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003702
David Blaikieb61b8152013-01-17 08:49:22 +00003703 return Member->getAnyMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00003704}
3705
David Blaikie3fc2f912013-01-17 05:26:25 +00003706static void DiagnoseBaseOrMemInitializerOrder(
3707 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3708 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003709 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003710 return;
Mike Stump11289f42009-09-09 15:08:12 +00003711
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003712 // Don't check initializers order unless the warning is enabled at the
3713 // location of at least one initializer.
3714 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003715 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003716 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003717 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3718 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003719 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003720 ShouldCheckOrder = true;
3721 break;
3722 }
3723 }
3724 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003725 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003726
John McCallbb7b6582010-04-10 07:37:23 +00003727 // Build the list of bases and members in the order that they'll
3728 // actually be initialized. The explicit initializers should be in
3729 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003730 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003731
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003732 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3733
John McCallbb7b6582010-04-10 07:37:23 +00003734 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003735 for (const auto &VBase : ClassDecl->vbases())
3736 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003737
John McCallbb7b6582010-04-10 07:37:23 +00003738 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003739 for (const auto &Base : ClassDecl->bases()) {
3740 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003741 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003742 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003743 }
Mike Stump11289f42009-09-09 15:08:12 +00003744
John McCallbb7b6582010-04-10 07:37:23 +00003745 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003746 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003747 if (Field->isUnnamedBitfield())
3748 continue;
3749
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003750 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003751 }
3752
John McCallbb7b6582010-04-10 07:37:23 +00003753 unsigned NumIdealInits = IdealInitKeys.size();
3754 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003755
Alexis Hunt1d792652011-01-08 20:30:50 +00003756 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003757 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003758 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003759 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003760
3761 // Scan forward to try to find this initializer in the idealized
3762 // initializers list.
3763 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3764 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003765 break;
John McCallbb7b6582010-04-10 07:37:23 +00003766
3767 // If we didn't find this initializer, it must be because we
3768 // scanned past it on a previous iteration. That can only
3769 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003770 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003771 Sema::SemaDiagnosticBuilder D =
3772 SemaRef.Diag(PrevInit->getSourceLocation(),
3773 diag::warn_initializer_out_of_order);
3774
Francois Pichetd583da02010-12-04 09:14:42 +00003775 if (PrevInit->isAnyMemberInitializer())
3776 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003777 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003778 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003779
Francois Pichetd583da02010-12-04 09:14:42 +00003780 if (Init->isAnyMemberInitializer())
3781 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003782 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003783 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003784
3785 // Move back to the initializer's location in the ideal list.
3786 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3787 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003788 break;
John McCallbb7b6582010-04-10 07:37:23 +00003789
3790 assert(IdealIndex != NumIdealInits &&
3791 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003792 }
John McCallbb7b6582010-04-10 07:37:23 +00003793
3794 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003795 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003796}
3797
John McCall23eebd92010-04-10 09:28:51 +00003798namespace {
3799bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003800 CXXCtorInitializer *Init,
3801 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003802 if (!PrevInit) {
3803 PrevInit = Init;
3804 return false;
3805 }
3806
Douglas Gregorea306a12013-03-25 23:28:23 +00003807 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003808 S.Diag(Init->getSourceLocation(),
3809 diag::err_multiple_mem_initialization)
3810 << Field->getDeclName()
3811 << Init->getSourceRange();
3812 else {
John McCall424cec92011-01-19 06:33:43 +00003813 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003814 assert(BaseClass && "neither field nor base");
3815 S.Diag(Init->getSourceLocation(),
3816 diag::err_multiple_base_initialization)
3817 << QualType(BaseClass, 0)
3818 << Init->getSourceRange();
3819 }
3820 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3821 << 0 << PrevInit->getSourceRange();
3822
3823 return true;
3824}
3825
Alexis Hunt1d792652011-01-08 20:30:50 +00003826typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003827typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3828
3829bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003830 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003831 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003832 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003833 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003834 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003835
3836 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003837 if (Parent->isUnion()) {
3838 UnionEntry &En = Unions[Parent];
3839 if (En.first && En.first != Child) {
3840 S.Diag(Init->getSourceLocation(),
3841 diag::err_multiple_mem_union_initialization)
3842 << Field->getDeclName()
3843 << Init->getSourceRange();
3844 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3845 << 0 << En.second->getSourceRange();
3846 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003847 }
3848 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003849 En.first = Child;
3850 En.second = Init;
3851 }
David Blaikie0f65d592011-11-17 06:01:57 +00003852 if (!Parent->isAnonymousStructOrUnion())
3853 return false;
John McCall23eebd92010-04-10 09:28:51 +00003854 }
3855
3856 Child = Parent;
3857 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003858 }
John McCall23eebd92010-04-10 09:28:51 +00003859
3860 return false;
3861}
3862}
3863
Anders Carlssone857b292010-04-02 03:37:03 +00003864/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003865void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003866 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003867 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003868 bool AnyErrors) {
3869 if (!ConstructorDecl)
3870 return;
3871
3872 AdjustDeclIfTemplate(ConstructorDecl);
3873
3874 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003875 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003876
3877 if (!Constructor) {
3878 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3879 return;
3880 }
3881
John McCall23eebd92010-04-10 09:28:51 +00003882 // Mapping for the duplicate initializers check.
3883 // For member initializers, this is keyed with a FieldDecl*.
3884 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003885 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003886
3887 // Mapping for the inconsistent anonymous-union initializers check.
3888 RedundantUnionMap MemberUnions;
3889
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003890 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003891 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003892 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003893
Abramo Bagnara341d7832010-05-26 18:09:23 +00003894 // Set the source order index.
3895 Init->setSourceOrder(i);
3896
Francois Pichetd583da02010-12-04 09:14:42 +00003897 if (Init->isAnyMemberInitializer()) {
3898 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003899 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3900 CheckRedundantUnionInit(*this, Init, MemberUnions))
3901 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003902 } else if (Init->isBaseInitializer()) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003903 const void *Key =
3904 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall23eebd92010-04-10 09:28:51 +00003905 if (CheckRedundantInit(*this, Init, Members[Key]))
3906 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003907 } else {
3908 assert(Init->isDelegatingInitializer());
3909 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003910 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003911 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003912 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003913 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003914 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003915 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003916 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003917 // Return immediately as the initializer is set.
3918 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003919 }
Anders Carlssone857b292010-04-02 03:37:03 +00003920 }
3921
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003922 if (HadError)
3923 return;
3924
David Blaikie3fc2f912013-01-17 05:26:25 +00003925 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003926
David Blaikie3fc2f912013-01-17 05:26:25 +00003927 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003928
Richard Trieuef64e942013-10-25 00:56:00 +00003929 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003930}
3931
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003932void
John McCalla6309952010-03-16 21:39:52 +00003933Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3934 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003935 // Ignore dependent contexts. Also ignore unions, since their members never
3936 // have destructors implicitly called.
3937 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003938 return;
John McCall1064d7e2010-03-16 05:22:47 +00003939
3940 // FIXME: all the access-control diagnostics are positioned on the
3941 // field/base declaration. That's probably good; that said, the
3942 // user might reasonably want to know why the destructor is being
3943 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003944
Anders Carlssondee9a302009-11-17 04:44:12 +00003945 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003946 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003947 if (Field->isInvalidDecl())
3948 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003949
3950 // Don't destroy incomplete or zero-length arrays.
3951 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3952 continue;
3953
Anders Carlssondee9a302009-11-17 04:44:12 +00003954 QualType FieldType = Context.getBaseElementType(Field->getType());
3955
3956 const RecordType* RT = FieldType->getAs<RecordType>();
3957 if (!RT)
3958 continue;
3959
3960 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003961 if (FieldClassDecl->isInvalidDecl())
3962 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003963 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003964 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003965 // The destructor for an implicit anonymous union member is never invoked.
3966 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3967 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003968
Douglas Gregore71edda2010-07-01 22:47:18 +00003969 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003970 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003971 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003972 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003973 << Field->getDeclName()
3974 << FieldType);
3975
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003976 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003977 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003978 }
3979
John McCall1064d7e2010-03-16 05:22:47 +00003980 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3981
Anders Carlssondee9a302009-11-17 04:44:12 +00003982 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003983 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00003984 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00003985 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00003986
3987 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003988 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003989 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003990
John McCall1064d7e2010-03-16 05:22:47 +00003991 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003992 // If our base class is invalid, we probably can't get its dtor anyway.
3993 if (BaseClassDecl->isInvalidDecl())
3994 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003995 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003996 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003997
Douglas Gregore71edda2010-07-01 22:47:18 +00003998 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003999 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004000
4001 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004002 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004003 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004004 << Base.getType()
4005 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004006 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004007
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004008 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004009 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004010 }
4011
4012 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004013 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004014 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004015 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004016
4017 // Ignore direct virtual bases.
4018 if (DirectVirtualBases.count(RT))
4019 continue;
4020
John McCall1064d7e2010-03-16 05:22:47 +00004021 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004022 // If our base class is invalid, we probably can't get its dtor anyway.
4023 if (BaseClassDecl->isInvalidDecl())
4024 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004025 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004026 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004027
Douglas Gregore71edda2010-07-01 22:47:18 +00004028 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004029 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004030 if (CheckDestructorAccess(
4031 ClassDecl->getLocation(), Dtor,
4032 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004033 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004034 Context.getTypeDeclType(ClassDecl)) ==
4035 AR_accessible) {
4036 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004037 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004038 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4039 SourceRange(), DeclarationName(), 0);
4040 }
John McCall1064d7e2010-03-16 05:22:47 +00004041
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004042 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004043 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004044 }
4045}
4046
John McCall48871652010-08-21 09:40:31 +00004047void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004048 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004049 return;
Mike Stump11289f42009-09-09 15:08:12 +00004050
Mike Stump11289f42009-09-09 15:08:12 +00004051 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004052 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004053 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004054 DiagnoseUninitializedFields(*this, Constructor);
4055 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004056}
4057
Mike Stump11289f42009-09-09 15:08:12 +00004058bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004059 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004060 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4061 unsigned DiagID;
4062 AbstractDiagSelID SelID;
4063
4064 public:
4065 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4066 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004067
Craig Toppera798a9d2014-03-02 09:32:10 +00004068 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004069 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004070 if (SelID == -1)
4071 S.Diag(Loc, DiagID) << T;
4072 else
4073 S.Diag(Loc, DiagID) << SelID << T;
4074 }
4075 } Diagnoser(DiagID, SelID);
4076
4077 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004078}
4079
Anders Carlssoneabf7702009-08-27 00:13:57 +00004080bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004081 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004082 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004083 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004084
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004085 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004086 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004087
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004088 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004089 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004090 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004091 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004092
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004093 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004094 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004095 }
Mike Stump11289f42009-09-09 15:08:12 +00004096
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004097 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004098 if (!RT)
4099 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004100
John McCall67da35c2010-02-04 22:26:26 +00004101 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004102
John McCall02db245d2010-08-18 09:41:07 +00004103 // We can't answer whether something is abstract until it has a
4104 // definition. If it's currently being defined, we'll walk back
4105 // over all the declarations when we have a full definition.
4106 const CXXRecordDecl *Def = RD->getDefinition();
4107 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004108 return false;
4109
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004110 if (!RD->isAbstract())
4111 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004112
Douglas Gregorae298422012-05-04 17:09:59 +00004113 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004114 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004115
John McCall02db245d2010-08-18 09:41:07 +00004116 return true;
4117}
4118
4119void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4120 // Check if we've already emitted the list of pure virtual functions
4121 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004122 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004123 return;
Mike Stump11289f42009-09-09 15:08:12 +00004124
Richard Smithbc46e432013-07-22 02:56:56 +00004125 // If the diagnostic is suppressed, don't emit the notes. We're only
4126 // going to emit them once, so try to attach them to a diagnostic we're
4127 // actually going to show.
4128 if (Diags.isLastDiagnosticIgnored())
4129 return;
4130
Douglas Gregor4165bd62010-03-23 23:47:56 +00004131 CXXFinalOverriderMap FinalOverriders;
4132 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004133
Anders Carlssona2f74f32010-06-03 01:00:02 +00004134 // Keep a set of seen pure methods so we won't diagnose the same method
4135 // more than once.
4136 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4137
Douglas Gregor4165bd62010-03-23 23:47:56 +00004138 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4139 MEnd = FinalOverriders.end();
4140 M != MEnd;
4141 ++M) {
4142 for (OverridingMethods::iterator SO = M->second.begin(),
4143 SOEnd = M->second.end();
4144 SO != SOEnd; ++SO) {
4145 // C++ [class.abstract]p4:
4146 // A class is abstract if it contains or inherits at least one
4147 // pure virtual function for which the final overrider is pure
4148 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004149
Douglas Gregor4165bd62010-03-23 23:47:56 +00004150 //
4151 if (SO->second.size() != 1)
4152 continue;
4153
4154 if (!SO->second.front().Method->isPure())
4155 continue;
4156
Anders Carlssona2f74f32010-06-03 01:00:02 +00004157 if (!SeenPureMethods.insert(SO->second.front().Method))
4158 continue;
4159
Douglas Gregor4165bd62010-03-23 23:47:56 +00004160 Diag(SO->second.front().Method->getLocation(),
4161 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004162 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004163 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004164 }
4165
4166 if (!PureVirtualClassDiagSet)
4167 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4168 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004169}
4170
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004171namespace {
John McCall02db245d2010-08-18 09:41:07 +00004172struct AbstractUsageInfo {
4173 Sema &S;
4174 CXXRecordDecl *Record;
4175 CanQualType AbstractType;
4176 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004177
John McCall02db245d2010-08-18 09:41:07 +00004178 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4179 : S(S), Record(Record),
4180 AbstractType(S.Context.getCanonicalType(
4181 S.Context.getTypeDeclType(Record))),
4182 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004183
John McCall02db245d2010-08-18 09:41:07 +00004184 void DiagnoseAbstractType() {
4185 if (Invalid) return;
4186 S.DiagnoseAbstractType(Record);
4187 Invalid = true;
4188 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004189
John McCall02db245d2010-08-18 09:41:07 +00004190 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4191};
4192
4193struct CheckAbstractUsage {
4194 AbstractUsageInfo &Info;
4195 const NamedDecl *Ctx;
4196
4197 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4198 : Info(Info), Ctx(Ctx) {}
4199
4200 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4201 switch (TL.getTypeLocClass()) {
4202#define ABSTRACT_TYPELOC(CLASS, PARENT)
4203#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004204 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004205#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004206 }
John McCall02db245d2010-08-18 09:41:07 +00004207 }
Mike Stump11289f42009-09-09 15:08:12 +00004208
John McCall02db245d2010-08-18 09:41:07 +00004209 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004210 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004211 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4212 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004213 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004214
4215 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004216 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004217 }
John McCall02db245d2010-08-18 09:41:07 +00004218 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004219
John McCall02db245d2010-08-18 09:41:07 +00004220 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4221 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4222 }
Mike Stump11289f42009-09-09 15:08:12 +00004223
John McCall02db245d2010-08-18 09:41:07 +00004224 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4225 // Visit the type parameters from a permissive context.
4226 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4227 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4228 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4229 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4230 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4231 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004232 }
John McCall02db245d2010-08-18 09:41:07 +00004233 }
Mike Stump11289f42009-09-09 15:08:12 +00004234
John McCall02db245d2010-08-18 09:41:07 +00004235 // Visit pointee types from a permissive context.
4236#define CheckPolymorphic(Type) \
4237 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4238 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4239 }
4240 CheckPolymorphic(PointerTypeLoc)
4241 CheckPolymorphic(ReferenceTypeLoc)
4242 CheckPolymorphic(MemberPointerTypeLoc)
4243 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004244 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004245
John McCall02db245d2010-08-18 09:41:07 +00004246 /// Handle all the types we haven't given a more specific
4247 /// implementation for above.
4248 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4249 // Every other kind of type that we haven't called out already
4250 // that has an inner type is either (1) sugar or (2) contains that
4251 // inner type in some way as a subobject.
4252 if (TypeLoc Next = TL.getNextTypeLoc())
4253 return Visit(Next, Sel);
4254
4255 // If there's no inner type and we're in a permissive context,
4256 // don't diagnose.
4257 if (Sel == Sema::AbstractNone) return;
4258
4259 // Check whether the type matches the abstract type.
4260 QualType T = TL.getType();
4261 if (T->isArrayType()) {
4262 Sel = Sema::AbstractArrayType;
4263 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004264 }
John McCall02db245d2010-08-18 09:41:07 +00004265 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4266 if (CT != Info.AbstractType) return;
4267
4268 // It matched; do some magic.
4269 if (Sel == Sema::AbstractArrayType) {
4270 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4271 << T << TL.getSourceRange();
4272 } else {
4273 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4274 << Sel << T << TL.getSourceRange();
4275 }
4276 Info.DiagnoseAbstractType();
4277 }
4278};
4279
4280void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4281 Sema::AbstractDiagSelID Sel) {
4282 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4283}
4284
4285}
4286
4287/// Check for invalid uses of an abstract type in a method declaration.
4288static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4289 CXXMethodDecl *MD) {
4290 // No need to do the check on definitions, which require that
4291 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004292 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004293 return;
4294
4295 // For safety's sake, just ignore it if we don't have type source
4296 // information. This should never happen for non-implicit methods,
4297 // but...
4298 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4299 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4300}
4301
4302/// Check for invalid uses of an abstract type within a class definition.
4303static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4304 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004305 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004306 if (D->isImplicit()) continue;
4307
4308 // Methods and method templates.
4309 if (isa<CXXMethodDecl>(D)) {
4310 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4311 } else if (isa<FunctionTemplateDecl>(D)) {
4312 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4313 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4314
4315 // Fields and static variables.
4316 } else if (isa<FieldDecl>(D)) {
4317 FieldDecl *FD = cast<FieldDecl>(D);
4318 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4319 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4320 } else if (isa<VarDecl>(D)) {
4321 VarDecl *VD = cast<VarDecl>(D);
4322 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4323 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4324
4325 // Nested classes and class templates.
4326 } else if (isa<CXXRecordDecl>(D)) {
4327 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4328 } else if (isa<ClassTemplateDecl>(D)) {
4329 CheckAbstractClassUsage(Info,
4330 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4331 }
4332 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004333}
4334
Douglas Gregorc99f1552009-12-03 18:33:45 +00004335/// \brief Perform semantic checks on a class definition that has been
4336/// completing, introducing implicitly-declared members, checking for
4337/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004338void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004339 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004340 return;
4341
John McCall02db245d2010-08-18 09:41:07 +00004342 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4343 AbstractUsageInfo Info(*this, Record);
4344 CheckAbstractClassUsage(Info, Record);
4345 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004346
4347 // If this is not an aggregate type and has no user-declared constructor,
4348 // complain about any non-static data members of reference or const scalar
4349 // type, since they will never get initializers.
4350 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004351 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4352 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004353 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004354 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004355 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004356 continue;
4357
Douglas Gregor454a5b62010-04-15 00:00:53 +00004358 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004359 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004360 if (!Complained) {
4361 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4362 << Record->getTagKind() << Record;
4363 Complained = true;
4364 }
4365
4366 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4367 << F->getType()->isReferenceType()
4368 << F->getDeclName();
4369 }
4370 }
4371 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004372
Anders Carlssone771e762011-01-25 18:08:22 +00004373 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004374 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004375
4376 if (Record->getIdentifier()) {
4377 // C++ [class.mem]p13:
4378 // If T is the name of a class, then each of the following shall have a
4379 // name different from T:
4380 // - every member of every anonymous union that is a member of class T.
4381 //
4382 // C++ [class.mem]p14:
4383 // In addition, if class T has a user-declared constructor (12.1), every
4384 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004385 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4386 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4387 ++I) {
4388 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004389 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4390 isa<IndirectFieldDecl>(D)) {
4391 Diag(D->getLocation(), diag::err_member_name_of_class)
4392 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004393 break;
4394 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004395 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004396 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004397
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004398 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004399 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004400 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004401 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004402 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4403 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4404 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004405
David Majnemera5433082013-10-18 00:33:31 +00004406 if (Record->isAbstract()) {
4407 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4408 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4409 << FA->isSpelledAsSealed();
4410 DiagnoseAbstractType(Record);
4411 }
David Blaikie348df502012-09-21 03:21:07 +00004412 }
4413
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004414 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004415 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004416 // See if a method overloads virtual methods in a base
4417 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004418 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004419 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004420
4421 // Check whether the explicitly-defaulted special members are valid.
4422 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004423 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004424
4425 // For an explicitly defaulted or deleted special member, we defer
4426 // determining triviality until the class is complete. That time is now!
4427 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004428 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004429 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004430 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004431
4432 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004433 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004434 }
4435 }
4436 }
4437 }
4438
4439 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4440 // function that is not a constructor declares that member function to be
4441 // const. [...] The class of which that function is a member shall be
4442 // a literal type.
4443 //
4444 // If the class has virtual bases, any constexpr members will already have
4445 // been diagnosed by the checks performed on the member declaration, so
4446 // suppress this (less useful) diagnostic.
4447 //
4448 // We delay this until we know whether an explicitly-defaulted (or deleted)
4449 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004450 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004451 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004452 for (const auto *M : Record->methods()) {
4453 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004454 switch (Record->getTemplateSpecializationKind()) {
4455 case TSK_ImplicitInstantiation:
4456 case TSK_ExplicitInstantiationDeclaration:
4457 case TSK_ExplicitInstantiationDefinition:
4458 // If a template instantiates to a non-literal type, but its members
4459 // instantiate to constexpr functions, the template is technically
4460 // ill-formed, but we allow it for sanity.
4461 continue;
4462
4463 case TSK_Undeclared:
4464 case TSK_ExplicitSpecialization:
4465 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4466 diag::err_constexpr_method_non_literal);
4467 break;
4468 }
4469
4470 // Only produce one error per class.
4471 break;
4472 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004473 }
4474 }
Sebastian Redl08905022011-02-05 19:23:19 +00004475
John McCall95833f32014-02-27 20:30:49 +00004476 // ms_struct is a request to use the same ABI rules as MSVC. Check
4477 // whether this class uses any C++ features that are implemented
4478 // completely differently in MSVC, and if so, emit a diagnostic.
4479 // That diagnostic defaults to an error, but we allow projects to
4480 // map it down to a warning (or ignore it). It's a fairly common
4481 // practice among users of the ms_struct pragma to mass-annotate
4482 // headers, sweeping up a bunch of types that the project doesn't
4483 // really rely on MSVC-compatible layout for. We must therefore
4484 // support "ms_struct except for C++ stuff" as a secondary ABI.
4485 if (Record->isMsStruct(Context) &&
4486 (Record->isPolymorphic() || Record->getNumBases())) {
4487 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004488 }
4489
Richard Smithc2bc61b2013-03-18 21:12:30 +00004490 // Declare inheriting constructors. We do this eagerly here because:
4491 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004492 // constructors from different classes.
4493 // - The lazy declaration of the other implicit constructors is so as to not
4494 // waste space and performance on classes that are not meant to be
4495 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004496 // have inheriting constructors.
4497 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004498}
4499
Richard Smith41c35d62013-11-27 03:39:20 +00004500/// Look up the special member function that would be called by a special
4501/// member function for a subobject of class type.
4502///
4503/// \param Class The class type of the subobject.
4504/// \param CSM The kind of special member function.
4505/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4506/// \param ConstRHS True if this is a copy operation with a const object
4507/// on its RHS, that is, if the argument to the outer special member
4508/// function is 'const' and this is not a field marked 'mutable'.
4509static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4510 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4511 unsigned FieldQuals, bool ConstRHS) {
4512 unsigned LHSQuals = 0;
4513 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4514 LHSQuals = FieldQuals;
4515
4516 unsigned RHSQuals = FieldQuals;
4517 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4518 RHSQuals = 0;
4519 else if (ConstRHS)
4520 RHSQuals |= Qualifiers::Const;
4521
4522 return S.LookupSpecialMember(Class, CSM,
4523 RHSQuals & Qualifiers::Const,
4524 RHSQuals & Qualifiers::Volatile,
4525 false,
4526 LHSQuals & Qualifiers::Const,
4527 LHSQuals & Qualifiers::Volatile);
4528}
4529
Richard Smithb5800092012-06-10 05:43:50 +00004530/// Is the special member function which would be selected to perform the
4531/// specified operation on the specified class type a constexpr constructor?
4532static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4533 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004534 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004535 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004536 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004537 if (!SMOR || !SMOR->getMethod())
4538 // A constructor we wouldn't select can't be "involved in initializing"
4539 // anything.
4540 return true;
4541 return SMOR->getMethod()->isConstexpr();
4542}
4543
4544/// Determine whether the specified special member function would be constexpr
4545/// if it were implicitly defined.
4546static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4547 Sema::CXXSpecialMember CSM,
4548 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004549 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004550 return false;
4551
4552 // C++11 [dcl.constexpr]p4:
4553 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004554 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004555 switch (CSM) {
4556 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004557 // Since default constructor lookup is essentially trivial (and cannot
4558 // involve, for instance, template instantiation), we compute whether a
4559 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4560 //
4561 // This is important for performance; we need to know whether the default
4562 // constructor is constexpr to determine whether the type is a literal type.
4563 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4564
Richard Smithb5800092012-06-10 05:43:50 +00004565 case Sema::CXXCopyConstructor:
4566 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004567 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004568 break;
4569
4570 case Sema::CXXCopyAssignment:
4571 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004572 if (!S.getLangOpts().CPlusPlus1y)
4573 return false;
4574 // In C++1y, we need to perform overload resolution.
4575 Ctor = false;
4576 break;
4577
Richard Smithb5800092012-06-10 05:43:50 +00004578 case Sema::CXXDestructor:
4579 case Sema::CXXInvalid:
4580 return false;
4581 }
4582
4583 // -- if the class is a non-empty union, or for each non-empty anonymous
4584 // union member of a non-union class, exactly one non-static data member
4585 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004586 //
4587 // If we squint, this is guaranteed, since exactly one non-static data member
4588 // will be initialized (if the constructor isn't deleted), we just don't know
4589 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004590 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004591 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004592
4593 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004594 if (Ctor && ClassDecl->getNumVBases())
4595 return false;
4596
4597 // C++1y [class.copy]p26:
4598 // -- [the class] is a literal type, and
4599 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004600 return false;
4601
4602 // -- every constructor involved in initializing [...] base class
4603 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004604 // -- the assignment operator selected to copy/move each direct base
4605 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004606 for (const auto &B : ClassDecl->bases()) {
4607 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004608 if (!BaseType) continue;
4609
4610 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004611 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004612 return false;
4613 }
4614
4615 // -- every constructor involved in initializing non-static data members
4616 // [...] shall be a constexpr constructor;
4617 // -- every non-static data member and base class sub-object shall be
4618 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004619 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004620 // thereof), the assignment operator selected to copy/move that member is
4621 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004622 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004623 if (F->isInvalidDecl())
4624 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004625 QualType BaseType = S.Context.getBaseElementType(F->getType());
4626 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004627 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004628 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4629 BaseType.getCVRQualifiers(),
4630 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004631 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004632 }
4633 }
4634
4635 // All OK, it's constexpr!
4636 return true;
4637}
4638
Richard Smithd3b5c9082012-07-27 04:22:15 +00004639static Sema::ImplicitExceptionSpecification
4640computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4641 switch (S.getSpecialMember(MD)) {
4642 case Sema::CXXDefaultConstructor:
4643 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4644 case Sema::CXXCopyConstructor:
4645 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4646 case Sema::CXXCopyAssignment:
4647 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4648 case Sema::CXXMoveConstructor:
4649 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4650 case Sema::CXXMoveAssignment:
4651 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4652 case Sema::CXXDestructor:
4653 return S.ComputeDefaultedDtorExceptionSpec(MD);
4654 case Sema::CXXInvalid:
4655 break;
4656 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004657 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4658 "only special members have implicit exception specs");
4659 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004660}
4661
Reid Kleckner78af0702013-08-27 23:08:25 +00004662static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4663 CXXMethodDecl *MD) {
4664 FunctionProtoType::ExtProtoInfo EPI;
4665
4666 // Build an exception specification pointing back at this member.
4667 EPI.ExceptionSpecType = EST_Unevaluated;
4668 EPI.ExceptionSpecDecl = MD;
4669
4670 // Set the calling convention to the default for C++ instance methods.
4671 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4672 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4673 /*IsCXXMethod=*/true));
4674 return EPI;
4675}
4676
Richard Smithd3b5c9082012-07-27 04:22:15 +00004677void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4678 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4679 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4680 return;
4681
Richard Smith7f782272012-07-30 23:48:14 +00004682 // Evaluate the exception specification.
4683 ImplicitExceptionSpecification ExceptSpec =
4684 computeImplicitExceptionSpec(*this, Loc, MD);
4685
Richard Smith564417a2014-03-20 21:47:22 +00004686 FunctionProtoType::ExtProtoInfo EPI;
4687 ExceptSpec.getEPI(EPI);
4688
Richard Smith7f782272012-07-30 23:48:14 +00004689 // Update the type of the special member to use it.
Richard Smith564417a2014-03-20 21:47:22 +00004690 UpdateExceptionSpec(MD, EPI);
Richard Smith7f782272012-07-30 23:48:14 +00004691
4692 // A user-provided destructor can be defined outside the class. When that
4693 // happens, be sure to update the exception specification on both
4694 // declarations.
4695 const FunctionProtoType *CanonicalFPT =
4696 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4697 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith564417a2014-03-20 21:47:22 +00004698 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004699}
4700
Richard Smithb9e90b12012-05-15 04:39:51 +00004701void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4702 CXXRecordDecl *RD = MD->getParent();
4703 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004704
Richard Smithb9e90b12012-05-15 04:39:51 +00004705 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4706 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004707
4708 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004709 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004710 bool First = MD == MD->getCanonicalDecl();
4711
4712 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004713
4714 // C++11 [dcl.fct.def.default]p1:
4715 // A function that is explicitly defaulted shall
4716 // -- be a special member function (checked elsewhere),
4717 // -- have the same type (except for ref-qualifiers, and except that a
4718 // copy operation can take a non-const reference) as an implicit
4719 // declaration, and
4720 // -- not have default arguments.
4721 unsigned ExpectedParams = 1;
4722 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4723 ExpectedParams = 0;
4724 if (MD->getNumParams() != ExpectedParams) {
4725 // This also checks for default arguments: a copy or move constructor with a
4726 // default argument is classified as a default constructor, and assignment
4727 // operations and destructors can't have default arguments.
4728 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4729 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004730 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004731 } else if (MD->isVariadic()) {
4732 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4733 << CSM << MD->getSourceRange();
4734 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004735 }
4736
Richard Smithb9e90b12012-05-15 04:39:51 +00004737 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004738
Richard Smithb5800092012-06-10 05:43:50 +00004739 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004740 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004741 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004742 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004743 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004744
Richard Smithb9e90b12012-05-15 04:39:51 +00004745 QualType ReturnType = Context.VoidTy;
4746 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4747 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004748 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004749 QualType ExpectedReturnType =
4750 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4751 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4752 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4753 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4754 HadError = true;
4755 }
4756
4757 // A defaulted special member cannot have cv-qualifiers.
4758 if (Type->getTypeQuals()) {
4759 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004760 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004761 HadError = true;
4762 }
4763 }
4764
4765 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004766 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004767 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004768 if (ExpectedParams && ArgType->isReferenceType()) {
4769 // Argument must be reference to possibly-const T.
4770 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004771 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004772
4773 if (ReferentType.isVolatileQualified()) {
4774 Diag(MD->getLocation(),
4775 diag::err_defaulted_special_member_volatile_param) << CSM;
4776 HadError = true;
4777 }
4778
Richard Smithb5800092012-06-10 05:43:50 +00004779 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004780 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4781 Diag(MD->getLocation(),
4782 diag::err_defaulted_special_member_copy_const_param)
4783 << (CSM == CXXCopyAssignment);
4784 // FIXME: Explain why this special member can't be const.
4785 } else {
4786 Diag(MD->getLocation(),
4787 diag::err_defaulted_special_member_move_const_param)
4788 << (CSM == CXXMoveAssignment);
4789 }
4790 HadError = true;
4791 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004792 } else if (ExpectedParams) {
4793 // A copy assignment operator can take its argument by value, but a
4794 // defaulted one cannot.
4795 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004796 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004797 HadError = true;
4798 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004799
Richard Smithcc36f692011-12-22 02:22:31 +00004800 // C++11 [dcl.fct.def.default]p2:
4801 // An explicitly-defaulted function may be declared constexpr only if it
4802 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004803 // Do not apply this rule to members of class templates, since core issue 1358
4804 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004805 // functions which cannot be constexpr (for non-constructors in C++11 and for
4806 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004807 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4808 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004809 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4810 : isa<CXXConstructorDecl>(MD)) &&
4811 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004812 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4813 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004814 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004815 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004816 }
Richard Smithbd305122012-12-11 01:14:52 +00004817
Richard Smithcc36f692011-12-22 02:22:31 +00004818 // and may have an explicit exception-specification only if it is compatible
4819 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004820 if (Type->hasExceptionSpec()) {
4821 // Delay the check if this is the first declaration of the special member,
4822 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004823 if (First) {
4824 // If the exception specification needs to be instantiated, do so now,
4825 // before we clobber it with an EST_Unevaluated specification below.
4826 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4827 InstantiateExceptionSpec(MD->getLocStart(), MD);
4828 Type = MD->getType()->getAs<FunctionProtoType>();
4829 }
Richard Smithbd305122012-12-11 01:14:52 +00004830 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004831 } else
Richard Smithbd305122012-12-11 01:14:52 +00004832 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4833 }
Richard Smithcc36f692011-12-22 02:22:31 +00004834
4835 // If a function is explicitly defaulted on its first declaration,
4836 if (First) {
4837 // -- it is implicitly considered to be constexpr if the implicit
4838 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004839 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004840
Richard Smithb9e90b12012-05-15 04:39:51 +00004841 // -- it is implicitly considered to have the same exception-specification
4842 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004843 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4844 EPI.ExceptionSpecType = EST_Unevaluated;
4845 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004846 MD->setType(Context.getFunctionType(ReturnType,
4847 ArrayRef<QualType>(&ArgType,
4848 ExpectedParams),
4849 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004850 }
4851
Richard Smithb9e90b12012-05-15 04:39:51 +00004852 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004853 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004854 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004855 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004856 // C++11 [dcl.fct.def.default]p4:
4857 // [For a] user-provided explicitly-defaulted function [...] if such a
4858 // function is implicitly defined as deleted, the program is ill-formed.
4859 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00004860 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00004861 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004862 }
4863 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004864
Richard Smithb9e90b12012-05-15 04:39:51 +00004865 if (HadError)
4866 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004867}
4868
Richard Smithbd305122012-12-11 01:14:52 +00004869/// Check whether the exception specification provided for an
4870/// explicitly-defaulted special member matches the exception specification
4871/// that would have been generated for an implicit special member, per
4872/// C++11 [dcl.fct.def.default]p2.
4873void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4874 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4875 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004876 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4877 /*IsCXXMethod=*/true);
4878 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004879 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4880 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004881 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004882
4883 // Ensure that it matches.
4884 CheckEquivalentExceptionSpec(
4885 PDiag(diag::err_incorrect_defaulted_exception_spec)
4886 << getSpecialMember(MD), PDiag(),
4887 ImplicitType, SourceLocation(),
4888 SpecifiedType, MD->getLocation());
4889}
4890
Alp Tokerae3a9442013-10-18 05:54:19 +00004891void Sema::CheckDelayedMemberExceptionSpecs() {
4892 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4893 2> Checks;
4894 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00004895
Alp Tokerae3a9442013-10-18 05:54:19 +00004896 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4897 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4898
4899 // Perform any deferred checking of exception specifications for virtual
4900 // destructors.
4901 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4902 const CXXDestructorDecl *Dtor = Checks[i].first;
4903 assert(!Dtor->getParent()->isDependentType() &&
4904 "Should not ever add destructors of templates into the list.");
4905 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4906 }
4907
4908 // Check that any explicitly-defaulted methods have exception specifications
4909 // compatible with their implicit exception specifications.
4910 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4911 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4912 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00004913}
4914
Richard Smithd951a1d2012-02-18 02:02:13 +00004915namespace {
4916struct SpecialMemberDeletionInfo {
4917 Sema &S;
4918 CXXMethodDecl *MD;
4919 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004920 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004921
4922 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00004923 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00004924 SourceLocation Loc;
4925
4926 bool AllFieldsAreConst;
4927
4928 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004929 Sema::CXXSpecialMember CSM, bool Diagnose)
4930 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004931 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00004932 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00004933 AllFieldsAreConst(true) {
4934 switch (CSM) {
4935 case Sema::CXXDefaultConstructor:
4936 case Sema::CXXCopyConstructor:
4937 IsConstructor = true;
4938 break;
4939 case Sema::CXXMoveConstructor:
4940 IsConstructor = true;
4941 IsMove = true;
4942 break;
4943 case Sema::CXXCopyAssignment:
4944 IsAssignment = true;
4945 break;
4946 case Sema::CXXMoveAssignment:
4947 IsAssignment = true;
4948 IsMove = true;
4949 break;
4950 case Sema::CXXDestructor:
4951 break;
4952 case Sema::CXXInvalid:
4953 llvm_unreachable("invalid special member kind");
4954 }
4955
4956 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00004957 if (const ReferenceType *RT =
4958 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
4959 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00004960 }
4961 }
4962
4963 bool inUnion() const { return MD->getParent()->isUnion(); }
4964
4965 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00004966 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00004967 unsigned Quals, bool IsMutable) {
4968 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
4969 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00004970 }
4971
Richard Smith852265f2012-03-30 20:53:28 +00004972 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00004973
Richard Smith852265f2012-03-30 20:53:28 +00004974 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00004975 bool shouldDeleteForField(FieldDecl *FD);
4976 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00004977
Richard Smithaf136f82012-07-18 03:51:16 +00004978 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4979 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00004980 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4981 Sema::SpecialMemberOverloadResult *SMOR,
4982 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00004983
4984 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00004985};
4986}
4987
John McCalld4274212012-04-09 20:53:23 +00004988/// Is the given special member inaccessible when used on the given
4989/// sub-object.
4990bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4991 CXXMethodDecl *target) {
4992 /// If we're operating on a base class, the object type is the
4993 /// type of this special member.
4994 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004995 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00004996 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4997 objectTy = S.Context.getTypeDeclType(MD->getParent());
4998 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4999
5000 // If we're operating on a field, the object type is the type of the field.
5001 } else {
5002 objectTy = S.Context.getTypeDeclType(target->getParent());
5003 }
5004
5005 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5006}
5007
Richard Smith852265f2012-03-30 20:53:28 +00005008/// Check whether we should delete a special member due to the implicit
5009/// definition containing a call to a special member of a subobject.
5010bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5011 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5012 bool IsDtorCallInCtor) {
5013 CXXMethodDecl *Decl = SMOR->getMethod();
5014 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5015
5016 int DiagKind = -1;
5017
5018 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5019 DiagKind = !Decl ? 0 : 1;
5020 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5021 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005022 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005023 DiagKind = 3;
5024 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5025 !Decl->isTrivial()) {
5026 // A member of a union must have a trivial corresponding special member.
5027 // As a weird special case, a destructor call from a union's constructor
5028 // must be accessible and non-deleted, but need not be trivial. Such a
5029 // destructor is never actually called, but is semantically checked as
5030 // if it were.
5031 DiagKind = 4;
5032 }
5033
5034 if (DiagKind == -1)
5035 return false;
5036
5037 if (Diagnose) {
5038 if (Field) {
5039 S.Diag(Field->getLocation(),
5040 diag::note_deleted_special_member_class_subobject)
5041 << CSM << MD->getParent() << /*IsField*/true
5042 << Field << DiagKind << IsDtorCallInCtor;
5043 } else {
5044 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5045 S.Diag(Base->getLocStart(),
5046 diag::note_deleted_special_member_class_subobject)
5047 << CSM << MD->getParent() << /*IsField*/false
5048 << Base->getType() << DiagKind << IsDtorCallInCtor;
5049 }
5050
5051 if (DiagKind == 1)
5052 S.NoteDeletedFunction(Decl);
5053 // FIXME: Explain inaccessibility if DiagKind == 3.
5054 }
5055
5056 return true;
5057}
5058
Richard Smith921bd202012-02-26 09:11:52 +00005059/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005060/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005061bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005062 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005063 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005064 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005065
5066 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005067 // -- any direct or virtual base class, or non-static data member with no
5068 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005069 // either M has no default constructor or overload resolution as applied
5070 // to M's default constructor results in an ambiguity or in a function
5071 // that is deleted or inaccessible
5072 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5073 // -- a direct or virtual base class B that cannot be copied/moved because
5074 // overload resolution, as applied to B's corresponding special member,
5075 // results in an ambiguity or a function that is deleted or inaccessible
5076 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005077 // C++11 [class.dtor]p5:
5078 // -- any direct or virtual base class [...] has a type with a destructor
5079 // that is deleted or inaccessible
5080 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005081 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005082 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5083 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005084 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005085
Richard Smith852265f2012-03-30 20:53:28 +00005086 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5087 // -- any direct or virtual base class or non-static data member has a
5088 // type with a destructor that is deleted or inaccessible
5089 if (IsConstructor) {
5090 Sema::SpecialMemberOverloadResult *SMOR =
5091 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5092 false, false, false, false, false);
5093 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5094 return true;
5095 }
5096
Richard Smith921bd202012-02-26 09:11:52 +00005097 return false;
5098}
5099
5100/// Check whether we should delete a special member function due to the class
5101/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005102bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005103 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005104 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005105}
5106
5107/// Check whether we should delete a special member function due to the class
5108/// having a particular non-static data member.
5109bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5110 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5111 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5112
5113 if (CSM == Sema::CXXDefaultConstructor) {
5114 // For a default constructor, all references must be initialized in-class
5115 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005116 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5117 if (Diagnose)
5118 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5119 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005120 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005121 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005122 // C++11 [class.ctor]p5: any non-variant non-static data member of
5123 // const-qualified type (or array thereof) with no
5124 // brace-or-equal-initializer does not have a user-provided default
5125 // constructor.
5126 if (!inUnion() && FieldType.isConstQualified() &&
5127 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005128 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5129 if (Diagnose)
5130 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005131 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005132 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005133 }
5134
5135 if (inUnion() && !FieldType.isConstQualified())
5136 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005137 } else if (CSM == Sema::CXXCopyConstructor) {
5138 // For a copy constructor, data members must not be of rvalue reference
5139 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005140 if (FieldType->isRValueReferenceType()) {
5141 if (Diagnose)
5142 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5143 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005144 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005145 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005146 } else if (IsAssignment) {
5147 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005148 if (FieldType->isReferenceType()) {
5149 if (Diagnose)
5150 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5151 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005152 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005153 }
5154 if (!FieldRecord && FieldType.isConstQualified()) {
5155 // C++11 [class.copy]p23:
5156 // -- a non-static data member of const non-class type (or array thereof)
5157 if (Diagnose)
5158 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005159 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005160 return true;
5161 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005162 }
5163
5164 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005165 // Some additional restrictions exist on the variant members.
5166 if (!inUnion() && FieldRecord->isUnion() &&
5167 FieldRecord->isAnonymousStructOrUnion()) {
5168 bool AllVariantFieldsAreConst = true;
5169
Richard Smith5704fe82012-03-29 19:00:10 +00005170 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005171 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005172 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005173
5174 if (!UnionFieldType.isConstQualified())
5175 AllVariantFieldsAreConst = false;
5176
Richard Smith921bd202012-02-26 09:11:52 +00005177 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5178 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005179 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005180 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005181 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005182 }
5183
5184 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005185 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005186 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005187 if (Diagnose)
5188 S.Diag(FieldRecord->getLocation(),
5189 diag::note_deleted_default_ctor_all_const)
5190 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005191 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005192 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005193
Richard Smith5704fe82012-03-29 19:00:10 +00005194 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005195 // This is technically non-conformant, but sanity demands it.
5196 return false;
5197 }
5198
Richard Smithaf136f82012-07-18 03:51:16 +00005199 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5200 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005201 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005202 }
5203
5204 return false;
5205}
5206
5207/// C++11 [class.ctor] p5:
5208/// A defaulted default constructor for a class X is defined as deleted if
5209/// X is a union and all of its variant members are of const-qualified type.
5210bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005211 // This is a silly definition, because it gives an empty union a deleted
5212 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005213 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005214 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005215 if (Diagnose)
5216 S.Diag(MD->getParent()->getLocation(),
5217 diag::note_deleted_default_ctor_all_const)
5218 << MD->getParent() << /*not anonymous union*/0;
5219 return true;
5220 }
5221 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005222}
5223
5224/// Determine whether a defaulted special member function should be defined as
5225/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5226/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005227bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5228 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005229 if (MD->isInvalidDecl())
5230 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005231 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005232 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005233 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005234 return false;
5235
Richard Smithd951a1d2012-02-18 02:02:13 +00005236 // C++11 [expr.lambda.prim]p19:
5237 // The closure type associated with a lambda-expression has a
5238 // deleted (8.4.3) default constructor and a deleted copy
5239 // assignment operator.
5240 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005241 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5242 if (Diagnose)
5243 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005244 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005245 }
5246
Richard Smith6f1e2c62012-04-02 20:59:25 +00005247 // For an anonymous struct or union, the copy and assignment special members
5248 // will never be used, so skip the check. For an anonymous union declared at
5249 // namespace scope, the constructor and destructor are used.
5250 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5251 RD->isAnonymousStructOrUnion())
5252 return false;
5253
Richard Smith852265f2012-03-30 20:53:28 +00005254 // C++11 [class.copy]p7, p18:
5255 // If the class definition declares a move constructor or move assignment
5256 // operator, an implicitly declared copy constructor or copy assignment
5257 // operator is defined as deleted.
5258 if (MD->isImplicit() &&
5259 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5260 CXXMethodDecl *UserDeclaredMove = 0;
5261
5262 // In Microsoft mode, a user-declared move only causes the deletion of the
5263 // corresponding copy operation, not both copy operations.
5264 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005265 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005266 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005267
5268 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005269 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005270 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005271 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005272 break;
5273 }
5274 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005275 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005276 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005277 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005278 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005279
5280 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005281 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005282 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005283 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005284 break;
5285 }
5286 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005287 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005288 }
5289
5290 if (UserDeclaredMove) {
5291 Diag(UserDeclaredMove->getLocation(),
5292 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005293 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005294 << UserDeclaredMove->isMoveAssignmentOperator();
5295 return true;
5296 }
5297 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005298
Richard Smith6f1e2c62012-04-02 20:59:25 +00005299 // Do access control from the special member function
5300 ContextRAII MethodContext(*this, MD);
5301
Richard Smith921bd202012-02-26 09:11:52 +00005302 // C++11 [class.dtor]p5:
5303 // -- for a virtual destructor, lookup of the non-array deallocation function
5304 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005305 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005306 FunctionDecl *OperatorDelete = 0;
5307 DeclarationName Name =
5308 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5309 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005310 OperatorDelete, false)) {
5311 if (Diagnose)
5312 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005313 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005314 }
Richard Smith921bd202012-02-26 09:11:52 +00005315 }
5316
Richard Smith852265f2012-03-30 20:53:28 +00005317 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005318
Aaron Ballman574705e2014-03-13 15:41:46 +00005319 for (auto &BI : RD->bases())
5320 if (!BI.isVirtual() &&
5321 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005322 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005323
Richard Smithd1627032013-07-22 18:06:23 +00005324 // Per DR1611, do not consider virtual bases of constructors of abstract
5325 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005326 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005327 for (auto &BI : RD->vbases())
5328 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005329 return true;
5330 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005331
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005332 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005333 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005334 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005335 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005336
Richard Smithd951a1d2012-02-18 02:02:13 +00005337 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005338 return true;
5339
5340 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005341}
5342
Richard Smith92f241f2012-12-08 02:53:02 +00005343/// Perform lookup for a special member of the specified kind, and determine
5344/// whether it is trivial. If the triviality can be determined without the
5345/// lookup, skip it. This is intended for use when determining whether a
5346/// special member of a containing object is trivial, and thus does not ever
5347/// perform overload resolution for default constructors.
5348///
5349/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5350/// member that was most likely to be intended to be trivial, if any.
5351static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5352 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005353 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005354 if (Selected)
5355 *Selected = 0;
5356
5357 switch (CSM) {
5358 case Sema::CXXInvalid:
5359 llvm_unreachable("not a special member");
5360
5361 case Sema::CXXDefaultConstructor:
5362 // C++11 [class.ctor]p5:
5363 // A default constructor is trivial if:
5364 // - all the [direct subobjects] have trivial default constructors
5365 //
5366 // Note, no overload resolution is performed in this case.
5367 if (RD->hasTrivialDefaultConstructor())
5368 return true;
5369
5370 if (Selected) {
5371 // If there's a default constructor which could have been trivial, dig it
5372 // out. Otherwise, if there's any user-provided default constructor, point
5373 // to that as an example of why there's not a trivial one.
5374 CXXConstructorDecl *DefCtor = 0;
5375 if (RD->needsImplicitDefaultConstructor())
5376 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005377 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005378 if (!CI->isDefaultConstructor())
5379 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005380 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005381 if (!DefCtor->isUserProvided())
5382 break;
5383 }
5384
5385 *Selected = DefCtor;
5386 }
5387
5388 return false;
5389
5390 case Sema::CXXDestructor:
5391 // C++11 [class.dtor]p5:
5392 // A destructor is trivial if:
5393 // - all the direct [subobjects] have trivial destructors
5394 if (RD->hasTrivialDestructor())
5395 return true;
5396
5397 if (Selected) {
5398 if (RD->needsImplicitDestructor())
5399 S.DeclareImplicitDestructor(RD);
5400 *Selected = RD->getDestructor();
5401 }
5402
5403 return false;
5404
5405 case Sema::CXXCopyConstructor:
5406 // C++11 [class.copy]p12:
5407 // A copy constructor is trivial if:
5408 // - the constructor selected to copy each direct [subobject] is trivial
5409 if (RD->hasTrivialCopyConstructor()) {
5410 if (Quals == Qualifiers::Const)
5411 // We must either select the trivial copy constructor or reach an
5412 // ambiguity; no need to actually perform overload resolution.
5413 return true;
5414 } else if (!Selected) {
5415 return false;
5416 }
5417 // In C++98, we are not supposed to perform overload resolution here, but we
5418 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5419 // cases like B as having a non-trivial copy constructor:
5420 // struct A { template<typename T> A(T&); };
5421 // struct B { mutable A a; };
5422 goto NeedOverloadResolution;
5423
5424 case Sema::CXXCopyAssignment:
5425 // C++11 [class.copy]p25:
5426 // A copy assignment operator is trivial if:
5427 // - the assignment operator selected to copy each direct [subobject] is
5428 // trivial
5429 if (RD->hasTrivialCopyAssignment()) {
5430 if (Quals == Qualifiers::Const)
5431 return true;
5432 } else if (!Selected) {
5433 return false;
5434 }
5435 // In C++98, we are not supposed to perform overload resolution here, but we
5436 // treat that as a language defect.
5437 goto NeedOverloadResolution;
5438
5439 case Sema::CXXMoveConstructor:
5440 case Sema::CXXMoveAssignment:
5441 NeedOverloadResolution:
5442 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005443 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005444
5445 // The standard doesn't describe how to behave if the lookup is ambiguous.
5446 // We treat it as not making the member non-trivial, just like the standard
5447 // mandates for the default constructor. This should rarely matter, because
5448 // the member will also be deleted.
5449 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5450 return true;
5451
5452 if (!SMOR->getMethod()) {
5453 assert(SMOR->getKind() ==
5454 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5455 return false;
5456 }
5457
5458 // We deliberately don't check if we found a deleted special member. We're
5459 // not supposed to!
5460 if (Selected)
5461 *Selected = SMOR->getMethod();
5462 return SMOR->getMethod()->isTrivial();
5463 }
5464
5465 llvm_unreachable("unknown special method kind");
5466}
5467
Benjamin Kramer3e350262013-02-15 12:30:38 +00005468static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005469 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005470 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005471 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005472
5473 // Look for constructor templates.
5474 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5475 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5476 if (CXXConstructorDecl *CD =
5477 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5478 return CD;
5479 }
5480
5481 return 0;
5482}
5483
5484/// The kind of subobject we are checking for triviality. The values of this
5485/// enumeration are used in diagnostics.
5486enum TrivialSubobjectKind {
5487 /// The subobject is a base class.
5488 TSK_BaseClass,
5489 /// The subobject is a non-static data member.
5490 TSK_Field,
5491 /// The object is actually the complete object.
5492 TSK_CompleteObject
5493};
5494
5495/// Check whether the special member selected for a given type would be trivial.
5496static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005497 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005498 Sema::CXXSpecialMember CSM,
5499 TrivialSubobjectKind Kind,
5500 bool Diagnose) {
5501 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5502 if (!SubRD)
5503 return true;
5504
5505 CXXMethodDecl *Selected;
5506 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Richard Smith41c35d62013-11-27 03:39:20 +00005507 ConstRHS, Diagnose ? &Selected : 0))
Richard Smith92f241f2012-12-08 02:53:02 +00005508 return true;
5509
5510 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005511 if (ConstRHS)
5512 SubType.addConst();
5513
Richard Smith92f241f2012-12-08 02:53:02 +00005514 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5515 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5516 << Kind << SubType.getUnqualifiedType();
5517 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5518 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5519 } else if (!Selected)
5520 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5521 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5522 else if (Selected->isUserProvided()) {
5523 if (Kind == TSK_CompleteObject)
5524 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5525 << Kind << SubType.getUnqualifiedType() << CSM;
5526 else {
5527 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5528 << Kind << SubType.getUnqualifiedType() << CSM;
5529 S.Diag(Selected->getLocation(), diag::note_declared_at);
5530 }
5531 } else {
5532 if (Kind != TSK_CompleteObject)
5533 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5534 << Kind << SubType.getUnqualifiedType() << CSM;
5535
5536 // Explain why the defaulted or deleted special member isn't trivial.
5537 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5538 }
5539 }
5540
5541 return false;
5542}
5543
5544/// Check whether the members of a class type allow a special member to be
5545/// trivial.
5546static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5547 Sema::CXXSpecialMember CSM,
5548 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005549 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005550 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5551 continue;
5552
5553 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5554
5555 // Pretend anonymous struct or union members are members of this class.
5556 if (FI->isAnonymousStructOrUnion()) {
5557 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5558 CSM, ConstArg, Diagnose))
5559 return false;
5560 continue;
5561 }
5562
5563 // C++11 [class.ctor]p5:
5564 // A default constructor is trivial if [...]
5565 // -- no non-static data member of its class has a
5566 // brace-or-equal-initializer
5567 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5568 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005569 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005570 return false;
5571 }
5572
5573 // Objective C ARC 4.3.5:
5574 // [...] nontrivally ownership-qualified types are [...] not trivially
5575 // default constructible, copy constructible, move constructible, copy
5576 // assignable, move assignable, or destructible [...]
5577 if (S.getLangOpts().ObjCAutoRefCount &&
5578 FieldType.hasNonTrivialObjCLifetime()) {
5579 if (Diagnose)
5580 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5581 << RD << FieldType.getObjCLifetime();
5582 return false;
5583 }
5584
Richard Smith41c35d62013-11-27 03:39:20 +00005585 bool ConstRHS = ConstArg && !FI->isMutable();
5586 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5587 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005588 return false;
5589 }
5590
5591 return true;
5592}
5593
5594/// Diagnose why the specified class does not have a trivial special member of
5595/// the given kind.
5596void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5597 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005598
Richard Smith41c35d62013-11-27 03:39:20 +00005599 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5600 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005601 TSK_CompleteObject, /*Diagnose*/true);
5602}
5603
5604/// Determine whether a defaulted or deleted special member function is trivial,
5605/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5606/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5607bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5608 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005609 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5610
5611 CXXRecordDecl *RD = MD->getParent();
5612
5613 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005614
Richard Smith2002bfe2013-11-04 02:02:27 +00005615 // C++11 [class.copy]p12, p25: [DR1593]
5616 // A [special member] is trivial if [...] its parameter-type-list is
5617 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005618 switch (CSM) {
5619 case CXXDefaultConstructor:
5620 case CXXDestructor:
5621 // Trivial default constructors and destructors cannot have parameters.
5622 break;
5623
5624 case CXXCopyConstructor:
5625 case CXXCopyAssignment: {
5626 // Trivial copy operations always have const, non-volatile parameter types.
5627 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005628 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005629 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5630 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5631 if (Diagnose)
5632 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5633 << Param0->getSourceRange() << Param0->getType()
5634 << Context.getLValueReferenceType(
5635 Context.getRecordType(RD).withConst());
5636 return false;
5637 }
5638 break;
5639 }
5640
5641 case CXXMoveConstructor:
5642 case CXXMoveAssignment: {
5643 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005644 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005645 const RValueReferenceType *RT =
5646 Param0->getType()->getAs<RValueReferenceType>();
5647 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5648 if (Diagnose)
5649 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5650 << Param0->getSourceRange() << Param0->getType()
5651 << Context.getRValueReferenceType(Context.getRecordType(RD));
5652 return false;
5653 }
5654 break;
5655 }
5656
5657 case CXXInvalid:
5658 llvm_unreachable("not a special member");
5659 }
5660
Richard Smith92f241f2012-12-08 02:53:02 +00005661 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5662 if (Diagnose)
5663 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5664 diag::note_nontrivial_default_arg)
5665 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5666 return false;
5667 }
5668 if (MD->isVariadic()) {
5669 if (Diagnose)
5670 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5671 return false;
5672 }
5673
5674 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5675 // A copy/move [constructor or assignment operator] is trivial if
5676 // -- the [member] selected to copy/move each direct base class subobject
5677 // is trivial
5678 //
5679 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5680 // A [default constructor or destructor] is trivial if
5681 // -- all the direct base classes have trivial [default constructors or
5682 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005683 for (const auto &BI : RD->bases())
5684 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005685 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005686 return false;
5687
5688 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5689 // A copy/move [constructor or assignment operator] for a class X is
5690 // trivial if
5691 // -- for each non-static data member of X that is of class type (or array
5692 // thereof), the constructor selected to copy/move that member is
5693 // trivial
5694 //
5695 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5696 // A [default constructor or destructor] is trivial if
5697 // -- for all of the non-static data members of its class that are of class
5698 // type (or array thereof), each such class has a trivial [default
5699 // constructor or destructor]
5700 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5701 return false;
5702
5703 // C++11 [class.dtor]p5:
5704 // A destructor is trivial if [...]
5705 // -- the destructor is not virtual
5706 if (CSM == CXXDestructor && MD->isVirtual()) {
5707 if (Diagnose)
5708 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5709 return false;
5710 }
5711
5712 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5713 // A [special member] for class X is trivial if [...]
5714 // -- class X has no virtual functions and no virtual base classes
5715 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5716 if (!Diagnose)
5717 return false;
5718
5719 if (RD->getNumVBases()) {
5720 // Check for virtual bases. We already know that the corresponding
5721 // member in all bases is trivial, so vbases must all be direct.
5722 CXXBaseSpecifier &BS = *RD->vbases_begin();
5723 assert(BS.isVirtual());
5724 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5725 return false;
5726 }
5727
5728 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005729 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005730 if (MI->isVirtual()) {
5731 SourceLocation MLoc = MI->getLocStart();
5732 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5733 return false;
5734 }
5735 }
5736
5737 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5738 }
5739
5740 // Looks like it's trivial!
5741 return true;
5742}
5743
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005744/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005745namespace {
5746 struct FindHiddenVirtualMethodData {
5747 Sema *S;
5748 CXXMethodDecl *Method;
5749 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005750 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005751 };
5752}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005753
David Blaikie282c92a2012-10-19 00:53:08 +00005754/// \brief Check whether any most overriden method from MD in Methods
5755static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5756 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5757 if (MD->size_overridden_methods() == 0)
5758 return Methods.count(MD->getCanonicalDecl());
5759 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5760 E = MD->end_overridden_methods();
5761 I != E; ++I)
5762 if (CheckMostOverridenMethods(*I, Methods))
5763 return true;
5764 return false;
5765}
5766
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005767/// \brief Member lookup function that determines whether a given C++
5768/// method overloads virtual methods in a base class without overriding any,
5769/// to be used with CXXRecordDecl::lookupInBases().
5770static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5771 CXXBasePath &Path,
5772 void *UserData) {
5773 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5774
5775 FindHiddenVirtualMethodData &Data
5776 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5777
5778 DeclarationName Name = Data.Method->getDeclName();
5779 assert(Name.getNameKind() == DeclarationName::Identifier);
5780
5781 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005782 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005783 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005784 !Path.Decls.empty();
5785 Path.Decls = Path.Decls.slice(1)) {
5786 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005787 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005788 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005789 foundSameNameMethod = true;
5790 // Interested only in hidden virtual methods.
5791 if (!MD->isVirtual())
5792 continue;
5793 // If the method we are checking overrides a method from its base
5794 // don't warn about the other overloaded methods.
5795 if (!Data.S->IsOverload(Data.Method, MD, false))
5796 return true;
5797 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005798 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005799 overloadedMethods.push_back(MD);
5800 }
5801 }
5802
5803 if (foundSameNameMethod)
5804 Data.OverloadedMethods.append(overloadedMethods.begin(),
5805 overloadedMethods.end());
5806 return foundSameNameMethod;
5807}
5808
David Blaikie282c92a2012-10-19 00:53:08 +00005809/// \brief Add the most overriden methods from MD to Methods
5810static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5811 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5812 if (MD->size_overridden_methods() == 0)
5813 Methods.insert(MD->getCanonicalDecl());
5814 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5815 E = MD->end_overridden_methods();
5816 I != E; ++I)
5817 AddMostOverridenMethods(*I, Methods);
5818}
5819
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005820/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005821/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005822void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5823 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005824 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005825 return;
5826
5827 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5828 /*bool RecordPaths=*/false,
5829 /*bool DetectVirtual=*/false);
5830 FindHiddenVirtualMethodData Data;
5831 Data.Method = MD;
5832 Data.S = this;
5833
5834 // Keep the base methods that were overriden or introduced in the subclass
5835 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005836 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005837 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5838 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5839 NamedDecl *ND = *I;
5840 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005841 ND = shad->getTargetDecl();
5842 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5843 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005844 }
5845
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005846 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5847 OverloadedMethods = Data.OverloadedMethods;
5848}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005849
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005850void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5851 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5852 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5853 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5854 PartialDiagnostic PD = PDiag(
5855 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5856 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5857 Diag(overloadedMD->getLocation(), PD);
5858 }
5859}
5860
5861/// \brief Diagnose methods which overload virtual methods in a base class
5862/// without overriding any.
5863void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5864 if (MD->isInvalidDecl())
5865 return;
5866
5867 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5868 MD->getLocation()) == DiagnosticsEngine::Ignored)
5869 return;
5870
5871 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5872 FindHiddenVirtualMethods(MD, OverloadedMethods);
5873 if (!OverloadedMethods.empty()) {
5874 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5875 << MD << (OverloadedMethods.size() > 1);
5876
5877 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005878 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005879}
5880
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005881void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005882 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005883 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005884 SourceLocation RBrac,
5885 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005886 if (!TagDecl)
5887 return;
Mike Stump11289f42009-09-09 15:08:12 +00005888
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005889 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005890
Rafael Espindola06e1b132012-07-12 04:32:30 +00005891 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5892 if (l->getKind() != AttributeList::AT_Visibility)
5893 continue;
5894 l->setInvalid();
5895 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5896 l->getName();
5897 }
5898
David Blaikie751c5582011-09-22 02:58:26 +00005899 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005900 // strict aliasing violation!
5901 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005902 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005903
Douglas Gregor0be31a22010-07-02 17:43:08 +00005904 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005905 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005906}
5907
Douglas Gregor05379422008-11-03 17:51:48 +00005908/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5909/// special functions, such as the default constructor, copy
5910/// constructor, or destructor, to the given C++ class (C++
5911/// [special]p1). This routine can only be executed just before the
5912/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005913void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005914 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005915 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005916
Richard Smith6b02d462012-12-08 08:32:28 +00005917 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005918 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005919
Richard Smith6b02d462012-12-08 08:32:28 +00005920 // If the properties or semantics of the copy constructor couldn't be
5921 // determined while the class was being declared, force a declaration
5922 // of it now.
5923 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5924 DeclareImplicitCopyConstructor(ClassDecl);
5925 }
5926
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005927 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005928 ++ASTContext::NumImplicitMoveConstructors;
5929
Richard Smith6b02d462012-12-08 08:32:28 +00005930 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5931 DeclareImplicitMoveConstructor(ClassDecl);
5932 }
5933
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005934 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5935 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00005936
5937 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005938 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00005939 // it shows up in the right place in the vtable and that we diagnose
5940 // problems with the implicit exception specification.
5941 if (ClassDecl->isDynamicClass() ||
5942 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005943 DeclareImplicitCopyAssignment(ClassDecl);
5944 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005945
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005946 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005947 ++ASTContext::NumImplicitMoveAssignmentOperators;
5948
5949 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00005950 if (ClassDecl->isDynamicClass() ||
5951 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00005952 DeclareImplicitMoveAssignment(ClassDecl);
5953 }
5954
Douglas Gregor7454c562010-07-02 20:37:36 +00005955 if (!ClassDecl->hasUserDeclaredDestructor()) {
5956 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00005957
5958 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00005959 // have to declare the destructor immediately. This ensures that, e.g., it
5960 // shows up in the right place in the vtable and that we diagnose problems
5961 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00005962 if (ClassDecl->isDynamicClass() ||
5963 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00005964 DeclareImplicitDestructor(ClassDecl);
5965 }
Douglas Gregor05379422008-11-03 17:51:48 +00005966}
5967
Francois Pichet1c229c02011-04-22 22:18:13 +00005968void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5969 if (!D)
5970 return;
5971
5972 int NumParamList = D->getNumTemplateParameterLists();
5973 for (int i = 0; i < NumParamList; i++) {
5974 TemplateParameterList* Params = D->getTemplateParameterList(i);
5975 for (TemplateParameterList::iterator Param = Params->begin(),
5976 ParamEnd = Params->end();
5977 Param != ParamEnd; ++Param) {
5978 NamedDecl *Named = cast<NamedDecl>(*Param);
5979 if (Named->getDeclName()) {
5980 S->AddDecl(Named);
5981 IdResolver.AddDecl(Named);
5982 }
5983 }
5984 }
5985}
5986
John McCall48871652010-08-21 09:40:31 +00005987void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00005988 if (!D)
5989 return;
5990
5991 TemplateParameterList *Params = 0;
5992 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5993 Params = Template->getTemplateParameters();
5994 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5995 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5996 Params = PartialSpec->getTemplateParameters();
5997 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005998 return;
5999
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006000 for (TemplateParameterList::iterator Param = Params->begin(),
6001 ParamEnd = Params->end();
6002 Param != ParamEnd; ++Param) {
6003 NamedDecl *Named = cast<NamedDecl>(*Param);
6004 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00006005 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006006 IdResolver.AddDecl(Named);
6007 }
6008 }
6009}
6010
John McCall48871652010-08-21 09:40:31 +00006011void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006012 if (!RecordD) return;
6013 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006014 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006015 PushDeclContext(S, Record);
6016}
6017
John McCall48871652010-08-21 09:40:31 +00006018void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006019 if (!RecordD) return;
6020 PopDeclContext();
6021}
6022
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006023/// This is used to implement the constant expression evaluation part of the
6024/// attribute enable_if extension. There is nothing in standard C++ which would
6025/// require reentering parameters.
6026void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6027 if (!Param)
6028 return;
6029
6030 S->AddDecl(Param);
6031 if (Param->getDeclName())
6032 IdResolver.AddDecl(Param);
6033}
6034
Douglas Gregor4d87df52008-12-16 21:30:33 +00006035/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6036/// parsing a top-level (non-nested) C++ class, and we are now
6037/// parsing those parts of the given Method declaration that could
6038/// not be parsed earlier (C++ [class.mem]p2), such as default
6039/// arguments. This action should enter the scope of the given
6040/// Method declaration as if we had just parsed the qualified method
6041/// name. However, it should not bring the parameters into scope;
6042/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006043void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006044}
6045
6046/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6047/// C++ method declaration. We're (re-)introducing the given
6048/// function parameter into scope for use in parsing later parts of
6049/// the method declaration. For example, we could see an
6050/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006051void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006052 if (!ParamD)
6053 return;
Mike Stump11289f42009-09-09 15:08:12 +00006054
John McCall48871652010-08-21 09:40:31 +00006055 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006056
6057 // If this parameter has an unparsed default argument, clear it out
6058 // to make way for the parsed default argument.
6059 if (Param->hasUnparsedDefaultArg())
6060 Param->setDefaultArg(0);
6061
John McCall48871652010-08-21 09:40:31 +00006062 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006063 if (Param->getDeclName())
6064 IdResolver.AddDecl(Param);
6065}
6066
6067/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6068/// processing the delayed method declaration for Method. The method
6069/// declaration is now considered finished. There may be a separate
6070/// ActOnStartOfFunctionDef action later (not necessarily
6071/// immediately!) for this method, if it was also defined inside the
6072/// class body.
John McCall48871652010-08-21 09:40:31 +00006073void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006074 if (!MethodD)
6075 return;
Mike Stump11289f42009-09-09 15:08:12 +00006076
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006077 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006078
John McCall48871652010-08-21 09:40:31 +00006079 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006080
6081 // Now that we have our default arguments, check the constructor
6082 // again. It could produce additional diagnostics or affect whether
6083 // the class has implicitly-declared destructors, among other
6084 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006085 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6086 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006087
6088 // Check the default arguments, which we may have added.
6089 if (!Method->isInvalidDecl())
6090 CheckCXXDefaultArguments(Method);
6091}
6092
Douglas Gregor831c93f2008-11-05 20:51:48 +00006093/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006094/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006095/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006096/// emit diagnostics and set the invalid bit to true. In any case, the type
6097/// will be updated to reflect a well-formed type for the constructor and
6098/// returned.
6099QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006100 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006101 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006102
6103 // C++ [class.ctor]p3:
6104 // A constructor shall not be virtual (10.3) or static (9.4). A
6105 // constructor can be invoked for a const, volatile or const
6106 // volatile object. A constructor shall not be declared const,
6107 // volatile, or const volatile (9.3.2).
6108 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006109 if (!D.isInvalidType())
6110 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6111 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6112 << SourceRange(D.getIdentifierLoc());
6113 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006114 }
John McCall8e7d6562010-08-26 03:08:43 +00006115 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006116 if (!D.isInvalidType())
6117 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6118 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6119 << SourceRange(D.getIdentifierLoc());
6120 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006121 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006122 }
Mike Stump11289f42009-09-09 15:08:12 +00006123
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006124 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006125 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006126 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006127 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6128 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006129 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006130 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6131 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006132 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006133 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6134 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006135 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006136 }
Mike Stump11289f42009-09-09 15:08:12 +00006137
Douglas Gregordb9d6642011-01-26 05:01:58 +00006138 // C++0x [class.ctor]p4:
6139 // A constructor shall not be declared with a ref-qualifier.
6140 if (FTI.hasRefQualifier()) {
6141 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6142 << FTI.RefQualifierIsLValueRef
6143 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6144 D.setInvalidType();
6145 }
6146
Douglas Gregor831c93f2008-11-05 20:51:48 +00006147 // Rebuild the function type "R" without any type qualifiers (in
6148 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006149 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006150 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006151 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006152 return R;
6153
6154 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6155 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006156 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006157
6158 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006159}
6160
Douglas Gregor4d87df52008-12-16 21:30:33 +00006161/// CheckConstructor - Checks a fully-formed constructor for
6162/// well-formedness, issuing any diagnostics required. Returns true if
6163/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006164void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006165 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006166 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6167 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006168 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006169
6170 // C++ [class.copy]p3:
6171 // A declaration of a constructor for a class X is ill-formed if
6172 // its first parameter is of type (optionally cv-qualified) X and
6173 // either there are no other parameters or else all other
6174 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006175 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006176 ((Constructor->getNumParams() == 1) ||
6177 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006178 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6179 Constructor->getTemplateSpecializationKind()
6180 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006181 QualType ParamType = Constructor->getParamDecl(0)->getType();
6182 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6183 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006184 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006185 const char *ConstRef
6186 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6187 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006188 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006189 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006190
6191 // FIXME: Rather that making the constructor invalid, we should endeavor
6192 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006193 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006194 }
6195 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006196}
6197
John McCalldeb646e2010-08-04 01:04:25 +00006198/// CheckDestructor - Checks a fully-formed destructor definition for
6199/// well-formedness, issuing any diagnostics required. Returns true
6200/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006201bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006202 CXXRecordDecl *RD = Destructor->getParent();
6203
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006204 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006205 SourceLocation Loc;
6206
6207 if (!Destructor->isImplicit())
6208 Loc = Destructor->getLocation();
6209 else
6210 Loc = RD->getLocation();
6211
6212 // If we have a virtual destructor, look up the deallocation function
6213 FunctionDecl *OperatorDelete = 0;
6214 DeclarationName Name =
6215 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006216 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006217 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006218 // If there's no class-specific operator delete, look up the global
6219 // non-array delete.
6220 if (!OperatorDelete)
6221 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006222
Eli Friedmanfa0df832012-02-02 03:46:19 +00006223 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006224
6225 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006226 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006227
6228 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006229}
6230
Mike Stump11289f42009-09-09 15:08:12 +00006231static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00006232FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
Alp Tokerc5350722014-02-26 22:27:52 +00006233 return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6234 FTI.Params[0].Param &&
6235 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00006236}
6237
Douglas Gregor831c93f2008-11-05 20:51:48 +00006238/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6239/// the well-formednes of the destructor declarator @p D with type @p
6240/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006241/// emit diagnostics and set the declarator to invalid. Even if this happens,
6242/// will be updated to reflect a well-formed type for the destructor and
6243/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006244QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006245 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006246 // C++ [class.dtor]p1:
6247 // [...] A typedef-name that names a class is a class-name
6248 // (7.1.3); however, a typedef-name that names a class shall not
6249 // be used as the identifier in the declarator for a destructor
6250 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006251 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006252 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006253 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006254 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006255 else if (const TemplateSpecializationType *TST =
6256 DeclaratorType->getAs<TemplateSpecializationType>())
6257 if (TST->isTypeAlias())
6258 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6259 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006260
6261 // C++ [class.dtor]p2:
6262 // A destructor is used to destroy objects of its class type. A
6263 // destructor takes no parameters, and no return type can be
6264 // specified for it (not even void). The address of a destructor
6265 // shall not be taken. A destructor shall not be static. A
6266 // destructor can be invoked for a const, volatile or const
6267 // volatile object. A destructor shall not be declared const,
6268 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006269 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006270 if (!D.isInvalidType())
6271 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6272 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006273 << SourceRange(D.getIdentifierLoc())
6274 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6275
John McCall8e7d6562010-08-26 03:08:43 +00006276 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006277 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006278 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006279 // Destructors don't have return types, but the parser will
6280 // happily parse something like:
6281 //
6282 // class X {
6283 // float ~X();
6284 // };
6285 //
6286 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006287 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6288 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6289 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006290 }
Mike Stump11289f42009-09-09 15:08:12 +00006291
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006292 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006293 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006294 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006295 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6296 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006297 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006298 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6299 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006300 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006301 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6302 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006303 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006304 }
6305
Douglas Gregordb9d6642011-01-26 05:01:58 +00006306 // C++0x [class.dtor]p2:
6307 // A destructor shall not be declared with a ref-qualifier.
6308 if (FTI.hasRefQualifier()) {
6309 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6310 << FTI.RefQualifierIsLValueRef
6311 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6312 D.setInvalidType();
6313 }
6314
Douglas Gregor831c93f2008-11-05 20:51:48 +00006315 // Make sure we don't have any parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006316 if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006317 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6318
6319 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006320 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006321 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006322 }
6323
Mike Stump11289f42009-09-09 15:08:12 +00006324 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006325 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006326 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006327 D.setInvalidType();
6328 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006329
6330 // Rebuild the function type "R" without any type qualifiers or
6331 // parameters (in case any of the errors above fired) and with
6332 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006333 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006334 if (!D.isInvalidType())
6335 return R;
6336
Douglas Gregor95755162010-07-01 05:10:53 +00006337 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006338 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6339 EPI.Variadic = false;
6340 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006341 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006342 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006343}
6344
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006345/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6346/// well-formednes of the conversion function declarator @p D with
6347/// type @p R. If there are any errors in the declarator, this routine
6348/// will emit diagnostics and return true. Otherwise, it will return
6349/// false. Either way, the type @p R will be updated to reflect a
6350/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006351void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006352 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006353 // C++ [class.conv.fct]p1:
6354 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006355 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006356 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006357 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006358 if (!D.isInvalidType())
6359 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006360 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6361 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006362 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006363 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006364 }
John McCall212fa2e2010-04-13 00:04:31 +00006365
6366 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6367
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006368 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006369 // Conversion functions don't have return types, but the parser will
6370 // happily parse something like:
6371 //
6372 // class X {
6373 // float operator bool();
6374 // };
6375 //
6376 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006377 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6378 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6379 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006380 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006381 }
6382
John McCall212fa2e2010-04-13 00:04:31 +00006383 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6384
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006385 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006386 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006387 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6388
6389 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006390 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006391 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006392 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006393 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006394 D.setInvalidType();
6395 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006396
John McCall212fa2e2010-04-13 00:04:31 +00006397 // Diagnose "&operator bool()" and other such nonsense. This
6398 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006399 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006400 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006401 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006402 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006403 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006404 }
6405
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006406 // C++ [class.conv.fct]p4:
6407 // The conversion-type-id shall not represent a function type nor
6408 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006409 if (ConvType->isArrayType()) {
6410 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6411 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006412 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006413 } else if (ConvType->isFunctionType()) {
6414 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6415 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006416 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006417 }
6418
6419 // Rebuild the function type "R" without any parameters (in case any
6420 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006421 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006422 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006423 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006424
Douglas Gregor5fb53972009-01-14 15:45:31 +00006425 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006426 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006427 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006428 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006429 diag::warn_cxx98_compat_explicit_conversion_functions :
6430 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006431 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006432}
6433
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006434/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6435/// the declaration of the given C++ conversion function. This routine
6436/// is responsible for recording the conversion function in the C++
6437/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006438Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006439 assert(Conversion && "Expected to receive a conversion function declaration");
6440
Douglas Gregor4287b372008-12-12 08:25:50 +00006441 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006442
6443 // Make sure we aren't redeclaring the conversion function.
6444 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006445
6446 // C++ [class.conv.fct]p1:
6447 // [...] A conversion function is never used to convert a
6448 // (possibly cv-qualified) object to the (possibly cv-qualified)
6449 // same object type (or a reference to it), to a (possibly
6450 // cv-qualified) base class of that type (or a reference to it),
6451 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006452 // FIXME: Suppress this warning if the conversion function ends up being a
6453 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006454 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006455 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006456 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006457 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006458 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6459 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006460 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006461 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006462 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6463 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006464 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006465 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006466 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006467 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006468 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006469 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006470 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006471 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006472 }
6473
Douglas Gregor457104e2010-09-29 04:25:11 +00006474 if (FunctionTemplateDecl *ConversionTemplate
6475 = Conversion->getDescribedFunctionTemplate())
6476 return ConversionTemplate;
6477
John McCall48871652010-08-21 09:40:31 +00006478 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006479}
6480
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006481//===----------------------------------------------------------------------===//
6482// Namespace Handling
6483//===----------------------------------------------------------------------===//
6484
Richard Smith45bb8852012-10-04 22:13:39 +00006485/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6486/// reopened.
6487static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6488 SourceLocation Loc,
6489 IdentifierInfo *II, bool *IsInline,
6490 NamespaceDecl *PrevNS) {
6491 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006492
Richard Smithf501cc32012-10-05 01:46:25 +00006493 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6494 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6495 // inline namespaces, with the intention of bringing names into namespace std.
6496 //
6497 // We support this just well enough to get that case working; this is not
6498 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006499 if (*IsInline && II && II->getName().startswith("__atomic") &&
6500 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006501 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006502 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6503 NS = NS->getPreviousDecl())
6504 NS->setInline(*IsInline);
6505 // Patch up the lookup table for the containing namespace. This isn't really
6506 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006507 for (auto *I : PrevNS->decls())
6508 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006509 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6510 return;
6511 }
6512
6513 if (PrevNS->isInline())
6514 // The user probably just forgot the 'inline', so suggest that it
6515 // be added back.
6516 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6517 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6518 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006519 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006520
6521 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6522 *IsInline = PrevNS->isInline();
6523}
John McCallb1be5232010-08-26 09:15:37 +00006524
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006525/// ActOnStartNamespaceDef - This is called at the start of a namespace
6526/// definition.
John McCall48871652010-08-21 09:40:31 +00006527Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006528 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006529 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006530 SourceLocation IdentLoc,
6531 IdentifierInfo *II,
6532 SourceLocation LBrace,
6533 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006534 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6535 // For anonymous namespace, take the location of the left brace.
6536 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006537 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006538 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006539 bool IsStd = false;
6540 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006541 Scope *DeclRegionScope = NamespcScope->getParent();
6542
Douglas Gregore57e7522012-01-07 09:11:48 +00006543 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006544 if (II) {
6545 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006546 // The identifier in an original-namespace-definition shall not
6547 // have been previously defined in the declarative region in
6548 // which the original-namespace-definition appears. The
6549 // identifier in an original-namespace-definition is the name of
6550 // the namespace. Subsequently in that declarative region, it is
6551 // treated as an original-namespace-name.
6552 //
6553 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006554 // look through using directives, just look for any ordinary names.
6555
6556 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006557 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6558 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006559 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006560 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6561 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6562 ++I) {
6563 if ((*I)->getIdentifierNamespace() & IDNS) {
6564 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006565 break;
6566 }
6567 }
6568
Douglas Gregore57e7522012-01-07 09:11:48 +00006569 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6570
6571 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006572 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006573 if (IsInline != PrevNS->isInline())
6574 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6575 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006576 } else if (PrevDecl) {
6577 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006578 Diag(Loc, diag::err_redefinition_different_kind)
6579 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006580 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006581 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006582 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006583 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006584 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006585 // This is the first "real" definition of the namespace "std", so update
6586 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006587 PrevNS = getStdNamespace();
6588 IsStd = true;
6589 AddToKnown = !IsInline;
6590 } else {
6591 // We've seen this namespace for the first time.
6592 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006593 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006594 } else {
John McCall4fa53422009-10-01 00:25:31 +00006595 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006596
6597 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006598 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006599 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006600 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006601 } else {
6602 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006603 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006604 }
6605
Richard Smith45bb8852012-10-04 22:13:39 +00006606 if (PrevNS && IsInline != PrevNS->isInline())
6607 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6608 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006609 }
6610
6611 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6612 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006613 if (IsInvalid)
6614 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006615
6616 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006617
Douglas Gregore57e7522012-01-07 09:11:48 +00006618 // FIXME: Should we be merging attributes?
6619 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006620 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006621
6622 if (IsStd)
6623 StdNamespace = Namespc;
6624 if (AddToKnown)
6625 KnownNamespaces[Namespc] = false;
6626
6627 if (II) {
6628 PushOnScopeChains(Namespc, DeclRegionScope);
6629 } else {
6630 // Link the anonymous namespace into its parent.
6631 DeclContext *Parent = CurContext->getRedeclContext();
6632 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6633 TU->setAnonymousNamespace(Namespc);
6634 } else {
6635 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006636 }
John McCall4fa53422009-10-01 00:25:31 +00006637
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006638 CurContext->addDecl(Namespc);
6639
John McCall4fa53422009-10-01 00:25:31 +00006640 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6641 // behaves as if it were replaced by
6642 // namespace unique { /* empty body */ }
6643 // using namespace unique;
6644 // namespace unique { namespace-body }
6645 // where all occurrences of 'unique' in a translation unit are
6646 // replaced by the same identifier and this identifier differs
6647 // from all other identifiers in the entire program.
6648
6649 // We just create the namespace with an empty name and then add an
6650 // implicit using declaration, just like the standard suggests.
6651 //
6652 // CodeGen enforces the "universally unique" aspect by giving all
6653 // declarations semantically contained within an anonymous
6654 // namespace internal linkage.
6655
Douglas Gregore57e7522012-01-07 09:11:48 +00006656 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006657 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006658 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006659 /* 'using' */ LBrace,
6660 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006661 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006662 /* identifier */ SourceLocation(),
6663 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006664 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006665 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006666 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006667 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006668 }
6669
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006670 ActOnDocumentableDecl(Namespc);
6671
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006672 // Although we could have an invalid decl (i.e. the namespace name is a
6673 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006674 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6675 // for the namespace has the declarations that showed up in that particular
6676 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006677 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006678 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006679}
6680
Sebastian Redla6602e92009-11-23 15:34:23 +00006681/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6682/// is a namespace alias, returns the namespace it points to.
6683static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6684 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6685 return AD->getNamespace();
6686 return dyn_cast_or_null<NamespaceDecl>(D);
6687}
6688
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006689/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6690/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006691void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006692 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6693 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006694 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006695 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006696 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006697 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006698}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006699
John McCall28a0cf72010-08-25 07:42:41 +00006700CXXRecordDecl *Sema::getStdBadAlloc() const {
6701 return cast_or_null<CXXRecordDecl>(
6702 StdBadAlloc.get(Context.getExternalSource()));
6703}
6704
6705NamespaceDecl *Sema::getStdNamespace() const {
6706 return cast_or_null<NamespaceDecl>(
6707 StdNamespace.get(Context.getExternalSource()));
6708}
6709
Douglas Gregorcdf87022010-06-29 17:53:46 +00006710/// \brief Retrieve the special "std" namespace, which may require us to
6711/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006712NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006713 if (!StdNamespace) {
6714 // The "std" namespace has not yet been defined, so build one implicitly.
6715 StdNamespace = NamespaceDecl::Create(Context,
6716 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006717 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006718 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006719 &PP.getIdentifierTable().get("std"),
6720 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006721 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006722 }
6723
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006724 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006725}
6726
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006727bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006728 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006729 "Looking for std::initializer_list outside of C++.");
6730
6731 // We're looking for implicit instantiations of
6732 // template <typename E> class std::initializer_list.
6733
6734 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6735 return false;
6736
Sebastian Redl43144e72012-01-17 22:49:58 +00006737 ClassTemplateDecl *Template = 0;
6738 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006739
Sebastian Redl43144e72012-01-17 22:49:58 +00006740 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006741
Sebastian Redl43144e72012-01-17 22:49:58 +00006742 ClassTemplateSpecializationDecl *Specialization =
6743 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6744 if (!Specialization)
6745 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006746
Sebastian Redl43144e72012-01-17 22:49:58 +00006747 Template = Specialization->getSpecializedTemplate();
6748 Arguments = Specialization->getTemplateArgs().data();
6749 } else if (const TemplateSpecializationType *TST =
6750 Ty->getAs<TemplateSpecializationType>()) {
6751 Template = dyn_cast_or_null<ClassTemplateDecl>(
6752 TST->getTemplateName().getAsTemplateDecl());
6753 Arguments = TST->getArgs();
6754 }
6755 if (!Template)
6756 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006757
6758 if (!StdInitializerList) {
6759 // Haven't recognized std::initializer_list yet, maybe this is it.
6760 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6761 if (TemplateClass->getIdentifier() !=
6762 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006763 !getStdNamespace()->InEnclosingNamespaceSetOf(
6764 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006765 return false;
6766 // This is a template called std::initializer_list, but is it the right
6767 // template?
6768 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006769 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006770 return false;
6771 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6772 return false;
6773
6774 // It's the right template.
6775 StdInitializerList = Template;
6776 }
6777
6778 if (Template != StdInitializerList)
6779 return false;
6780
6781 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006782 if (Element)
6783 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006784 return true;
6785}
6786
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006787static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6788 NamespaceDecl *Std = S.getStdNamespace();
6789 if (!Std) {
6790 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6791 return 0;
6792 }
6793
6794 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6795 Loc, Sema::LookupOrdinaryName);
6796 if (!S.LookupQualifiedName(Result, Std)) {
6797 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6798 return 0;
6799 }
6800 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6801 if (!Template) {
6802 Result.suppressDiagnostics();
6803 // We found something weird. Complain about the first thing we found.
6804 NamedDecl *Found = *Result.begin();
6805 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6806 return 0;
6807 }
6808
6809 // We found some template called std::initializer_list. Now verify that it's
6810 // correct.
6811 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006812 if (Params->getMinRequiredArguments() != 1 ||
6813 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006814 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6815 return 0;
6816 }
6817
6818 return Template;
6819}
6820
6821QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6822 if (!StdInitializerList) {
6823 StdInitializerList = LookupStdInitializerList(*this, Loc);
6824 if (!StdInitializerList)
6825 return QualType();
6826 }
6827
6828 TemplateArgumentListInfo Args(Loc, Loc);
6829 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6830 Context.getTrivialTypeSourceInfo(Element,
6831 Loc)));
6832 return Context.getCanonicalType(
6833 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6834}
6835
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006836bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6837 // C++ [dcl.init.list]p2:
6838 // A constructor is an initializer-list constructor if its first parameter
6839 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6840 // std::initializer_list<E> for some type E, and either there are no other
6841 // parameters or else all other parameters have default arguments.
6842 if (Ctor->getNumParams() < 1 ||
6843 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6844 return false;
6845
6846 QualType ArgType = Ctor->getParamDecl(0)->getType();
6847 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6848 ArgType = RT->getPointeeType().getUnqualifiedType();
6849
6850 return isStdInitializerList(ArgType, 0);
6851}
6852
Douglas Gregora172e082011-03-26 22:25:30 +00006853/// \brief Determine whether a using statement is in a context where it will be
6854/// apply in all contexts.
6855static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6856 switch (CurContext->getDeclKind()) {
6857 case Decl::TranslationUnit:
6858 return true;
6859 case Decl::LinkageSpec:
6860 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6861 default:
6862 return false;
6863 }
6864}
6865
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006866namespace {
6867
6868// Callback to only accept typo corrections that are namespaces.
6869class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006870public:
Craig Toppera798a9d2014-03-02 09:32:10 +00006871 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006872 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006873 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006874 return false;
6875 }
6876};
6877
6878}
6879
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006880static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6881 CXXScopeSpec &SS,
6882 SourceLocation IdentLoc,
6883 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006884 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006885 R.clear();
6886 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006887 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00006888 Validator)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006889 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006890 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6891 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006892 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006893 S.diagnoseTypo(Corrected,
6894 S.PDiag(diag::err_using_directive_member_suggest)
6895 << Ident << DC << DroppedSpecifier << SS.getRange(),
6896 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006897 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006898 S.diagnoseTypo(Corrected,
6899 S.PDiag(diag::err_using_directive_suggest) << Ident,
6900 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006901 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006902 R.addDecl(Corrected.getCorrectionDecl());
6903 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006904 }
6905 return false;
6906}
6907
John McCall48871652010-08-21 09:40:31 +00006908Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006909 SourceLocation UsingLoc,
6910 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006911 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006912 SourceLocation IdentLoc,
6913 IdentifierInfo *NamespcName,
6914 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006915 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6916 assert(NamespcName && "Invalid NamespcName.");
6917 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006918
6919 // This can only happen along a recovery path.
6920 while (S->getFlags() & Scope::TemplateParamScope)
6921 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006922 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006923
Douglas Gregor889ceb72009-02-03 19:21:40 +00006924 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006925 NestedNameSpecifier *Qualifier = 0;
6926 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00006927 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006928
Douglas Gregor34074322009-01-14 22:20:51 +00006929 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006930 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6931 LookupParsedName(R, S, &SS);
6932 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006933 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006934
Douglas Gregorcdf87022010-06-29 17:53:46 +00006935 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006936 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006937 // Allow "using namespace std;" or "using namespace ::std;" even if
6938 // "std" hasn't been defined yet, for GCC compatibility.
6939 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6940 NamespcName->isStr("std")) {
6941 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006942 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006943 R.resolveKind();
6944 }
6945 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006946 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006947 }
6948
John McCall9f3059a2009-10-09 21:13:30 +00006949 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006950 NamedDecl *Named = R.getFoundDecl();
6951 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6952 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006953 // C++ [namespace.udir]p1:
6954 // A using-directive specifies that the names in the nominated
6955 // namespace can be used in the scope in which the
6956 // using-directive appears after the using-directive. During
6957 // unqualified name lookup (3.4.1), the names appear as if they
6958 // were declared in the nearest enclosing namespace which
6959 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006960 // namespace. [Note: in this context, "contains" means "contains
6961 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006962
6963 // Find enclosing context containing both using-directive and
6964 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006965 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006966 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6967 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6968 CommonAncestor = CommonAncestor->getParent();
6969
Sebastian Redla6602e92009-11-23 15:34:23 +00006970 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006971 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006972 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006973
Douglas Gregora172e082011-03-26 22:25:30 +00006974 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00006975 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006976 Diag(IdentLoc, diag::warn_using_directive_in_header);
6977 }
6978
Douglas Gregor889ceb72009-02-03 19:21:40 +00006979 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006980 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006981 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006982 }
6983
Richard Smith54ecd982013-02-20 19:22:51 +00006984 if (UDir)
6985 ProcessDeclAttributeList(S, UDir, AttrList);
6986
John McCall48871652010-08-21 09:40:31 +00006987 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00006988}
6989
6990void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00006991 // If the scope has an associated entity and the using directive is at
6992 // namespace or translation unit scope, add the UsingDirectiveDecl into
6993 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006994 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00006995 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006996 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006997 else
Richard Smith05afe5e2012-03-13 03:12:56 +00006998 // Otherwise, it is at block sope. The using-directives will affect lookup
6999 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007000 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007001}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007002
Douglas Gregorfec52632009-06-20 00:51:54 +00007003
John McCall48871652010-08-21 09:40:31 +00007004Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007005 AccessSpecifier AS,
7006 bool HasUsingKeyword,
7007 SourceLocation UsingLoc,
7008 CXXScopeSpec &SS,
7009 UnqualifiedId &Name,
7010 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007011 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007012 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007013 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007014
Douglas Gregor220f4272009-11-04 16:30:06 +00007015 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007016 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007017 case UnqualifiedId::IK_Identifier:
7018 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007019 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007020 case UnqualifiedId::IK_ConversionFunctionId:
7021 break;
7022
7023 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007024 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007025 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007026 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007027 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007028 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007029 diag::err_using_decl_constructor)
7030 << SS.getRange();
7031
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007032 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007033
John McCall48871652010-08-21 09:40:31 +00007034 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007035
7036 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007037 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007038 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007039 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007040
7041 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007042 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007043 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00007044 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007045 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007046
7047 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7048 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007049 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00007050 return 0;
John McCall3969e302009-12-08 07:46:18 +00007051
Richard Smithc2bc61b2013-03-18 21:12:30 +00007052 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007053 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007054 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007055 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7056 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007057 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007058 }
7059
Douglas Gregorc4356532010-12-16 00:46:58 +00007060 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7061 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7062 return 0;
7063
John McCall3f746822009-11-17 05:59:44 +00007064 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007065 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007066 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007067 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007068 if (UD)
7069 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007070
John McCall48871652010-08-21 09:40:31 +00007071 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007072}
7073
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007074/// \brief Determine whether a using declaration considers the given
7075/// declarations as "equivalent", e.g., if they are redeclarations of
7076/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007077static bool
7078IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7079 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007080 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007081
Richard Smithdda56e42011-04-15 14:24:37 +00007082 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007083 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007084 return Context.hasSameType(TD1->getUnderlyingType(),
7085 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007086
7087 return false;
7088}
7089
7090
John McCall84d87672009-12-10 09:41:52 +00007091/// Determines whether to create a using shadow decl for a particular
7092/// decl, given the set of decls existing prior to this using lookup.
7093bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007094 const LookupResult &Previous,
7095 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007096 // Diagnose finding a decl which is not from a base class of the
7097 // current class. We do this now because there are cases where this
7098 // function will silently decide not to build a shadow decl, which
7099 // will pre-empt further diagnostics.
7100 //
7101 // We don't need to do this in C++0x because we do the check once on
7102 // the qualifier.
7103 //
7104 // FIXME: diagnose the following if we care enough:
7105 // struct A { int foo; };
7106 // struct B : A { using A::foo; };
7107 // template <class T> struct C : A {};
7108 // template <class T> struct D : C<T> { using B::foo; } // <---
7109 // This is invalid (during instantiation) in C++03 because B::foo
7110 // resolves to the using decl in B, which is not a base class of D<T>.
7111 // We can't diagnose it immediately because C<T> is an unknown
7112 // specialization. The UsingShadowDecl in D<T> then points directly
7113 // to A::foo, which will look well-formed when we instantiate.
7114 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007115 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007116 DeclContext *OrigDC = Orig->getDeclContext();
7117
7118 // Handle enums and anonymous structs.
7119 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7120 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7121 while (OrigRec->isAnonymousStructOrUnion())
7122 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7123
7124 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7125 if (OrigDC == CurContext) {
7126 Diag(Using->getLocation(),
7127 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007128 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007129 Diag(Orig->getLocation(), diag::note_using_decl_target);
7130 return true;
7131 }
7132
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007133 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007134 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007135 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007136 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007137 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007138 Diag(Orig->getLocation(), diag::note_using_decl_target);
7139 return true;
7140 }
7141 }
7142
7143 if (Previous.empty()) return false;
7144
7145 NamedDecl *Target = Orig;
7146 if (isa<UsingShadowDecl>(Target))
7147 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7148
John McCalla17e83e2009-12-11 02:33:26 +00007149 // If the target happens to be one of the previous declarations, we
7150 // don't have a conflict.
7151 //
7152 // FIXME: but we might be increasing its access, in which case we
7153 // should redeclare it.
7154 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithfd8634a2013-10-23 02:17:46 +00007155 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007156 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7157 I != E; ++I) {
7158 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007159 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7160 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7161 PrevShadow = Shadow;
7162 FoundEquivalentDecl = true;
7163 }
John McCalla17e83e2009-12-11 02:33:26 +00007164
7165 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7166 }
7167
Richard Smithfd8634a2013-10-23 02:17:46 +00007168 if (FoundEquivalentDecl)
7169 return false;
7170
Alp Tokera2794f92014-01-22 07:29:52 +00007171 if (FunctionDecl *FD = Target->getAsFunction()) {
John McCall84d87672009-12-10 09:41:52 +00007172 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00007173 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007174 case Ovl_Overload:
7175 return false;
7176
7177 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007178 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007179 break;
Richard Smith18819302014-02-06 01:31:33 +00007180
John McCall84d87672009-12-10 09:41:52 +00007181 // We found a decl with the exact signature.
7182 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007183 // If we're in a record, we want to hide the target, so we
7184 // return true (without a diagnostic) to tell the caller not to
7185 // build a shadow decl.
7186 if (CurContext->isRecord())
7187 return true;
7188
7189 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007190 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007191 break;
7192 }
7193
7194 Diag(Target->getLocation(), diag::note_using_decl_target);
7195 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7196 return true;
7197 }
7198
7199 // Target is not a function.
7200
John McCall84d87672009-12-10 09:41:52 +00007201 if (isa<TagDecl>(Target)) {
7202 // No conflict between a tag and a non-tag.
7203 if (!Tag) return false;
7204
John McCalle29c5cd2009-12-10 19:51:03 +00007205 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007206 Diag(Target->getLocation(), diag::note_using_decl_target);
7207 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7208 return true;
7209 }
7210
7211 // No conflict between a tag and a non-tag.
7212 if (!NonTag) return false;
7213
John McCalle29c5cd2009-12-10 19:51:03 +00007214 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007215 Diag(Target->getLocation(), diag::note_using_decl_target);
7216 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7217 return true;
7218}
7219
John McCall3f746822009-11-17 05:59:44 +00007220/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007221UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007222 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007223 NamedDecl *Orig,
7224 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007225
7226 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007227 NamedDecl *Target = Orig;
7228 if (isa<UsingShadowDecl>(Target)) {
7229 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7230 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007231 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007232
John McCall3f746822009-11-17 05:59:44 +00007233 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007234 = UsingShadowDecl::Create(Context, CurContext,
7235 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007236 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007237
Douglas Gregor457104e2010-09-29 04:25:11 +00007238 Shadow->setAccess(UD->getAccess());
7239 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7240 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007241
7242 Shadow->setPreviousDecl(PrevDecl);
7243
John McCall3f746822009-11-17 05:59:44 +00007244 if (S)
John McCall3969e302009-12-08 07:46:18 +00007245 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007246 else
John McCall3969e302009-12-08 07:46:18 +00007247 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007248
John McCall3969e302009-12-08 07:46:18 +00007249
John McCall84d87672009-12-10 09:41:52 +00007250 return Shadow;
7251}
John McCall3969e302009-12-08 07:46:18 +00007252
John McCall84d87672009-12-10 09:41:52 +00007253/// Hides a using shadow declaration. This is required by the current
7254/// using-decl implementation when a resolvable using declaration in a
7255/// class is followed by a declaration which would hide or override
7256/// one or more of the using decl's targets; for example:
7257///
7258/// struct Base { void foo(int); };
7259/// struct Derived : Base {
7260/// using Base::foo;
7261/// void foo(int);
7262/// };
7263///
7264/// The governing language is C++03 [namespace.udecl]p12:
7265///
7266/// When a using-declaration brings names from a base class into a
7267/// derived class scope, member functions in the derived class
7268/// override and/or hide member functions with the same name and
7269/// parameter types in a base class (rather than conflicting).
7270///
7271/// There are two ways to implement this:
7272/// (1) optimistically create shadow decls when they're not hidden
7273/// by existing declarations, or
7274/// (2) don't create any shadow decls (or at least don't make them
7275/// visible) until we've fully parsed/instantiated the class.
7276/// The problem with (1) is that we might have to retroactively remove
7277/// a shadow decl, which requires several O(n) operations because the
7278/// decl structures are (very reasonably) not designed for removal.
7279/// (2) avoids this but is very fiddly and phase-dependent.
7280void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007281 if (Shadow->getDeclName().getNameKind() ==
7282 DeclarationName::CXXConversionFunctionName)
7283 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7284
John McCall84d87672009-12-10 09:41:52 +00007285 // Remove it from the DeclContext...
7286 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007287
John McCall84d87672009-12-10 09:41:52 +00007288 // ...and the scope, if applicable...
7289 if (S) {
John McCall48871652010-08-21 09:40:31 +00007290 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007291 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007292 }
7293
John McCall84d87672009-12-10 09:41:52 +00007294 // ...and the using decl.
7295 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7296
7297 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007298 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007299}
7300
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007301namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007302class UsingValidatorCCC : public CorrectionCandidateCallback {
7303public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007304 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7305 bool RequireMember)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007306 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007307 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007308
Craig Toppera798a9d2014-03-02 09:32:10 +00007309 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007310 NamedDecl *ND = Candidate.getCorrectionDecl();
7311
7312 // Keywords are not valid here.
7313 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007314 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007315
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007316 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7317 !isa<TypeDecl>(ND))
7318 return false;
7319
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007320 // Completely unqualified names are invalid for a 'using' declaration.
7321 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7322 return false;
7323
7324 if (isa<TypeDecl>(ND))
7325 return HasTypenameKeyword || !IsInstantiation;
7326
7327 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007328 }
7329
7330private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007331 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007332 bool IsInstantiation;
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007333 bool RequireMember;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007334};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007335} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007336
John McCalle61f2ba2009-11-18 02:36:19 +00007337/// Builds a using declaration.
7338///
7339/// \param IsInstantiation - Whether this call arises from an
7340/// instantiation of an unresolved using declaration. We treat
7341/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007342NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7343 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007344 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007345 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007346 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007347 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007348 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007349 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007350 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007351 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007352 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007353
Anders Carlssonf038fc22009-08-28 05:49:21 +00007354 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007355
Anders Carlsson59140b32009-08-28 03:16:11 +00007356 if (SS.isEmpty()) {
7357 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007358 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007359 }
Mike Stump11289f42009-09-09 15:08:12 +00007360
John McCall84d87672009-12-10 09:41:52 +00007361 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007362 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007363 ForRedeclaration);
7364 Previous.setHideTags(false);
7365 if (S) {
7366 LookupName(Previous, S);
7367
7368 // It is really dumb that we have to do this.
7369 LookupResult::Filter F = Previous.makeFilter();
7370 while (F.hasNext()) {
7371 NamedDecl *D = F.next();
7372 if (!isDeclInScope(D, CurContext, S))
7373 F.erase();
7374 }
7375 F.done();
7376 } else {
7377 assert(IsInstantiation && "no scope in non-instantiation");
7378 assert(CurContext->isRecord() && "scope not record in instantiation");
7379 LookupQualifiedName(Previous, CurContext);
7380 }
7381
John McCall84d87672009-12-10 09:41:52 +00007382 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007383 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7384 SS, IdentLoc, Previous))
John McCall84d87672009-12-10 09:41:52 +00007385 return 0;
7386
7387 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00007388 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7389 return 0;
7390
John McCall84c16cf2009-11-12 03:15:40 +00007391 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007392 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007393 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007394 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007395 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007396 // FIXME: not all declaration name kinds are legal here
7397 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7398 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007399 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007400 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007401 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007402 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7403 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007404 }
John McCallb96ec562009-12-04 22:46:56 +00007405 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007406 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007407 NameInfo, HasTypenameKeyword);
Anders Carlssonf038fc22009-08-28 05:49:21 +00007408 }
John McCallb96ec562009-12-04 22:46:56 +00007409 D->setAccess(AS);
7410 CurContext->addDecl(D);
7411
7412 if (!LookupContext) return D;
7413 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00007414
John McCall0b66eb32010-05-01 00:40:08 +00007415 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00007416 UD->setInvalidDecl();
7417 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00007418 }
7419
Richard Smith23d55872012-04-02 01:30:27 +00007420 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007421 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith23d55872012-04-02 01:30:27 +00007422 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlc1f8e492011-03-12 13:44:32 +00007423 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007424 return UD;
7425 }
7426
7427 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007428
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007429 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007430
John McCall3969e302009-12-08 07:46:18 +00007431 // Unlike most lookups, we don't always want to hide tag
7432 // declarations: tag names are visible through the using declaration
7433 // even if hidden by ordinary names, *except* in a dependent context
7434 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007435 if (!IsInstantiation)
7436 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007437
John McCall5dadb652012-04-07 03:04:20 +00007438 // For the purposes of this lookup, we have a base object type
7439 // equal to that of the current context.
7440 if (CurContext->isRecord()) {
7441 R.setBaseObjectType(
7442 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7443 }
7444
John McCall27b18f82009-11-17 02:14:36 +00007445 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007446
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007447 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007448 if (R.empty()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007449 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7450 CurContext->isRecord());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007451 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7452 R.getLookupKind(), S, &SS, CCC)){
7453 // We reject any correction for which ND would be NULL.
7454 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007455 R.setLookupName(Corrected.getCorrection());
7456 R.addDecl(ND);
Richard Smithf9b15102013-08-17 00:46:16 +00007457 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007458 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007459 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7460 << NameInfo.getName() << LookupContext << 0
7461 << SS.getRange());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007462 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007463 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007464 << NameInfo.getName() << LookupContext << SS.getRange();
7465 UD->setInvalidDecl();
7466 return UD;
7467 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007468 }
7469
John McCallb96ec562009-12-04 22:46:56 +00007470 if (R.isAmbiguous()) {
7471 UD->setInvalidDecl();
7472 return UD;
7473 }
Mike Stump11289f42009-09-09 15:08:12 +00007474
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007475 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007476 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007477 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007478 Diag(IdentLoc, diag::err_using_typename_non_type);
7479 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7480 Diag((*I)->getUnderlyingDecl()->getLocation(),
7481 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007482 UD->setInvalidDecl();
7483 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007484 }
7485 } else {
7486 // If we asked for a non-typename and we got a type, error out,
7487 // but only if this is an instantiation of an unresolved using
7488 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007489 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007490 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7491 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007492 UD->setInvalidDecl();
7493 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007494 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007495 }
7496
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007497 // C++0x N2914 [namespace.udecl]p6:
7498 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007499 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007500 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7501 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007502 UD->setInvalidDecl();
7503 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007504 }
Mike Stump11289f42009-09-09 15:08:12 +00007505
John McCall84d87672009-12-10 09:41:52 +00007506 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithfd8634a2013-10-23 02:17:46 +00007507 UsingShadowDecl *PrevDecl = 0;
7508 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7509 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007510 }
John McCall3f746822009-11-17 05:59:44 +00007511
7512 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007513}
7514
Sebastian Redl08905022011-02-05 19:23:19 +00007515/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007516bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007517 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007518
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007519 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007520 assert(SourceType &&
7521 "Using decl naming constructor doesn't have type in scope spec.");
7522 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7523
7524 // Check whether the named type is a direct base class.
7525 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7526 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7527 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7528 BaseIt != BaseE; ++BaseIt) {
7529 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7530 if (CanonicalSourceType == BaseType)
7531 break;
Richard Smith23d55872012-04-02 01:30:27 +00007532 if (BaseIt->getType()->isDependentType())
7533 break;
Sebastian Redl08905022011-02-05 19:23:19 +00007534 }
7535
7536 if (BaseIt == BaseE) {
7537 // Did not find SourceType in the bases.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007538 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007539 diag::err_using_decl_constructor_not_in_direct_base)
7540 << UD->getNameInfo().getSourceRange()
7541 << QualType(SourceType, 0) << TargetClass;
7542 return true;
7543 }
7544
Richard Smith23d55872012-04-02 01:30:27 +00007545 if (!CurContext->isDependentContext())
7546 BaseIt->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007547
7548 return false;
7549}
7550
John McCall84d87672009-12-10 09:41:52 +00007551/// Checks that the given using declaration is not an invalid
7552/// redeclaration. Note that this is checking only for the using decl
7553/// itself, not for any ill-formedness among the UsingShadowDecls.
7554bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007555 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007556 const CXXScopeSpec &SS,
7557 SourceLocation NameLoc,
7558 const LookupResult &Prev) {
7559 // C++03 [namespace.udecl]p8:
7560 // C++0x [namespace.udecl]p10:
7561 // A using-declaration is a declaration and can therefore be used
7562 // repeatedly where (and only where) multiple declarations are
7563 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007564 //
John McCall032092f2010-11-29 18:01:58 +00007565 // That's in non-member contexts.
7566 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007567 return false;
7568
Aaron Ballman4a979672014-01-03 13:56:08 +00007569 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007570
7571 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7572 NamedDecl *D = *I;
7573
7574 bool DTypename;
7575 NestedNameSpecifier *DQual;
7576 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007577 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007578 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007579 } else if (UnresolvedUsingValueDecl *UD
7580 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7581 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007582 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007583 } else if (UnresolvedUsingTypenameDecl *UD
7584 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7585 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007586 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007587 } else continue;
7588
7589 // using decls differ if one says 'typename' and the other doesn't.
7590 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007591 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007592
7593 // using decls differ if they name different scopes (but note that
7594 // template instantiation can cause this check to trigger when it
7595 // didn't before instantiation).
7596 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7597 Context.getCanonicalNestedNameSpecifier(DQual))
7598 continue;
7599
7600 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007601 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007602 return true;
7603 }
7604
7605 return false;
7606}
7607
John McCall3969e302009-12-08 07:46:18 +00007608
John McCallb96ec562009-12-04 22:46:56 +00007609/// Checks that the given nested-name qualifier used in a using decl
7610/// in the current context is appropriately related to the current
7611/// scope. If an error is found, diagnoses it and returns true.
7612bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7613 const CXXScopeSpec &SS,
7614 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007615 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007616
John McCall3969e302009-12-08 07:46:18 +00007617 if (!CurContext->isRecord()) {
7618 // C++03 [namespace.udecl]p3:
7619 // C++0x [namespace.udecl]p8:
7620 // A using-declaration for a class member shall be a member-declaration.
7621
7622 // If we weren't able to compute a valid scope, it must be a
7623 // dependent class scope.
7624 if (!NamedContext || NamedContext->isRecord()) {
7625 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7626 << SS.getRange();
7627 return true;
7628 }
7629
7630 // Otherwise, everything is known to be fine.
7631 return false;
7632 }
7633
7634 // The current scope is a record.
7635
7636 // If the named context is dependent, we can't decide much.
7637 if (!NamedContext) {
7638 // FIXME: in C++0x, we can diagnose if we can prove that the
7639 // nested-name-specifier does not refer to a base class, which is
7640 // still possible in some cases.
7641
7642 // Otherwise we have to conservatively report that things might be
7643 // okay.
7644 return false;
7645 }
7646
7647 if (!NamedContext->isRecord()) {
7648 // Ideally this would point at the last name in the specifier,
7649 // but we don't have that level of source info.
7650 Diag(SS.getRange().getBegin(),
7651 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007652 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007653 return true;
7654 }
7655
Douglas Gregor7c842292010-12-21 07:41:49 +00007656 if (!NamedContext->isDependentContext() &&
7657 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7658 return true;
7659
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007660 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007661 // C++0x [namespace.udecl]p3:
7662 // In a using-declaration used as a member-declaration, the
7663 // nested-name-specifier shall name a base class of the class
7664 // being defined.
7665
7666 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7667 cast<CXXRecordDecl>(NamedContext))) {
7668 if (CurContext == NamedContext) {
7669 Diag(NameLoc,
7670 diag::err_using_decl_nested_name_specifier_is_current_class)
7671 << SS.getRange();
7672 return true;
7673 }
7674
7675 Diag(SS.getRange().getBegin(),
7676 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007677 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007678 << cast<CXXRecordDecl>(CurContext)
7679 << SS.getRange();
7680 return true;
7681 }
7682
7683 return false;
7684 }
7685
7686 // C++03 [namespace.udecl]p4:
7687 // A using-declaration used as a member-declaration shall refer
7688 // to a member of a base class of the class being defined [etc.].
7689
7690 // Salient point: SS doesn't have to name a base class as long as
7691 // lookup only finds members from base classes. Therefore we can
7692 // diagnose here only if we can prove that that can't happen,
7693 // i.e. if the class hierarchies provably don't intersect.
7694
7695 // TODO: it would be nice if "definitely valid" results were cached
7696 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7697 // need to be repeated.
7698
7699 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007700 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007701
7702 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7703 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7704 Data->Bases.insert(Base);
7705 return true;
7706 }
7707
7708 bool hasDependentBases(const CXXRecordDecl *Class) {
7709 return !Class->forallBases(collect, this);
7710 }
7711
7712 /// Returns true if the base is dependent or is one of the
7713 /// accumulated base classes.
7714 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7715 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7716 return !Data->Bases.count(Base);
7717 }
7718
7719 bool mightShareBases(const CXXRecordDecl *Class) {
7720 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7721 }
7722 };
7723
7724 UserData Data;
7725
7726 // Returns false if we find a dependent base.
7727 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7728 return false;
7729
7730 // Returns false if the class has a dependent base or if it or one
7731 // of its bases is present in the base set of the current context.
7732 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7733 return false;
7734
7735 Diag(SS.getRange().getBegin(),
7736 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007737 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007738 << cast<CXXRecordDecl>(CurContext)
7739 << SS.getRange();
7740
7741 return true;
John McCallb96ec562009-12-04 22:46:56 +00007742}
7743
Richard Smithdda56e42011-04-15 14:24:37 +00007744Decl *Sema::ActOnAliasDeclaration(Scope *S,
7745 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007746 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007747 SourceLocation UsingLoc,
7748 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007749 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007750 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007751 // Skip up to the relevant declaration scope.
7752 while (S->getFlags() & Scope::TemplateParamScope)
7753 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007754 assert((S->getFlags() & Scope::DeclScope) &&
7755 "got alias-declaration outside of declaration scope");
7756
7757 if (Type.isInvalid())
7758 return 0;
7759
7760 bool Invalid = false;
7761 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7762 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007763 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007764
7765 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7766 return 0;
7767
7768 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007769 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007770 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007771 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7772 TInfo->getTypeLoc().getBeginLoc());
7773 }
Richard Smithdda56e42011-04-15 14:24:37 +00007774
7775 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7776 LookupName(Previous, S);
7777
7778 // Warn about shadowing the name of a template parameter.
7779 if (Previous.isSingleResult() &&
7780 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007781 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007782 Previous.clear();
7783 }
7784
7785 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7786 "name in alias declaration must be an identifier");
7787 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7788 Name.StartLocation,
7789 Name.Identifier, TInfo);
7790
7791 NewTD->setAccess(AS);
7792
7793 if (Invalid)
7794 NewTD->setInvalidDecl();
7795
Richard Smith54ecd982013-02-20 19:22:51 +00007796 ProcessDeclAttributeList(S, NewTD, AttrList);
7797
Richard Smith3f1b5d02011-05-05 21:57:07 +00007798 CheckTypedefForVariablyModifiedType(S, NewTD);
7799 Invalid |= NewTD->isInvalidDecl();
7800
Richard Smithdda56e42011-04-15 14:24:37 +00007801 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007802
7803 NamedDecl *NewND;
7804 if (TemplateParamLists.size()) {
7805 TypeAliasTemplateDecl *OldDecl = 0;
7806 TemplateParameterList *OldTemplateParams = 0;
7807
7808 if (TemplateParamLists.size() != 1) {
7809 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007810 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7811 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007812 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007813 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007814
7815 // Only consider previous declarations in the same scope.
7816 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7817 /*ExplicitInstantiationOrSpecialization*/false);
7818 if (!Previous.empty()) {
7819 Redeclaration = true;
7820
7821 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7822 if (!OldDecl && !Invalid) {
7823 Diag(UsingLoc, diag::err_redefinition_different_kind)
7824 << Name.Identifier;
7825
7826 NamedDecl *OldD = Previous.getRepresentativeDecl();
7827 if (OldD->getLocation().isValid())
7828 Diag(OldD->getLocation(), diag::note_previous_definition);
7829
7830 Invalid = true;
7831 }
7832
7833 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7834 if (TemplateParameterListsAreEqual(TemplateParams,
7835 OldDecl->getTemplateParameters(),
7836 /*Complain=*/true,
7837 TPL_TemplateMatch))
7838 OldTemplateParams = OldDecl->getTemplateParameters();
7839 else
7840 Invalid = true;
7841
7842 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7843 if (!Invalid &&
7844 !Context.hasSameType(OldTD->getUnderlyingType(),
7845 NewTD->getUnderlyingType())) {
7846 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7847 // but we can't reasonably accept it.
7848 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7849 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7850 if (OldTD->getLocation().isValid())
7851 Diag(OldTD->getLocation(), diag::note_previous_definition);
7852 Invalid = true;
7853 }
7854 }
7855 }
7856
7857 // Merge any previous default template arguments into our parameters,
7858 // and check the parameter list.
7859 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7860 TPC_TypeAliasTemplate))
7861 return 0;
7862
7863 TypeAliasTemplateDecl *NewDecl =
7864 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7865 Name.Identifier, TemplateParams,
7866 NewTD);
7867
7868 NewDecl->setAccess(AS);
7869
7870 if (Invalid)
7871 NewDecl->setInvalidDecl();
7872 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00007873 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007874
7875 NewND = NewDecl;
7876 } else {
7877 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7878 NewND = NewTD;
7879 }
Richard Smithdda56e42011-04-15 14:24:37 +00007880
7881 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00007882 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00007883
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00007884 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007885 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00007886}
7887
John McCall48871652010-08-21 09:40:31 +00007888Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007889 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00007890 SourceLocation AliasLoc,
7891 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007892 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007893 SourceLocation IdentLoc,
7894 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00007895
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007896 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007897 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7898 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007899
Anders Carlssondca83c42009-03-28 06:23:46 +00007900 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00007901 NamedDecl *PrevDecl
7902 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7903 ForRedeclaration);
7904 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7905 PrevDecl = 0;
7906
7907 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007908 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00007909 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007910 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00007911 // FIXME: At some point, we'll want to create the (redundant)
7912 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00007913 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00007914 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00007915 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007916 }
Mike Stump11289f42009-09-09 15:08:12 +00007917
Anders Carlssondca83c42009-03-28 06:23:46 +00007918 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7919 diag::err_redefinition_different_kind;
7920 Diag(AliasLoc, DiagID) << Alias;
7921 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007922 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00007923 }
7924
John McCall27b18f82009-11-17 02:14:36 +00007925 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007926 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00007927
John McCall9f3059a2009-10-09 21:13:30 +00007928 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007929 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00007930 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007931 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00007932 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00007933 }
Mike Stump11289f42009-09-09 15:08:12 +00007934
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007935 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00007936 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00007937 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00007938 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00007939
John McCalld8d0d432010-02-16 06:53:13 +00007940 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00007941 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00007942}
7943
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007944Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00007945Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7946 CXXMethodDecl *MD) {
7947 CXXRecordDecl *ClassDecl = MD->getParent();
7948
Douglas Gregor6d880b12010-07-01 22:31:05 +00007949 // C++ [except.spec]p14:
7950 // An implicitly declared special member function (Clause 12) shall have an
7951 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00007952 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007953 if (ClassDecl->isInvalidDecl())
7954 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00007955
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007956 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00007957 for (const auto &B : ClassDecl->bases()) {
7958 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007959 continue;
7960
Aaron Ballman574705e2014-03-13 15:41:46 +00007961 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007962 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007963 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7964 // If this is a deleted function, add it anyway. This might be conformant
7965 // with the standard. This might not. I'm not sure. It might not matter.
7966 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00007967 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007968 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007969 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007970
7971 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00007972 for (const auto &B : ClassDecl->vbases()) {
7973 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007974 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007975 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7976 // If this is a deleted function, add it anyway. This might be conformant
7977 // with the standard. This might not. I'm not sure. It might not matter.
7978 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00007979 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007980 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007981 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007982
7983 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007984 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00007985 if (F->hasInClassInitializer()) {
7986 if (Expr *E = F->getInClassInitializer())
7987 ExceptSpec.CalledExpr(E);
7988 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00007989 // DR1351:
7990 // If the brace-or-equal-initializer of a non-static data member
7991 // invokes a defaulted default constructor of its class or of an
7992 // enclosing class in a potentially evaluated subexpression, the
7993 // program is ill-formed.
7994 //
7995 // This resolution is unworkable: the exception specification of the
7996 // default constructor can be needed in an unevaluated context, in
7997 // particular, in the operand of a noexcept-expression, and we can be
7998 // unable to compute an exception specification for an enclosed class.
7999 //
8000 // We do not allow an in-class initializer to require the evaluation
8001 // of the exception specification for any in-class initializer whose
8002 // definition is not lexically complete.
8003 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008004 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008005 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008006 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8007 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8008 // If this is a deleted function, add it anyway. This might be conformant
8009 // with the standard. This might not. I'm not sure. It might not matter.
8010 // In particular, the problem is that this function never gets called. It
8011 // might just be ill-formed because this function attempts to refer to
8012 // a deleted function here.
8013 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008014 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008015 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008016 }
John McCalldb40c7f2010-12-14 08:05:40 +00008017
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008018 return ExceptSpec;
8019}
8020
Richard Smithc2bc61b2013-03-18 21:12:30 +00008021Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008022Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8023 CXXRecordDecl *ClassDecl = CD->getParent();
8024
8025 // C++ [except.spec]p14:
8026 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008027 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008028 if (ClassDecl->isInvalidDecl())
8029 return ExceptSpec;
8030
8031 // Inherited constructor.
8032 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8033 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8034 // FIXME: Copying or moving the parameters could add extra exceptions to the
8035 // set, as could the default arguments for the inherited constructor. This
8036 // will be addressed when we implement the resolution of core issue 1351.
8037 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8038
8039 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008040 for (const auto &B : ClassDecl->bases()) {
8041 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008042 continue;
8043
Aaron Ballman574705e2014-03-13 15:41:46 +00008044 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008045 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8046 if (BaseClassDecl == InheritedDecl)
8047 continue;
8048 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8049 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008050 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008051 }
8052 }
8053
8054 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008055 for (const auto &B : ClassDecl->vbases()) {
8056 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008057 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8058 if (BaseClassDecl == InheritedDecl)
8059 continue;
8060 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8061 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008062 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008063 }
8064 }
8065
8066 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008067 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008068 if (F->hasInClassInitializer()) {
8069 if (Expr *E = F->getInClassInitializer())
8070 ExceptSpec.CalledExpr(E);
8071 else if (!F->isInvalidDecl())
8072 Diag(CD->getLocation(),
8073 diag::err_in_class_initializer_references_def_ctor) << CD;
8074 } else if (const RecordType *RecordTy
8075 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8076 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8077 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8078 if (Constructor)
8079 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8080 }
8081 }
8082
Richard Smithc2bc61b2013-03-18 21:12:30 +00008083 return ExceptSpec;
8084}
8085
Richard Smith8bf22e52012-11-29 01:34:07 +00008086namespace {
8087/// RAII object to register a special member as being currently declared.
8088struct DeclaringSpecialMember {
8089 Sema &S;
8090 Sema::SpecialMemberDecl D;
8091 bool WasAlreadyBeingDeclared;
8092
8093 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8094 : S(S), D(RD, CSM) {
8095 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8096 if (WasAlreadyBeingDeclared)
8097 // This almost never happens, but if it does, ensure that our cache
8098 // doesn't contain a stale result.
8099 S.SpecialMemberCache.clear();
8100
8101 // FIXME: Register a note to be produced if we encounter an error while
8102 // declaring the special member.
8103 }
8104 ~DeclaringSpecialMember() {
8105 if (!WasAlreadyBeingDeclared)
8106 S.SpecialMembersBeingDeclared.erase(D);
8107 }
8108
8109 /// \brief Are we already trying to declare this special member?
8110 bool isAlreadyBeingDeclared() const {
8111 return WasAlreadyBeingDeclared;
8112 }
8113};
8114}
8115
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008116CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8117 CXXRecordDecl *ClassDecl) {
8118 // C++ [class.ctor]p5:
8119 // A default constructor for a class X is a constructor of class X
8120 // that can be called without an argument. If there is no
8121 // user-declared constructor for class X, a default constructor is
8122 // implicitly declared. An implicitly-declared default constructor
8123 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008124 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008125 "Should not build implicit default constructor!");
8126
Richard Smith8bf22e52012-11-29 01:34:07 +00008127 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8128 if (DSM.isAlreadyBeingDeclared())
8129 return 0;
8130
Richard Smithb5800092012-06-10 05:43:50 +00008131 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8132 CXXDefaultConstructor,
8133 false);
8134
Douglas Gregor6d880b12010-07-01 22:31:05 +00008135 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008136 CanQualType ClassType
8137 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008138 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008139 DeclarationName Name
8140 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008141 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008142 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00008143 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00008144 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00008145 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008146 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008147 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008148 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008149
8150 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008151 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008152 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008153
Richard Smith6b02d462012-12-08 08:32:28 +00008154 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8155 // constructors is easy to compute.
8156 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8157
8158 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008159 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008160
Douglas Gregor9672f922010-07-03 00:47:00 +00008161 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008162 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008163
Douglas Gregor0be31a22010-07-02 17:43:08 +00008164 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008165 PushOnScopeChains(DefaultCon, S, false);
8166 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008167
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008168 return DefaultCon;
8169}
8170
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008171void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8172 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008173 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008174 !Constructor->doesThisDeclarationHaveABody() &&
8175 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008176 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008177
Anders Carlsson423f5d82010-04-23 16:04:08 +00008178 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008179 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008180
Eli Friedmaneaf34142012-10-18 20:14:08 +00008181 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008182 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008183 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008184 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008185 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008186 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008187 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008188 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008189 }
Douglas Gregor73193272010-09-20 16:48:21 +00008190
8191 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008192 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008193
Eli Friedman276dd182013-09-05 00:02:25 +00008194 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008195 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008196
8197 if (ASTMutationListener *L = getASTMutationListener()) {
8198 L->CompletedImplicitDefinition(Constructor);
8199 }
Richard Trieuef64e942013-10-25 00:56:00 +00008200
8201 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008202}
8203
Richard Smith938f40b2011-06-11 17:19:42 +00008204void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008205 // Perform any delayed checks on exception specifications.
8206 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008207}
8208
Richard Smith185be182013-04-10 05:48:59 +00008209namespace {
8210/// Information on inheriting constructors to declare.
8211class InheritingConstructorInfo {
8212public:
8213 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8214 : SemaRef(SemaRef), Derived(Derived) {
8215 // Mark the constructors that we already have in the derived class.
8216 //
8217 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8218 // unless there is a user-declared constructor with the same signature in
8219 // the class where the using-declaration appears.
8220 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8221 }
8222
8223 void inheritAll(CXXRecordDecl *RD) {
8224 visitAll(RD, &InheritingConstructorInfo::inherit);
8225 }
8226
8227private:
8228 /// Information about an inheriting constructor.
8229 struct InheritingConstructor {
8230 InheritingConstructor()
8231 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8232
8233 /// If \c true, a constructor with this signature is already declared
8234 /// in the derived class.
8235 bool DeclaredInDerived;
8236
8237 /// The constructor which is inherited.
8238 const CXXConstructorDecl *BaseCtor;
8239
8240 /// The derived constructor we declared.
8241 CXXConstructorDecl *DerivedCtor;
8242 };
8243
8244 /// Inheriting constructors with a given canonical type. There can be at
8245 /// most one such non-template constructor, and any number of templated
8246 /// constructors.
8247 struct InheritingConstructorsForType {
8248 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008249 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8250 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008251
8252 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8253 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8254 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8255 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8256 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8257 false, S.TPL_TemplateMatch))
8258 return Templates[I].second;
8259 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8260 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008261 }
Richard Smith185be182013-04-10 05:48:59 +00008262
8263 return NonTemplate;
8264 }
8265 };
8266
8267 /// Get or create the inheriting constructor record for a constructor.
8268 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8269 QualType CtorType) {
8270 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8271 .getEntry(SemaRef, Ctor);
8272 }
8273
8274 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8275
8276 /// Process all constructors for a class.
8277 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008278 for (const auto *Ctor : RD->ctors())
8279 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008280 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8281 I(RD->decls_begin()), E(RD->decls_end());
8282 I != E; ++I) {
8283 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8284 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8285 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008286 }
8287 }
Richard Smith185be182013-04-10 05:48:59 +00008288
8289 /// Note that a constructor (or constructor template) was declared in Derived.
8290 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8291 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8292 }
8293
8294 /// Inherit a single constructor.
8295 void inherit(const CXXConstructorDecl *Ctor) {
8296 const FunctionProtoType *CtorType =
8297 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008298 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008299 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8300
8301 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8302
8303 // Core issue (no number yet): the ellipsis is always discarded.
8304 if (EPI.Variadic) {
8305 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8306 SemaRef.Diag(Ctor->getLocation(),
8307 diag::note_using_decl_constructor_ellipsis);
8308 EPI.Variadic = false;
8309 }
8310
8311 // Declare a constructor for each number of parameters.
8312 //
8313 // C++11 [class.inhctor]p1:
8314 // The candidate set of inherited constructors from the class X named in
8315 // the using-declaration consists of [... modulo defects ...] for each
8316 // constructor or constructor template of X, the set of constructors or
8317 // constructor templates that results from omitting any ellipsis parameter
8318 // specification and successively omitting parameters with a default
8319 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008320 unsigned MinParams = minParamsToInherit(Ctor);
8321 unsigned Params = Ctor->getNumParams();
8322 if (Params >= MinParams) {
8323 do
8324 declareCtor(UsingLoc, Ctor,
8325 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008326 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008327 while (Params > MinParams &&
8328 Ctor->getParamDecl(--Params)->hasDefaultArg());
8329 }
Richard Smith185be182013-04-10 05:48:59 +00008330 }
8331
8332 /// Find the using-declaration which specified that we should inherit the
8333 /// constructors of \p Base.
8334 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8335 // No fancy lookup required; just look for the base constructor name
8336 // directly within the derived class.
8337 ASTContext &Context = SemaRef.Context;
8338 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8339 Context.getCanonicalType(Context.getRecordType(Base)));
8340 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8341 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8342 }
8343
8344 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8345 // C++11 [class.inhctor]p3:
8346 // [F]or each constructor template in the candidate set of inherited
8347 // constructors, a constructor template is implicitly declared
8348 if (Ctor->getDescribedFunctionTemplate())
8349 return 0;
8350
8351 // For each non-template constructor in the candidate set of inherited
8352 // constructors other than a constructor having no parameters or a
8353 // copy/move constructor having a single parameter, a constructor is
8354 // implicitly declared [...]
8355 if (Ctor->getNumParams() == 0)
8356 return 1;
8357 if (Ctor->isCopyOrMoveConstructor())
8358 return 2;
8359
8360 // Per discussion on core reflector, never inherit a constructor which
8361 // would become a default, copy, or move constructor of Derived either.
8362 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8363 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8364 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8365 }
8366
8367 /// Declare a single inheriting constructor, inheriting the specified
8368 /// constructor, with the given type.
8369 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8370 QualType DerivedType) {
8371 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8372
8373 // C++11 [class.inhctor]p3:
8374 // ... a constructor is implicitly declared with the same constructor
8375 // characteristics unless there is a user-declared constructor with
8376 // the same signature in the class where the using-declaration appears
8377 if (Entry.DeclaredInDerived)
8378 return;
8379
8380 // C++11 [class.inhctor]p7:
8381 // If two using-declarations declare inheriting constructors with the
8382 // same signature, the program is ill-formed
8383 if (Entry.DerivedCtor) {
8384 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8385 // Only diagnose this once per constructor.
8386 if (Entry.DerivedCtor->isInvalidDecl())
8387 return;
8388 Entry.DerivedCtor->setInvalidDecl();
8389
8390 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8391 SemaRef.Diag(BaseCtor->getLocation(),
8392 diag::note_using_decl_constructor_conflict_current_ctor);
8393 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8394 diag::note_using_decl_constructor_conflict_previous_ctor);
8395 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8396 diag::note_using_decl_constructor_conflict_previous_using);
8397 } else {
8398 // Core issue (no number): if the same inheriting constructor is
8399 // produced by multiple base class constructors from the same base
8400 // class, the inheriting constructor is defined as deleted.
8401 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8402 }
8403
8404 return;
8405 }
8406
8407 ASTContext &Context = SemaRef.Context;
8408 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8409 Context.getCanonicalType(Context.getRecordType(Derived)));
8410 DeclarationNameInfo NameInfo(Name, UsingLoc);
8411
8412 TemplateParameterList *TemplateParams = 0;
8413 if (const FunctionTemplateDecl *FTD =
8414 BaseCtor->getDescribedFunctionTemplate()) {
8415 TemplateParams = FTD->getTemplateParameters();
8416 // We're reusing template parameters from a different DeclContext. This
8417 // is questionable at best, but works out because the template depth in
8418 // both places is guaranteed to be 0.
8419 // FIXME: Rebuild the template parameters in the new context, and
8420 // transform the function type to refer to them.
8421 }
8422
8423 // Build type source info pointing at the using-declaration. This is
8424 // required by template instantiation.
8425 TypeSourceInfo *TInfo =
8426 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8427 FunctionProtoTypeLoc ProtoLoc =
8428 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8429
8430 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8431 Context, Derived, UsingLoc, NameInfo, DerivedType,
8432 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8433 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8434
8435 // Build an unevaluated exception specification for this constructor.
8436 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8437 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8438 EPI.ExceptionSpecType = EST_Unevaluated;
8439 EPI.ExceptionSpecDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008440 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008441 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008442
8443 // Build the parameter declarations.
8444 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008445 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008446 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008447 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008448 ParmVarDecl *PD = ParmVarDecl::Create(
8449 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
Alp Toker9cacbab2014-01-20 20:26:09 +00008450 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
Richard Smith185be182013-04-10 05:48:59 +00008451 PD->setScopeInfo(0, I);
8452 PD->setImplicit();
8453 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008454 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008455 }
8456
8457 // Set up the new constructor.
8458 DerivedCtor->setAccess(BaseCtor->getAccess());
8459 DerivedCtor->setParams(ParamDecls);
8460 DerivedCtor->setInheritedConstructor(BaseCtor);
8461 if (BaseCtor->isDeleted())
8462 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8463
8464 // If this is a constructor template, build the template declaration.
8465 if (TemplateParams) {
8466 FunctionTemplateDecl *DerivedTemplate =
8467 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8468 TemplateParams, DerivedCtor);
8469 DerivedTemplate->setAccess(BaseCtor->getAccess());
8470 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8471 Derived->addDecl(DerivedTemplate);
8472 } else {
8473 Derived->addDecl(DerivedCtor);
8474 }
8475
8476 Entry.BaseCtor = BaseCtor;
8477 Entry.DerivedCtor = DerivedCtor;
8478 }
8479
8480 Sema &SemaRef;
8481 CXXRecordDecl *Derived;
8482 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8483 MapType Map;
8484};
8485}
8486
8487void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8488 // Defer declaring the inheriting constructors until the class is
8489 // instantiated.
8490 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008491 return;
8492
Richard Smith185be182013-04-10 05:48:59 +00008493 // Find base classes from which we might inherit constructors.
8494 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008495 for (const auto &BaseIt : ClassDecl->bases())
8496 if (BaseIt.getInheritConstructors())
8497 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008498
Richard Smith185be182013-04-10 05:48:59 +00008499 // Go no further if we're not inheriting any constructors.
8500 if (InheritedBases.empty())
8501 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008502
Richard Smith185be182013-04-10 05:48:59 +00008503 // Declare the inherited constructors.
8504 InheritingConstructorInfo ICI(*this, ClassDecl);
8505 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8506 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008507}
8508
Richard Smithc2bc61b2013-03-18 21:12:30 +00008509void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8510 CXXConstructorDecl *Constructor) {
8511 CXXRecordDecl *ClassDecl = Constructor->getParent();
8512 assert(Constructor->getInheritedConstructor() &&
8513 !Constructor->doesThisDeclarationHaveABody() &&
8514 !Constructor->isDeleted());
8515
8516 SynthesizedFunctionScope Scope(*this, Constructor);
8517 DiagnosticErrorTrap Trap(Diags);
8518 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8519 Trap.hasErrorOccurred()) {
8520 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8521 << Context.getTagDeclType(ClassDecl);
8522 Constructor->setInvalidDecl();
8523 return;
8524 }
8525
8526 SourceLocation Loc = Constructor->getLocation();
8527 Constructor->setBody(new (Context) CompoundStmt(Loc));
8528
Eli Friedman276dd182013-09-05 00:02:25 +00008529 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008530 MarkVTableUsed(CurrentLocation, ClassDecl);
8531
8532 if (ASTMutationListener *L = getASTMutationListener()) {
8533 L->CompletedImplicitDefinition(Constructor);
8534 }
8535}
8536
8537
Alexis Huntf91729462011-05-12 22:46:25 +00008538Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008539Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8540 CXXRecordDecl *ClassDecl = MD->getParent();
8541
Douglas Gregorf1203042010-07-01 19:09:28 +00008542 // C++ [except.spec]p14:
8543 // An implicitly declared special member function (Clause 12) shall have
8544 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008545 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008546 if (ClassDecl->isInvalidDecl())
8547 return ExceptSpec;
8548
Douglas Gregorf1203042010-07-01 19:09:28 +00008549 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008550 for (const auto &B : ClassDecl->bases()) {
8551 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008552 continue;
8553
Aaron Ballman574705e2014-03-13 15:41:46 +00008554 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8555 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008556 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008557 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008558
Douglas Gregorf1203042010-07-01 19:09:28 +00008559 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008560 for (const auto &B : ClassDecl->vbases()) {
8561 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8562 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008563 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008564 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008565
Douglas Gregorf1203042010-07-01 19:09:28 +00008566 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008567 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008568 if (const RecordType *RecordTy
8569 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008570 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008571 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008572 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008573
Alexis Huntf91729462011-05-12 22:46:25 +00008574 return ExceptSpec;
8575}
8576
8577CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8578 // C++ [class.dtor]p2:
8579 // If a class has no user-declared destructor, a destructor is
8580 // declared implicitly. An implicitly-declared destructor is an
8581 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008582 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008583
Richard Smith8bf22e52012-11-29 01:34:07 +00008584 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8585 if (DSM.isAlreadyBeingDeclared())
8586 return 0;
8587
Douglas Gregor7454c562010-07-02 20:37:36 +00008588 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008589 CanQualType ClassType
8590 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008591 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008592 DeclarationName Name
8593 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008594 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008595 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008596 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8597 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008598 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008599 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008600 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008601 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008602
8603 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008604 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008605 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008606
Richard Smith6b02d462012-12-08 08:32:28 +00008607 AddOverriddenMethods(ClassDecl, Destructor);
8608
8609 // We don't need to use SpecialMemberIsTrivial here; triviality for
8610 // destructors is easy to compute.
8611 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8612
8613 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008614 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008615
Douglas Gregor7454c562010-07-02 20:37:36 +00008616 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008617 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008618
Douglas Gregor7454c562010-07-02 20:37:36 +00008619 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008620 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008621 PushOnScopeChains(Destructor, S, false);
8622 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008623
Douglas Gregorf1203042010-07-01 19:09:28 +00008624 return Destructor;
8625}
8626
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008627void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008628 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008629 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008630 !Destructor->doesThisDeclarationHaveABody() &&
8631 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008632 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008633 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008634 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008635
Douglas Gregor54818f02010-05-12 16:39:35 +00008636 if (Destructor->isInvalidDecl())
8637 return;
8638
Eli Friedmaneaf34142012-10-18 20:14:08 +00008639 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008640
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008641 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008642 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8643 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008644
Douglas Gregor54818f02010-05-12 16:39:35 +00008645 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008646 Diag(CurrentLocation, diag::note_member_synthesized_at)
8647 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8648
8649 Destructor->setInvalidDecl();
8650 return;
8651 }
8652
Douglas Gregor73193272010-09-20 16:48:21 +00008653 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008654 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008655 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008656 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008657
8658 if (ASTMutationListener *L = getASTMutationListener()) {
8659 L->CompletedImplicitDefinition(Destructor);
8660 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008661}
8662
Richard Smith84973e52012-04-21 18:42:51 +00008663/// \brief Perform any semantic analysis which needs to be delayed until all
8664/// pending class member declarations have been parsed.
8665void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008666 // If the context is an invalid C++ class, just suppress these checks.
8667 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8668 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008669 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008670 DelayedDestructorExceptionSpecChecks.clear();
8671 return;
8672 }
8673 }
Richard Smith84973e52012-04-21 18:42:51 +00008674}
8675
Richard Smithd3b5c9082012-07-27 04:22:15 +00008676void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8677 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008678 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008679 "adjusting dtor exception specs was introduced in c++11");
8680
Sebastian Redl623ea822011-05-19 05:13:44 +00008681 // C++11 [class.dtor]p3:
8682 // A declaration of a destructor that does not have an exception-
8683 // specification is implicitly considered to have the same exception-
8684 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008685 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008686 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008687 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008688 return;
8689
Chandler Carruth9a797572011-09-20 04:55:26 +00008690 // Replace the destructor's type, building off the existing one. Fortunately,
8691 // the only thing of interest in the destructor type is its extended info.
8692 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008693 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8694 EPI.ExceptionSpecType = EST_Unevaluated;
8695 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008696 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008697
Sebastian Redl623ea822011-05-19 05:13:44 +00008698 // FIXME: If the destructor has a body that could throw, and the newly created
8699 // spec doesn't allow exceptions, we should emit a warning, because this
8700 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008701 // However, we don't have a body or an exception specification yet, so it
8702 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008703}
8704
Pavel Labath58934982013-08-30 08:52:28 +00008705namespace {
8706/// \brief An abstract base class for all helper classes used in building the
8707// copy/move operators. These classes serve as factory functions and help us
8708// avoid using the same Expr* in the AST twice.
8709class ExprBuilder {
8710 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8711 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8712
8713protected:
8714 static Expr *assertNotNull(Expr *E) {
8715 assert(E && "Expression construction must not fail.");
8716 return E;
8717 }
8718
8719public:
8720 ExprBuilder() {}
8721 virtual ~ExprBuilder() {}
8722
8723 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8724};
8725
8726class RefBuilder: public ExprBuilder {
8727 VarDecl *Var;
8728 QualType VarType;
8729
8730public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008731 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008732 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8733 }
8734
8735 RefBuilder(VarDecl *Var, QualType VarType)
8736 : Var(Var), VarType(VarType) {}
8737};
8738
8739class ThisBuilder: public ExprBuilder {
8740public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008741 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008742 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8743 }
8744};
8745
8746class CastBuilder: public ExprBuilder {
8747 const ExprBuilder &Builder;
8748 QualType Type;
8749 ExprValueKind Kind;
8750 const CXXCastPath &Path;
8751
8752public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008753 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008754 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8755 CK_UncheckedDerivedToBase, Kind,
8756 &Path).take());
8757 }
8758
8759 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8760 const CXXCastPath &Path)
8761 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8762};
8763
8764class DerefBuilder: public ExprBuilder {
8765 const ExprBuilder &Builder;
8766
8767public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008768 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008769 return assertNotNull(
8770 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8771 }
8772
8773 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8774};
8775
8776class MemberBuilder: public ExprBuilder {
8777 const ExprBuilder &Builder;
8778 QualType Type;
8779 CXXScopeSpec SS;
8780 bool IsArrow;
8781 LookupResult &MemberLookup;
8782
8783public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008784 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008785 return assertNotNull(S.BuildMemberReferenceExpr(
8786 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8787 MemberLookup, 0).take());
8788 }
8789
8790 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8791 LookupResult &MemberLookup)
8792 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8793 MemberLookup(MemberLookup) {}
8794};
8795
8796class MoveCastBuilder: public ExprBuilder {
8797 const ExprBuilder &Builder;
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(CastForMoving(S, Builder.build(S, Loc)));
8802 }
8803
8804 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8805};
8806
8807class LvalueConvBuilder: public ExprBuilder {
8808 const ExprBuilder &Builder;
8809
8810public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008811 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008812 return assertNotNull(
8813 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8814 }
8815
8816 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8817};
8818
8819class SubscriptBuilder: public ExprBuilder {
8820 const ExprBuilder &Base;
8821 const ExprBuilder &Index;
8822
8823public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008824 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008825 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8826 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8827 }
8828
8829 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8830 : Base(Base), Index(Index) {}
8831};
8832
8833} // end anonymous namespace
8834
Richard Smith41ae3282012-11-14 00:50:40 +00008835/// When generating a defaulted copy or move assignment operator, if a field
8836/// should be copied with __builtin_memcpy rather than via explicit assignments,
8837/// do so. This optimization only applies for arrays of scalars, and for arrays
8838/// of class type where the selected copy/move-assignment operator is trivial.
8839static StmtResult
8840buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008841 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00008842 // Compute the size of the memory buffer to be copied.
8843 QualType SizeType = S.Context.getSizeType();
8844 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8845 S.Context.getTypeSizeInChars(T).getQuantity());
8846
8847 // Take the address of the field references for "from" and "to". We
8848 // directly construct UnaryOperators here because semantic analysis
8849 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00008850 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008851 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8852 S.Context.getPointerType(From->getType()),
8853 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00008854 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008855 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8856 S.Context.getPointerType(To->getType()),
8857 VK_RValue, OK_Ordinary, Loc);
8858
8859 const Type *E = T->getBaseElementTypeUnsafe();
8860 bool NeedsCollectableMemCpy =
8861 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8862
8863 // Create a reference to the __builtin_objc_memmove_collectable function
8864 StringRef MemCpyName = NeedsCollectableMemCpy ?
8865 "__builtin_objc_memmove_collectable" :
8866 "__builtin_memcpy";
8867 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8868 Sema::LookupOrdinaryName);
8869 S.LookupName(R, S.TUScope, true);
8870
8871 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8872 if (!MemCpy)
8873 // Something went horribly wrong earlier, and we will have complained
8874 // about it.
8875 return StmtError();
8876
8877 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8878 VK_RValue, Loc, 0);
8879 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8880
8881 Expr *CallArgs[] = {
8882 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8883 };
8884 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8885 Loc, CallArgs, Loc);
8886
8887 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8888 return S.Owned(Call.takeAs<Stmt>());
8889}
8890
Sebastian Redl22653ba2011-08-30 19:58:05 +00008891/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00008892/// \c To.
8893///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008894/// This routine is used to copy/move the members of a class with an
8895/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00008896/// copied are arrays, this routine builds for loops to copy them.
8897///
8898/// \param S The Sema object used for type-checking.
8899///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008900/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008901///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008902/// \param T The type of the expressions being copied/moved. Both expressions
8903/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008904///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008905/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008906///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008907/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008908///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008909/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008910/// Otherwise, it's a non-static member subobject.
8911///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008912/// \param Copying Whether we're copying or moving.
8913///
Douglas Gregorb139cd52010-05-01 20:49:11 +00008914/// \param Depth Internal parameter recording the depth of the recursion.
8915///
Richard Smith41ae3282012-11-14 00:50:40 +00008916/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8917/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00008918static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00008919buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008920 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00008921 bool CopyingBaseSubobject, bool Copying,
8922 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00008923 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00008924 // Each subobject is assigned in the manner appropriate to its type:
8925 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00008926 // - if the subobject is of class type, as if by a call to operator= with
8927 // the subobject as the object expression and the corresponding
8928 // subobject of x as a single function argument (as if by explicit
8929 // qualification; that is, ignoring any possible virtual overriding
8930 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00008931 //
8932 // C++03 [class.copy]p13:
8933 // - if the subobject is of class type, the copy assignment operator for
8934 // the class is used (as if by explicit qualification; that is,
8935 // ignoring any possible virtual overriding functions in more derived
8936 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008937 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8938 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00008939
Douglas Gregorb139cd52010-05-01 20:49:11 +00008940 // Look for operator=.
8941 DeclarationName Name
8942 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8943 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8944 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008945
Richard Smith52c0b582012-11-13 00:54:12 +00008946 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8947 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008948 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00008949 LookupResult::Filter F = OpLookup.makeFilter();
8950 while (F.hasNext()) {
8951 NamedDecl *D = F.next();
8952 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8953 if (Method->isCopyAssignmentOperator() ||
8954 (!Copying && Method->isMoveAssignmentOperator()))
8955 continue;
8956
8957 F.erase();
8958 }
8959 F.done();
John McCallab8c2732010-03-16 06:11:48 +00008960 }
Richard Smith52c0b582012-11-13 00:54:12 +00008961
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008962 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00008963 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008964 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00008965 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008966 // ambiguities), we need to cast "this" to that subobject type; to
8967 // ensure that we don't go through the virtual call mechanism, we need
8968 // to qualify the operator= name with the base class (see below). However,
8969 // this means that if the base class has a protected copy assignment
8970 // operator, the protected member access check will fail. So, we
8971 // rewrite "protected" access to "public" access in this case, since we
8972 // know by construction that we're calling from a derived class.
8973 if (CopyingBaseSubobject) {
8974 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8975 L != LEnd; ++L) {
8976 if (L.getAccess() == AS_protected)
8977 L.setAccess(AS_public);
8978 }
8979 }
Richard Smith52c0b582012-11-13 00:54:12 +00008980
Douglas Gregorb139cd52010-05-01 20:49:11 +00008981 // Create the nested-name-specifier that will be used to qualify the
8982 // reference to operator=; this is required to suppress the virtual
8983 // call mechanism.
8984 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00008985 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00008986 SS.MakeTrivial(S.Context,
8987 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00008988 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00008989 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00008990
Douglas Gregorb139cd52010-05-01 20:49:11 +00008991 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00008992 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00008993 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
8994 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00008995 /*FirstQualifierInScope=*/0,
8996 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00008997 /*TemplateArgs=*/0,
8998 /*SuppressQualifierCheck=*/true);
8999 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009000 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009001
Douglas Gregorb139cd52010-05-01 20:49:11 +00009002 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009003
Pavel Labath58934982013-08-30 08:52:28 +00009004 Expr *FromInst = From.build(S, Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009005 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009006 OpEqualRef.takeAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009007 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009008 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009009 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009010
Richard Smith41ae3282012-11-14 00:50:40 +00009011 // If we built a call to a trivial 'operator=' while copying an array,
9012 // bail out. We'll replace the whole shebang with a memcpy.
9013 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9014 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9015 return StmtResult((Stmt*)0);
9016
Richard Smith52c0b582012-11-13 00:54:12 +00009017 // Convert to an expression-statement, and clean up any produced
9018 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009019 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009020 }
John McCallab8c2732010-03-16 06:11:48 +00009021
Richard Smith52c0b582012-11-13 00:54:12 +00009022 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009023 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009024 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009025 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009026 ExprResult Assignment = S.CreateBuiltinBinOp(
9027 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009028 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009029 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009030 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009031 }
Richard Smith52c0b582012-11-13 00:54:12 +00009032
9033 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009034 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009035
Douglas Gregorb139cd52010-05-01 20:49:11 +00009036 // Construct a loop over the array bounds, e.g.,
9037 //
9038 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9039 //
9040 // that will copy each of the array elements.
9041 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009042
Douglas Gregorb139cd52010-05-01 20:49:11 +00009043 // Create the iteration variable.
9044 IdentifierInfo *IterationVarName = 0;
9045 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009046 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009047 llvm::raw_svector_ostream OS(Str);
9048 OS << "__i" << Depth;
9049 IterationVarName = &S.Context.Idents.get(OS.str());
9050 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009051 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009052 IterationVarName, SizeType,
9053 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009054 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009055
Douglas Gregorb139cd52010-05-01 20:49:11 +00009056 // Initialize the iteration variable to zero.
9057 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009058 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009059
Pavel Labath58934982013-08-30 08:52:28 +00009060 // Creates a reference to the iteration variable.
9061 RefBuilder IterationVarRef(IterationVar, SizeType);
9062 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009063
Douglas Gregorb139cd52010-05-01 20:49:11 +00009064 // Create the DeclStmt that holds the iteration variable.
9065 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009066
Douglas Gregorb139cd52010-05-01 20:49:11 +00009067 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009068 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9069 MoveCastBuilder FromIndexMove(FromIndexCopy);
9070 const ExprBuilder *FromIndex;
9071 if (Copying)
9072 FromIndex = &FromIndexCopy;
9073 else
9074 FromIndex = &FromIndexMove;
9075
9076 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009077
9078 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009079 StmtResult Copy =
9080 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009081 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009082 Copying, Depth + 1);
9083 // Bail out if copying fails or if we determined that we should use memcpy.
9084 if (Copy.isInvalid() || !Copy.get())
9085 return Copy;
9086
9087 // Create the comparison against the array bound.
9088 llvm::APInt Upper
9089 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9090 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009091 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009092 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9093 BO_NE, S.Context.BoolTy,
9094 VK_RValue, OK_Ordinary, Loc, false);
9095
9096 // Create the pre-increment of the iteration variable.
9097 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009098 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9099 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009100
Douglas Gregorb139cd52010-05-01 20:49:11 +00009101 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009102 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009103 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00009104 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00009105 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009106}
9107
Richard Smith41ae3282012-11-14 00:50:40 +00009108static StmtResult
9109buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009110 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009111 bool CopyingBaseSubobject, bool Copying) {
9112 // Maybe we should use a memcpy?
9113 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9114 T.isTriviallyCopyableType(S.Context))
9115 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9116
9117 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9118 CopyingBaseSubobject,
9119 Copying, 0));
9120
9121 // If we ended up picking a trivial assignment operator for an array of a
9122 // non-trivially-copyable class type, just emit a memcpy.
9123 if (!Result.isInvalid() && !Result.get())
9124 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9125
9126 return Result;
9127}
9128
Richard Smithd3b5c9082012-07-27 04:22:15 +00009129Sema::ImplicitExceptionSpecification
9130Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9131 CXXRecordDecl *ClassDecl = MD->getParent();
9132
9133 ImplicitExceptionSpecification ExceptSpec(*this);
9134 if (ClassDecl->isInvalidDecl())
9135 return ExceptSpec;
9136
9137 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009138 assert(T->getNumParams() == 1 && "not a copy assignment op");
9139 unsigned ArgQuals =
9140 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009141
Douglas Gregor68e11362010-07-01 17:48:08 +00009142 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009143 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009144 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009145
9146 // It is unspecified whether or not an implicit copy assignment operator
9147 // attempts to deduplicate calls to assignment operators of virtual bases are
9148 // made. As such, this exception specification is effectively unspecified.
9149 // Based on a similar decision made for constness in C++0x, we're erring on
9150 // the side of assuming such calls to be made regardless of whether they
9151 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009152 for (const auto &Base : ClassDecl->bases()) {
9153 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009154 continue;
9155
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009156 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009157 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009158 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9159 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009160 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009161 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009162
Aaron Ballman445a9392014-03-13 16:15:17 +00009163 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009164 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009165 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009166 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9167 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009168 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009169 }
9170
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009171 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009172 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009173 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9174 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009175 LookupCopyingAssignment(FieldClassDecl,
9176 ArgQuals | FieldType.getCVRQualifiers(),
9177 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009178 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009179 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009180 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009181
Richard Smithd3b5c9082012-07-27 04:22:15 +00009182 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009183}
9184
9185CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9186 // Note: The following rules are largely analoguous to the copy
9187 // constructor rules. Note that virtual bases are not taken into account
9188 // for determining the argument type of the operator. Note also that
9189 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009190 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009191
Richard Smith8bf22e52012-11-29 01:34:07 +00009192 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9193 if (DSM.isAlreadyBeingDeclared())
9194 return 0;
9195
Alexis Hunt119f3652011-05-14 05:23:20 +00009196 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9197 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009198 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9199 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009200 ArgType = ArgType.withConst();
9201 ArgType = Context.getLValueReferenceType(ArgType);
9202
Richard Smith99005e62013-05-07 03:19:20 +00009203 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9204 CXXCopyAssignment,
9205 Const);
9206
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009207 // An implicitly-declared copy assignment operator is an inline public
9208 // member of its class.
9209 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009210 SourceLocation ClassLoc = ClassDecl->getLocation();
9211 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009212 CXXMethodDecl *CopyAssignment =
9213 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9214 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9215 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009216 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009217 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009218 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009219
9220 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009221 FunctionProtoType::ExtProtoInfo EPI =
9222 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009223 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009224
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009225 // Add the parameter to the operator.
9226 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009227 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009228 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009229 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009230 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009231
Richard Smith6b02d462012-12-08 08:32:28 +00009232 AddOverriddenMethods(ClassDecl, CopyAssignment);
9233
9234 CopyAssignment->setTrivial(
9235 ClassDecl->needsOverloadResolutionForCopyAssignment()
9236 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9237 : ClassDecl->hasTrivialCopyAssignment());
9238
Richard Smith852265f2012-03-30 20:53:28 +00009239 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009240 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009241
Richard Smith6b02d462012-12-08 08:32:28 +00009242 // Note that we have added this copy-assignment operator.
9243 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9244
9245 if (Scope *S = getScopeForContext(ClassDecl))
9246 PushOnScopeChains(CopyAssignment, S, false);
9247 ClassDecl->addDecl(CopyAssignment);
9248
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009249 return CopyAssignment;
9250}
9251
Richard Smithd577fbb2013-06-13 03:23:42 +00009252/// Diagnose an implicit copy operation for a class which is odr-used, but
9253/// which is deprecated because the class has a user-declared copy constructor,
9254/// copy assignment operator, or destructor.
9255static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9256 SourceLocation UseLoc) {
9257 assert(CopyOp->isImplicit());
9258
9259 CXXRecordDecl *RD = CopyOp->getParent();
9260 CXXMethodDecl *UserDeclaredOperation = 0;
9261
9262 // In Microsoft mode, assignment operations don't affect constructors and
9263 // vice versa.
9264 if (RD->hasUserDeclaredDestructor()) {
9265 UserDeclaredOperation = RD->getDestructor();
9266 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9267 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009268 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009269 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009270 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009271 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009272 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009273 break;
9274 }
9275 }
9276 assert(UserDeclaredOperation);
9277 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9278 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009279 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009280 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009281 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009282 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009283 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009284 break;
9285 }
9286 }
9287 assert(UserDeclaredOperation);
9288 }
9289
9290 if (UserDeclaredOperation) {
9291 S.Diag(UserDeclaredOperation->getLocation(),
9292 diag::warn_deprecated_copy_operation)
9293 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9294 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9295 S.Diag(UseLoc, diag::note_member_synthesized_at)
9296 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9297 : Sema::CXXCopyAssignment)
9298 << RD;
9299 }
9300}
9301
Douglas Gregorb139cd52010-05-01 20:49:11 +00009302void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9303 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009304 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009305 CopyAssignOperator->isOverloadedOperator() &&
9306 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009307 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9308 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009309 "DefineImplicitCopyAssignment called for wrong function");
9310
9311 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9312
9313 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9314 CopyAssignOperator->setInvalidDecl();
9315 return;
9316 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009317
9318 // C++11 [class.copy]p18:
9319 // The [definition of an implicitly declared copy assignment operator] is
9320 // deprecated if the class has a user-declared copy constructor or a
9321 // user-declared destructor.
9322 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9323 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9324
Eli Friedman276dd182013-09-05 00:02:25 +00009325 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009326
Eli Friedmaneaf34142012-10-18 20:14:08 +00009327 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009328 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009329
9330 // C++0x [class.copy]p30:
9331 // The implicitly-defined or explicitly-defaulted copy assignment operator
9332 // for a non-union class X performs memberwise copy assignment of its
9333 // subobjects. The direct base classes of X are assigned first, in the
9334 // order of their declaration in the base-specifier-list, and then the
9335 // immediate non-static data members of X are assigned, in the order in
9336 // which they were declared in the class definition.
9337
9338 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009339 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009340
9341 // The parameter for the "other" object, which we are copying from.
9342 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9343 Qualifiers OtherQuals = Other->getType().getQualifiers();
9344 QualType OtherRefType = Other->getType();
9345 if (const LValueReferenceType *OtherRef
9346 = OtherRefType->getAs<LValueReferenceType>()) {
9347 OtherRefType = OtherRef->getPointeeType();
9348 OtherQuals = OtherRefType.getQualifiers();
9349 }
9350
9351 // Our location for everything implicitly-generated.
9352 SourceLocation Loc = CopyAssignOperator->getLocation();
9353
Pavel Labath58934982013-08-30 08:52:28 +00009354 // Builds a DeclRefExpr for the "other" object.
9355 RefBuilder OtherRef(Other, OtherRefType);
9356
9357 // Builds the "this" pointer.
9358 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009359
9360 // Assign base classes.
9361 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009362 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009363 // Form the assignment:
9364 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009365 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009366 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009367 Invalid = true;
9368 continue;
9369 }
9370
John McCallcf142162010-08-07 06:22:56 +00009371 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009372 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009373
Douglas Gregorb139cd52010-05-01 20:49:11 +00009374 // Construct the "from" expression, which is an implicit cast to the
9375 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009376 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9377 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009378
9379 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009380 DerefBuilder DerefThis(This);
9381 CastBuilder To(DerefThis,
9382 Context.getCVRQualifiedType(
9383 BaseType, CopyAssignOperator->getTypeQualifiers()),
9384 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009385
9386 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009387 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009388 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009389 /*CopyingBaseSubobject=*/true,
9390 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009391 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009392 Diag(CurrentLocation, diag::note_member_synthesized_at)
9393 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9394 CopyAssignOperator->setInvalidDecl();
9395 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009396 }
9397
9398 // Success! Record the copy.
9399 Statements.push_back(Copy.takeAs<Expr>());
9400 }
9401
Douglas Gregorb139cd52010-05-01 20:49:11 +00009402 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009403 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009404 if (Field->isUnnamedBitfield())
9405 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009406
9407 if (Field->isInvalidDecl()) {
9408 Invalid = true;
9409 continue;
9410 }
9411
Douglas Gregorb139cd52010-05-01 20:49:11 +00009412 // Check for members of reference type; we can't copy those.
9413 if (Field->getType()->isReferenceType()) {
9414 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9415 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9416 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009417 Diag(CurrentLocation, diag::note_member_synthesized_at)
9418 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009419 Invalid = true;
9420 continue;
9421 }
9422
9423 // Check for members of const-qualified, non-class type.
9424 QualType BaseType = Context.getBaseElementType(Field->getType());
9425 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9426 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9427 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9428 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009429 Diag(CurrentLocation, diag::note_member_synthesized_at)
9430 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009431 Invalid = true;
9432 continue;
9433 }
John McCall1b1a1db2011-06-17 00:18:42 +00009434
9435 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009436 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9437 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009438
9439 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009440 if (FieldType->isIncompleteArrayType()) {
9441 assert(ClassDecl->hasFlexibleArrayMember() &&
9442 "Incomplete array type is not valid");
9443 continue;
9444 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009445
9446 // Build references to the field in the object we're copying from and to.
9447 CXXScopeSpec SS; // Intentionally empty
9448 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9449 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009450 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009451 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009452
9453 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9454
9455 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009456
Douglas Gregorb139cd52010-05-01 20:49:11 +00009457 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009458 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009459 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009460 /*CopyingBaseSubobject=*/false,
9461 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009462 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009463 Diag(CurrentLocation, diag::note_member_synthesized_at)
9464 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9465 CopyAssignOperator->setInvalidDecl();
9466 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009467 }
9468
9469 // Success! Record the copy.
9470 Statements.push_back(Copy.takeAs<Stmt>());
9471 }
9472
9473 if (!Invalid) {
9474 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009475 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009476
John McCalldadc5752010-08-24 06:29:42 +00009477 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009478 if (Return.isInvalid())
9479 Invalid = true;
9480 else {
9481 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009482
9483 if (Trap.hasErrorOccurred()) {
9484 Diag(CurrentLocation, diag::note_member_synthesized_at)
9485 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9486 Invalid = true;
9487 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009488 }
9489 }
9490
9491 if (Invalid) {
9492 CopyAssignOperator->setInvalidDecl();
9493 return;
9494 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009495
9496 StmtResult Body;
9497 {
9498 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009499 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009500 /*isStmtExpr=*/false);
9501 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9502 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009503 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009504
9505 if (ASTMutationListener *L = getASTMutationListener()) {
9506 L->CompletedImplicitDefinition(CopyAssignOperator);
9507 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009508}
9509
Sebastian Redl22653ba2011-08-30 19:58:05 +00009510Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009511Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9512 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009513
Richard Smithd3b5c9082012-07-27 04:22:15 +00009514 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009515 if (ClassDecl->isInvalidDecl())
9516 return ExceptSpec;
9517
9518 // C++0x [except.spec]p14:
9519 // An implicitly declared special member function (Clause 12) shall have an
9520 // exception-specification. [...]
9521
9522 // It is unspecified whether or not an implicit move assignment operator
9523 // attempts to deduplicate calls to assignment operators of virtual bases are
9524 // made. As such, this exception specification is effectively unspecified.
9525 // Based on a similar decision made for constness in C++0x, we're erring on
9526 // the side of assuming such calls to be made regardless of whether they
9527 // actually happen.
9528 // Note that a move constructor is not implicitly declared when there are
9529 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009530 for (const auto &Base : ClassDecl->bases()) {
9531 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009532 continue;
9533
9534 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009535 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009536 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009537 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009538 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009539 }
9540
Aaron Ballman445a9392014-03-13 16:15:17 +00009541 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009542 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009543 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009544 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009545 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009546 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009547 }
9548
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009549 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009550 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009551 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009552 if (CXXMethodDecl *MoveAssign =
9553 LookupMovingAssignment(FieldClassDecl,
9554 FieldType.getCVRQualifiers(),
9555 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009556 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009557 }
9558 }
9559
9560 return ExceptSpec;
9561}
9562
9563CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009564 assert(ClassDecl->needsImplicitMoveAssignment());
9565
Richard Smith8bf22e52012-11-29 01:34:07 +00009566 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9567 if (DSM.isAlreadyBeingDeclared())
9568 return 0;
9569
Sebastian Redl22653ba2011-08-30 19:58:05 +00009570 // Note: The following rules are largely analoguous to the move
9571 // constructor rules.
9572
Sebastian Redl22653ba2011-08-30 19:58:05 +00009573 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9574 QualType RetType = Context.getLValueReferenceType(ArgType);
9575 ArgType = Context.getRValueReferenceType(ArgType);
9576
Richard Smith99005e62013-05-07 03:19:20 +00009577 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9578 CXXMoveAssignment,
9579 false);
9580
Sebastian Redl22653ba2011-08-30 19:58:05 +00009581 // An implicitly-declared move assignment operator is an inline public
9582 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009583 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9584 SourceLocation ClassLoc = ClassDecl->getLocation();
9585 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009586 CXXMethodDecl *MoveAssignment =
9587 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9588 /*TInfo=*/0, /*StorageClass=*/SC_None,
9589 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009590 MoveAssignment->setAccess(AS_public);
9591 MoveAssignment->setDefaulted();
9592 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009593
Richard Smithd3b5c9082012-07-27 04:22:15 +00009594 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009595 FunctionProtoType::ExtProtoInfo EPI =
9596 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009597 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009598
Sebastian Redl22653ba2011-08-30 19:58:05 +00009599 // Add the parameter to the operator.
9600 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9601 ClassLoc, ClassLoc, /*Id=*/0,
9602 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009603 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009604 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009605
Richard Smith6b02d462012-12-08 08:32:28 +00009606 AddOverriddenMethods(ClassDecl, MoveAssignment);
9607
9608 MoveAssignment->setTrivial(
9609 ClassDecl->needsOverloadResolutionForMoveAssignment()
9610 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9611 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009612
Richard Smithd951a1d2012-02-18 02:02:13 +00009613 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009614 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9615 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009616 }
9617
Richard Smith6b02d462012-12-08 08:32:28 +00009618 // Note that we have added this copy-assignment operator.
9619 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9620
Sebastian Redl22653ba2011-08-30 19:58:05 +00009621 if (Scope *S = getScopeForContext(ClassDecl))
9622 PushOnScopeChains(MoveAssignment, S, false);
9623 ClassDecl->addDecl(MoveAssignment);
9624
Sebastian Redl22653ba2011-08-30 19:58:05 +00009625 return MoveAssignment;
9626}
9627
Richard Smithb2504bd2013-11-04 04:26:14 +00009628/// Check if we're implicitly defining a move assignment operator for a class
9629/// with virtual bases. Such a move assignment might move-assign the virtual
9630/// base multiple times.
9631static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9632 SourceLocation CurrentLocation) {
9633 assert(!Class->isDependentContext() && "should not define dependent move");
9634
9635 // Only a virtual base could get implicitly move-assigned multiple times.
9636 // Only a non-trivial move assignment can observe this. We only want to
9637 // diagnose if we implicitly define an assignment operator that assigns
9638 // two base classes, both of which move-assign the same virtual base.
9639 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9640 Class->getNumBases() < 2)
9641 return;
9642
9643 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9644 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9645 VBaseMap VBases;
9646
Aaron Ballman574705e2014-03-13 15:41:46 +00009647 for (auto &BI : Class->bases()) {
9648 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009649 while (!Worklist.empty()) {
9650 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9651 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9652
9653 // If the base has no non-trivial move assignment operators,
9654 // we don't care about moves from it.
9655 if (!Base->hasNonTrivialMoveAssignment())
9656 continue;
9657
9658 // If there's nothing virtual here, skip it.
9659 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9660 continue;
9661
9662 // If we're not actually going to call a move assignment for this base,
9663 // or the selected move assignment is trivial, skip it.
9664 Sema::SpecialMemberOverloadResult *SMOR =
9665 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9666 /*ConstArg*/false, /*VolatileArg*/false,
9667 /*RValueThis*/true, /*ConstThis*/false,
9668 /*VolatileThis*/false);
9669 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9670 !SMOR->getMethod()->isMoveAssignmentOperator())
9671 continue;
9672
9673 if (BaseSpec->isVirtual()) {
9674 // We're going to move-assign this virtual base, and its move
9675 // assignment operator is not trivial. If this can happen for
9676 // multiple distinct direct bases of Class, diagnose it. (If it
9677 // only happens in one base, we'll diagnose it when synthesizing
9678 // that base class's move assignment operator.)
9679 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +00009680 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +00009681 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +00009682 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009683 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9684 << Class << Base;
9685 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9686 << (Base->getCanonicalDecl() ==
9687 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9688 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +00009689 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +00009690 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +00009691 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9692 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +00009693
9694 // Only diagnose each vbase once.
9695 Existing = 0;
9696 }
9697 } else {
9698 // Only walk over bases that have defaulted move assignment operators.
9699 // We assume that any user-provided move assignment operator handles
9700 // the multiple-moves-of-vbase case itself somehow.
9701 if (!SMOR->getMethod()->isDefaulted())
9702 continue;
9703
9704 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +00009705 for (auto &BI : Base->bases())
9706 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009707 }
9708 }
9709 }
9710}
9711
Sebastian Redl22653ba2011-08-30 19:58:05 +00009712void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9713 CXXMethodDecl *MoveAssignOperator) {
9714 assert((MoveAssignOperator->isDefaulted() &&
9715 MoveAssignOperator->isOverloadedOperator() &&
9716 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009717 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9718 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009719 "DefineImplicitMoveAssignment called for wrong function");
9720
9721 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9722
9723 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9724 MoveAssignOperator->setInvalidDecl();
9725 return;
9726 }
9727
Eli Friedman276dd182013-09-05 00:02:25 +00009728 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009729
Eli Friedmaneaf34142012-10-18 20:14:08 +00009730 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009731 DiagnosticErrorTrap Trap(Diags);
9732
9733 // C++0x [class.copy]p28:
9734 // The implicitly-defined or move assignment operator for a non-union class
9735 // X performs memberwise move assignment of its subobjects. The direct base
9736 // classes of X are assigned first, in the order of their declaration in the
9737 // base-specifier-list, and then the immediate non-static data members of X
9738 // are assigned, in the order in which they were declared in the class
9739 // definition.
9740
Richard Smithb2504bd2013-11-04 04:26:14 +00009741 // Issue a warning if our implicit move assignment operator will move
9742 // from a virtual base more than once.
9743 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009744
Sebastian Redl22653ba2011-08-30 19:58:05 +00009745 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009746 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009747
9748 // The parameter for the "other" object, which we are move from.
9749 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9750 QualType OtherRefType = Other->getType()->
9751 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009752 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009753 "Bad argument type of defaulted move assignment");
9754
9755 // Our location for everything implicitly-generated.
9756 SourceLocation Loc = MoveAssignOperator->getLocation();
9757
Pavel Labath58934982013-08-30 08:52:28 +00009758 // Builds a reference to the "other" object.
9759 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009760 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009761 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009762
Pavel Labath58934982013-08-30 08:52:28 +00009763 // Builds the "this" pointer.
9764 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009765
Sebastian Redl22653ba2011-08-30 19:58:05 +00009766 // Assign base classes.
9767 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009768 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009769 // C++11 [class.copy]p28:
9770 // It is unspecified whether subobjects representing virtual base classes
9771 // are assigned more than once by the implicitly-defined copy assignment
9772 // operator.
9773 // FIXME: Do not assign to a vbase that will be assigned by some other base
9774 // class. For a move-assignment, this can result in the vbase being moved
9775 // multiple times.
9776
Sebastian Redl22653ba2011-08-30 19:58:05 +00009777 // Form the assignment:
9778 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009779 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009780 if (!BaseType->isRecordType()) {
9781 Invalid = true;
9782 continue;
9783 }
9784
9785 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009786 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009787
9788 // Construct the "from" expression, which is an implicit cast to the
9789 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009790 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009791
9792 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009793 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009794
9795 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009796 CastBuilder To(DerefThis,
9797 Context.getCVRQualifiedType(
9798 BaseType, MoveAssignOperator->getTypeQualifiers()),
9799 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009800
9801 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009802 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009803 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009804 /*CopyingBaseSubobject=*/true,
9805 /*Copying=*/false);
9806 if (Move.isInvalid()) {
9807 Diag(CurrentLocation, diag::note_member_synthesized_at)
9808 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9809 MoveAssignOperator->setInvalidDecl();
9810 return;
9811 }
9812
9813 // Success! Record the move.
9814 Statements.push_back(Move.takeAs<Expr>());
9815 }
9816
Sebastian Redl22653ba2011-08-30 19:58:05 +00009817 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009818 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009819 if (Field->isUnnamedBitfield())
9820 continue;
9821
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009822 if (Field->isInvalidDecl()) {
9823 Invalid = true;
9824 continue;
9825 }
9826
Sebastian Redl22653ba2011-08-30 19:58:05 +00009827 // Check for members of reference type; we can't move those.
9828 if (Field->getType()->isReferenceType()) {
9829 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9830 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9831 Diag(Field->getLocation(), diag::note_declared_at);
9832 Diag(CurrentLocation, diag::note_member_synthesized_at)
9833 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9834 Invalid = true;
9835 continue;
9836 }
9837
9838 // Check for members of const-qualified, non-class type.
9839 QualType BaseType = Context.getBaseElementType(Field->getType());
9840 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9841 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9842 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9843 Diag(Field->getLocation(), diag::note_declared_at);
9844 Diag(CurrentLocation, diag::note_member_synthesized_at)
9845 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9846 Invalid = true;
9847 continue;
9848 }
9849
9850 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009851 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9852 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009853
9854 QualType FieldType = Field->getType().getNonReferenceType();
9855 if (FieldType->isIncompleteArrayType()) {
9856 assert(ClassDecl->hasFlexibleArrayMember() &&
9857 "Incomplete array type is not valid");
9858 continue;
9859 }
9860
9861 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009862 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9863 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009864 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009865 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009866 MemberBuilder From(MoveOther, OtherRefType,
9867 /*IsArrow=*/false, MemberLookup);
9868 MemberBuilder To(This, getCurrentThisType(),
9869 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009870
Pavel Labath58934982013-08-30 08:52:28 +00009871 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +00009872 "Member reference with rvalue base must be rvalue except for reference "
9873 "members, which aren't allowed for move assignment.");
9874
Sebastian Redl22653ba2011-08-30 19:58:05 +00009875 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009876 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009877 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009878 /*CopyingBaseSubobject=*/false,
9879 /*Copying=*/false);
9880 if (Move.isInvalid()) {
9881 Diag(CurrentLocation, diag::note_member_synthesized_at)
9882 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9883 MoveAssignOperator->setInvalidDecl();
9884 return;
9885 }
Richard Smith11d19592012-11-12 23:33:00 +00009886
Sebastian Redl22653ba2011-08-30 19:58:05 +00009887 // Success! Record the copy.
9888 Statements.push_back(Move.takeAs<Stmt>());
9889 }
9890
9891 if (!Invalid) {
9892 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009893 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00009894
9895 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9896 if (Return.isInvalid())
9897 Invalid = true;
9898 else {
9899 Statements.push_back(Return.takeAs<Stmt>());
9900
9901 if (Trap.hasErrorOccurred()) {
9902 Diag(CurrentLocation, diag::note_member_synthesized_at)
9903 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9904 Invalid = true;
9905 }
9906 }
9907 }
9908
9909 if (Invalid) {
9910 MoveAssignOperator->setInvalidDecl();
9911 return;
9912 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009913
9914 StmtResult Body;
9915 {
9916 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009917 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009918 /*isStmtExpr=*/false);
9919 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9920 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00009921 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9922
9923 if (ASTMutationListener *L = getASTMutationListener()) {
9924 L->CompletedImplicitDefinition(MoveAssignOperator);
9925 }
9926}
9927
Richard Smithd3b5c9082012-07-27 04:22:15 +00009928Sema::ImplicitExceptionSpecification
9929Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9930 CXXRecordDecl *ClassDecl = MD->getParent();
9931
9932 ImplicitExceptionSpecification ExceptSpec(*this);
9933 if (ClassDecl->isInvalidDecl())
9934 return ExceptSpec;
9935
9936 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009937 assert(T->getNumParams() >= 1 && "not a copy ctor");
9938 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009939
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009940 // C++ [except.spec]p14:
9941 // An implicitly declared special member function (Clause 12) shall have an
9942 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +00009943 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009944 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +00009945 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009946 continue;
9947
Douglas Gregora6d69502010-07-02 23:41:54 +00009948 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009949 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00009950 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00009951 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +00009952 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009953 }
Aaron Ballman445a9392014-03-13 16:15:17 +00009954 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00009955 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009956 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00009957 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00009958 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +00009959 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009960 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009961 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009962 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00009963 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9964 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +00009965 LookupCopyingConstructor(FieldClassDecl,
9966 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +00009967 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009968 }
9969 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009970
Richard Smithd3b5c9082012-07-27 04:22:15 +00009971 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +00009972}
9973
9974CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9975 CXXRecordDecl *ClassDecl) {
9976 // C++ [class.copy]p4:
9977 // If the class definition does not explicitly declare a copy
9978 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +00009979 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +00009980
Richard Smith8bf22e52012-11-29 01:34:07 +00009981 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9982 if (DSM.isAlreadyBeingDeclared())
9983 return 0;
9984
Alexis Hunt913820d2011-05-13 06:10:58 +00009985 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9986 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +00009987 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +00009988 if (Const)
9989 ArgType = ArgType.withConst();
9990 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +00009991
Richard Smithb5800092012-06-10 05:43:50 +00009992 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9993 CXXCopyConstructor,
9994 Const);
9995
Douglas Gregor54be3392010-07-01 17:57:27 +00009996 DeclarationName Name
9997 = Context.DeclarationNames.getCXXConstructorName(
9998 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009999 SourceLocation ClassLoc = ClassDecl->getLocation();
10000 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010001
10002 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010003 // member of its class.
10004 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010005 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010006 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010007 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010008 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010009 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010010
Richard Smithd3b5c9082012-07-27 04:22:15 +000010011 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010012 FunctionProtoType::ExtProtoInfo EPI =
10013 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010014 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010015 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010016
Douglas Gregor54be3392010-07-01 17:57:27 +000010017 // Add the parameter to the constructor.
10018 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010019 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +000010020 /*IdentifierInfo=*/0,
10021 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +000010022 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010023 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010024
Richard Smith6b02d462012-12-08 08:32:28 +000010025 CopyConstructor->setTrivial(
10026 ClassDecl->needsOverloadResolutionForCopyConstructor()
10027 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10028 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010029
Richard Smith852265f2012-03-30 20:53:28 +000010030 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010031 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010032
Richard Smith6b02d462012-12-08 08:32:28 +000010033 // Note that we have declared this constructor.
10034 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10035
10036 if (Scope *S = getScopeForContext(ClassDecl))
10037 PushOnScopeChains(CopyConstructor, S, false);
10038 ClassDecl->addDecl(CopyConstructor);
10039
Douglas Gregor54be3392010-07-01 17:57:27 +000010040 return CopyConstructor;
10041}
10042
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010043void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010044 CXXConstructorDecl *CopyConstructor) {
10045 assert((CopyConstructor->isDefaulted() &&
10046 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010047 !CopyConstructor->doesThisDeclarationHaveABody() &&
10048 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010049 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010050
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010051 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010052 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010053
Richard Smithd577fbb2013-06-13 03:23:42 +000010054 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010055 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010056 // deprecated if the class has a user-declared copy assignment operator
10057 // or a user-declared destructor.
10058 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10059 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10060
Eli Friedmaneaf34142012-10-18 20:14:08 +000010061 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010062 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010063
David Blaikie3fc2f912013-01-17 05:26:25 +000010064 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010065 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010066 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010067 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010068 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010069 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010070 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010071 CopyConstructor->setBody(ActOnCompoundStmt(
10072 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10073 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010074 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010075
Eli Friedman276dd182013-09-05 00:02:25 +000010076 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010077 if (ASTMutationListener *L = getASTMutationListener()) {
10078 L->CompletedImplicitDefinition(CopyConstructor);
10079 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010080}
10081
Sebastian Redl22653ba2011-08-30 19:58:05 +000010082Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010083Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10084 CXXRecordDecl *ClassDecl = MD->getParent();
10085
Sebastian Redl22653ba2011-08-30 19:58:05 +000010086 // C++ [except.spec]p14:
10087 // An implicitly declared special member function (Clause 12) shall have an
10088 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010089 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010090 if (ClassDecl->isInvalidDecl())
10091 return ExceptSpec;
10092
10093 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010094 for (const auto &B : ClassDecl->bases()) {
10095 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010096 continue;
10097
Aaron Ballman574705e2014-03-13 15:41:46 +000010098 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010099 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010100 CXXConstructorDecl *Constructor =
10101 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010102 // If this is a deleted function, add it anyway. This might be conformant
10103 // with the standard. This might not. I'm not sure. It might not matter.
10104 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010105 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010106 }
10107 }
10108
10109 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010110 for (const auto &B : ClassDecl->vbases()) {
10111 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010112 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010113 CXXConstructorDecl *Constructor =
10114 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010115 // If this is a deleted function, add it anyway. This might be conformant
10116 // with the standard. This might not. I'm not sure. It might not matter.
10117 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010118 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010119 }
10120 }
10121
10122 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010123 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010124 QualType FieldType = Context.getBaseElementType(F->getType());
10125 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10126 CXXConstructorDecl *Constructor =
10127 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010128 // If this is a deleted function, add it anyway. This might be conformant
10129 // with the standard. This might not. I'm not sure. It might not matter.
10130 // In particular, the problem is that this function never gets called. It
10131 // might just be ill-formed because this function attempts to refer to
10132 // a deleted function here.
10133 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010134 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010135 }
10136 }
10137
10138 return ExceptSpec;
10139}
10140
10141CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10142 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010143 assert(ClassDecl->needsImplicitMoveConstructor());
10144
Richard Smith8bf22e52012-11-29 01:34:07 +000010145 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10146 if (DSM.isAlreadyBeingDeclared())
10147 return 0;
10148
Sebastian Redl22653ba2011-08-30 19:58:05 +000010149 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10150 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010151
Richard Smithb5800092012-06-10 05:43:50 +000010152 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10153 CXXMoveConstructor,
10154 false);
10155
Sebastian Redl22653ba2011-08-30 19:58:05 +000010156 DeclarationName Name
10157 = Context.DeclarationNames.getCXXConstructorName(
10158 Context.getCanonicalType(ClassType));
10159 SourceLocation ClassLoc = ClassDecl->getLocation();
10160 DeclarationNameInfo NameInfo(Name, ClassLoc);
10161
Richard Smith99005e62013-05-07 03:19:20 +000010162 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010163 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010164 // member of its class.
10165 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010166 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010167 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010168 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010169 MoveConstructor->setAccess(AS_public);
10170 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010171
Richard Smithd3b5c9082012-07-27 04:22:15 +000010172 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010173 FunctionProtoType::ExtProtoInfo EPI =
10174 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010175 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010176 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010177
Sebastian Redl22653ba2011-08-30 19:58:05 +000010178 // Add the parameter to the constructor.
10179 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10180 ClassLoc, ClassLoc,
10181 /*IdentifierInfo=*/0,
10182 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010183 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010184 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010185
Richard Smith6b02d462012-12-08 08:32:28 +000010186 MoveConstructor->setTrivial(
10187 ClassDecl->needsOverloadResolutionForMoveConstructor()
10188 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10189 : ClassDecl->hasTrivialMoveConstructor());
10190
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010191 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010192 ClassDecl->setImplicitMoveConstructorIsDeleted();
10193 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010194 }
10195
10196 // Note that we have declared this constructor.
10197 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10198
10199 if (Scope *S = getScopeForContext(ClassDecl))
10200 PushOnScopeChains(MoveConstructor, S, false);
10201 ClassDecl->addDecl(MoveConstructor);
10202
10203 return MoveConstructor;
10204}
10205
10206void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10207 CXXConstructorDecl *MoveConstructor) {
10208 assert((MoveConstructor->isDefaulted() &&
10209 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010210 !MoveConstructor->doesThisDeclarationHaveABody() &&
10211 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010212 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10213
10214 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10215 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10216
Eli Friedmaneaf34142012-10-18 20:14:08 +000010217 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010218 DiagnosticErrorTrap Trap(Diags);
10219
David Blaikie3fc2f912013-01-17 05:26:25 +000010220 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010221 Trap.hasErrorOccurred()) {
10222 Diag(CurrentLocation, diag::note_member_synthesized_at)
10223 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10224 MoveConstructor->setInvalidDecl();
10225 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010226 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010227 MoveConstructor->setBody(ActOnCompoundStmt(
10228 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10229 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010230 }
10231
Eli Friedman276dd182013-09-05 00:02:25 +000010232 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010233
10234 if (ASTMutationListener *L = getASTMutationListener()) {
10235 L->CompletedImplicitDefinition(MoveConstructor);
10236 }
10237}
10238
Douglas Gregor74f7d502012-02-15 19:33:52 +000010239bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010240 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010241}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010242
10243void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010244 SourceLocation CurrentLocation,
10245 CXXConversionDecl *Conv) {
10246 CXXRecordDecl *Lambda = Conv->getParent();
10247 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10248 // If we are defining a specialization of a conversion to function-ptr
10249 // cache the deduced template arguments for this specialization
10250 // so that we can use them to retrieve the corresponding call-operator
10251 // and static-invoker.
10252 const TemplateArgumentList *DeducedTemplateArgs = 0;
10253
Douglas Gregor355efbb2012-02-17 03:02:34 +000010254
Faisal Vali571df122013-09-29 08:45:24 +000010255 // Retrieve the corresponding call-operator specialization.
10256 if (Lambda->isGenericLambda()) {
10257 assert(Conv->isFunctionTemplateSpecialization());
10258 FunctionTemplateDecl *CallOpTemplate =
10259 CallOp->getDescribedFunctionTemplate();
10260 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10261 void *InsertPos = 0;
10262 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10263 DeducedTemplateArgs->data(),
10264 DeducedTemplateArgs->size(),
10265 InsertPos);
10266 assert(CallOpSpec &&
10267 "Conversion operator must have a corresponding call operator");
10268 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10269 }
10270 // Mark the call operator referenced (and add to pending instantiations
10271 // if necessary).
10272 // For both the conversion and static-invoker template specializations
10273 // we construct their body's in this function, so no need to add them
10274 // to the PendingInstantiations.
10275 MarkFunctionReferenced(CurrentLocation, CallOp);
10276
Eli Friedmaneaf34142012-10-18 20:14:08 +000010277 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010278 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010279
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010280 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010281 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10282 // ... and get the corresponding specialization for a generic lambda.
10283 if (Lambda->isGenericLambda()) {
10284 assert(DeducedTemplateArgs &&
10285 "Must have deduced template arguments from Conversion Operator");
10286 FunctionTemplateDecl *InvokeTemplate =
10287 Invoker->getDescribedFunctionTemplate();
10288 void *InsertPos = 0;
10289 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10290 DeducedTemplateArgs->data(),
10291 DeducedTemplateArgs->size(),
10292 InsertPos);
10293 assert(InvokeSpec &&
10294 "Must have a corresponding static invoker specialization");
10295 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10296 }
10297 // Construct the body of the conversion function { return __invoke; }.
10298 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10299 VK_LValue, Conv->getLocation()).take();
10300 assert(FunctionRef && "Can't refer to __invoke function?");
10301 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10302 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10303 Conv->getLocation(),
10304 Conv->getLocation()));
10305
10306 Conv->markUsed(Context);
10307 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010308
Faisal Vali571df122013-09-29 08:45:24 +000010309 // Fill in the __invoke function with a dummy implementation. IR generation
10310 // will fill in the actual details.
10311 Invoker->markUsed(Context);
10312 Invoker->setReferenced();
10313 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10314
Douglas Gregord3b672c2012-02-16 01:06:16 +000010315 if (ASTMutationListener *L = getASTMutationListener()) {
10316 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010317 L->CompletedImplicitDefinition(Invoker);
10318 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010319}
10320
Faisal Vali571df122013-09-29 08:45:24 +000010321
10322
Douglas Gregord3b672c2012-02-16 01:06:16 +000010323void Sema::DefineImplicitLambdaToBlockPointerConversion(
10324 SourceLocation CurrentLocation,
10325 CXXConversionDecl *Conv)
10326{
Faisal Vali850da1a2013-09-29 17:08:32 +000010327 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010328
Eli Friedman276dd182013-09-05 00:02:25 +000010329 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010330
Eli Friedmaneaf34142012-10-18 20:14:08 +000010331 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010332 DiagnosticErrorTrap Trap(Diags);
10333
Douglas Gregored90df32012-02-22 05:02:47 +000010334 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010335 Expr *This = ActOnCXXThis(CurrentLocation).take();
10336 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010337
Eli Friedman98b01ed2012-03-01 04:01:32 +000010338 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10339 Conv->getLocation(),
10340 Conv, DerefThis);
10341
10342 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10343 // behavior. Note that only the general conversion function does this
10344 // (since it's unusable otherwise); in the case where we inline the
10345 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010346 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010347 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10348 CK_CopyAndAutoreleaseBlockObject,
10349 BuildBlock.get(), 0, VK_RValue);
10350
10351 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010352 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010353 Conv->setInvalidDecl();
10354 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010355 }
Douglas Gregored90df32012-02-22 05:02:47 +000010356
Douglas Gregored90df32012-02-22 05:02:47 +000010357 // Create the return statement that returns the block from the conversion
10358 // function.
Eli Friedman98b01ed2012-03-01 04:01:32 +000010359 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010360 if (Return.isInvalid()) {
10361 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10362 Conv->setInvalidDecl();
10363 return;
10364 }
10365
10366 // Set the body of the conversion function.
10367 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010368 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010369 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010370 Conv->getLocation()));
10371
Douglas Gregored90df32012-02-22 05:02:47 +000010372 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010373 if (ASTMutationListener *L = getASTMutationListener()) {
10374 L->CompletedImplicitDefinition(Conv);
10375 }
10376}
10377
Douglas Gregord2f70072012-03-10 06:53:13 +000010378/// \brief Determine whether the given list arguments contains exactly one
10379/// "real" (non-default) argument.
10380static bool hasOneRealArgument(MultiExprArg Args) {
10381 switch (Args.size()) {
10382 case 0:
10383 return false;
10384
10385 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010386 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010387 return false;
10388
10389 // fall through
10390 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010391 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010392 }
10393
10394 return false;
10395}
10396
John McCalldadc5752010-08-24 06:29:42 +000010397ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010398Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010399 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010400 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010401 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010402 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010403 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010404 unsigned ConstructKind,
10405 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010406 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010407
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010408 // C++0x [class.copy]p34:
10409 // When certain criteria are met, an implementation is allowed to
10410 // omit the copy/move construction of a class object, even if the
10411 // copy/move constructor and/or destructor for the object have
10412 // side effects. [...]
10413 // - when a temporary class object that has not been bound to a
10414 // reference (12.2) would be copied/moved to a class object
10415 // with the same cv-unqualified type, the copy/move operation
10416 // can be omitted by constructing the temporary object
10417 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010418 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010419 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010420 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010421 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010422 }
Mike Stump11289f42009-09-09 15:08:12 +000010423
10424 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010425 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010426 IsListInitialization, RequiresZeroInit,
10427 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010428}
10429
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010430/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10431/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010432ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010433Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10434 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010435 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010436 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010437 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010438 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010439 unsigned ConstructKind,
10440 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010441 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010442 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010443 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010444 HadMultipleCandidates,
10445 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010446 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10447 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010448}
10449
John McCall03c48482010-02-02 09:10:11 +000010450void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010451 if (VD->isInvalidDecl()) return;
10452
John McCall03c48482010-02-02 09:10:11 +000010453 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010454 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010455 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010456 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010457
Chandler Carruth86d17d32011-03-27 21:26:48 +000010458 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010459 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010460 CheckDestructorAccess(VD->getLocation(), Destructor,
10461 PDiag(diag::err_access_dtor_var)
10462 << VD->getDeclName()
10463 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010464 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010465
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010466 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010467 if (!VD->hasGlobalStorage()) return;
10468
10469 // Emit warning for non-trivial dtor in global scope (a real global,
10470 // class-static, function-static).
10471 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10472
10473 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010474 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000010475 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010476}
10477
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010478/// \brief Given a constructor and the set of arguments provided for the
10479/// constructor, convert the arguments and add any required default arguments
10480/// to form a proper call to this constructor.
10481///
10482/// \returns true if an error occurred, false otherwise.
10483bool
10484Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10485 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010486 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010487 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010488 bool AllowExplicit,
10489 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010490 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10491 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010492 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010493
10494 const FunctionProtoType *Proto
10495 = Constructor->getType()->getAs<FunctionProtoType>();
10496 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010497 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010498
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010499 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010500 if (NumArgs < NumParams)
10501 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010502 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010503 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010504
10505 VariadicCallType CallType =
10506 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010507 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010508 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010509 Proto, 0,
10510 llvm::makeArrayRef(Args, NumArgs),
10511 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010512 CallType, AllowExplicit,
10513 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010514 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010515
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010516 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010517
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010518 CheckConstructorCall(Constructor,
10519 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10520 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010521 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010522
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010523 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010524}
10525
Anders Carlssone363c8e2009-12-12 00:32:00 +000010526static inline bool
10527CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10528 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010529 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010530 if (isa<NamespaceDecl>(DC)) {
10531 return SemaRef.Diag(FnDecl->getLocation(),
10532 diag::err_operator_new_delete_declared_in_namespace)
10533 << FnDecl->getDeclName();
10534 }
10535
10536 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010537 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010538 return SemaRef.Diag(FnDecl->getLocation(),
10539 diag::err_operator_new_delete_declared_static)
10540 << FnDecl->getDeclName();
10541 }
10542
Anders Carlsson60659a82009-12-12 02:43:16 +000010543 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010544}
10545
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010546static inline bool
10547CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10548 CanQualType ExpectedResultType,
10549 CanQualType ExpectedFirstParamType,
10550 unsigned DependentParamTypeDiag,
10551 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010552 QualType ResultType =
10553 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010554
10555 // Check that the result type is not dependent.
10556 if (ResultType->isDependentType())
10557 return SemaRef.Diag(FnDecl->getLocation(),
10558 diag::err_operator_new_delete_dependent_result_type)
10559 << FnDecl->getDeclName() << ExpectedResultType;
10560
10561 // Check that the result type is what we expect.
10562 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10563 return SemaRef.Diag(FnDecl->getLocation(),
10564 diag::err_operator_new_delete_invalid_result_type)
10565 << FnDecl->getDeclName() << ExpectedResultType;
10566
10567 // A function template must have at least 2 parameters.
10568 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10569 return SemaRef.Diag(FnDecl->getLocation(),
10570 diag::err_operator_new_delete_template_too_few_parameters)
10571 << FnDecl->getDeclName();
10572
10573 // The function decl must have at least 1 parameter.
10574 if (FnDecl->getNumParams() == 0)
10575 return SemaRef.Diag(FnDecl->getLocation(),
10576 diag::err_operator_new_delete_too_few_parameters)
10577 << FnDecl->getDeclName();
10578
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010579 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010580 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10581 if (FirstParamType->isDependentType())
10582 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10583 << FnDecl->getDeclName() << ExpectedFirstParamType;
10584
10585 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010586 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010587 ExpectedFirstParamType)
10588 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10589 << FnDecl->getDeclName() << ExpectedFirstParamType;
10590
10591 return false;
10592}
10593
Anders Carlsson12308f42009-12-11 23:23:22 +000010594static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010595CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010596 // C++ [basic.stc.dynamic.allocation]p1:
10597 // A program is ill-formed if an allocation function is declared in a
10598 // namespace scope other than global scope or declared static in global
10599 // scope.
10600 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10601 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010602
10603 CanQualType SizeTy =
10604 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10605
10606 // C++ [basic.stc.dynamic.allocation]p1:
10607 // The return type shall be void*. The first parameter shall have type
10608 // std::size_t.
10609 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10610 SizeTy,
10611 diag::err_operator_new_dependent_param_type,
10612 diag::err_operator_new_param_type))
10613 return true;
10614
10615 // C++ [basic.stc.dynamic.allocation]p1:
10616 // The first parameter shall not have an associated default argument.
10617 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010618 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010619 diag::err_operator_new_default_arg)
10620 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10621
10622 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010623}
10624
10625static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010626CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010627 // C++ [basic.stc.dynamic.deallocation]p1:
10628 // A program is ill-formed if deallocation functions are declared in a
10629 // namespace scope other than global scope or declared static in global
10630 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010631 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10632 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010633
10634 // C++ [basic.stc.dynamic.deallocation]p2:
10635 // Each deallocation function shall return void and its first parameter
10636 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010637 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10638 SemaRef.Context.VoidPtrTy,
10639 diag::err_operator_delete_dependent_param_type,
10640 diag::err_operator_delete_param_type))
10641 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010642
Anders Carlsson12308f42009-12-11 23:23:22 +000010643 return false;
10644}
10645
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010646/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10647/// of this overloaded operator is well-formed. If so, returns false;
10648/// otherwise, emits appropriate diagnostics and returns true.
10649bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010650 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010651 "Expected an overloaded operator declaration");
10652
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010653 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10654
Mike Stump11289f42009-09-09 15:08:12 +000010655 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010656 // The allocation and deallocation functions, operator new,
10657 // operator new[], operator delete and operator delete[], are
10658 // described completely in 3.7.3. The attributes and restrictions
10659 // found in the rest of this subclause do not apply to them unless
10660 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010661 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010662 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010663
Anders Carlsson22f443f2009-12-12 00:26:23 +000010664 if (Op == OO_New || Op == OO_Array_New)
10665 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010666
10667 // C++ [over.oper]p6:
10668 // An operator function shall either be a non-static member
10669 // function or be a non-member function and have at least one
10670 // parameter whose type is a class, a reference to a class, an
10671 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010672 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10673 if (MethodDecl->isStatic())
10674 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010675 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010676 } else {
10677 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010678 for (auto Param : FnDecl->params()) {
10679 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010680 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10681 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010682 ClassOrEnumParam = true;
10683 break;
10684 }
10685 }
10686
Douglas Gregord69246b2008-11-17 16:14:12 +000010687 if (!ClassOrEnumParam)
10688 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010689 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010690 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010691 }
10692
10693 // C++ [over.oper]p8:
10694 // An operator function cannot have default arguments (8.3.6),
10695 // except where explicitly stated below.
10696 //
Mike Stump11289f42009-09-09 15:08:12 +000010697 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010698 // (C++ [over.call]p1).
10699 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010700 for (auto Param : FnDecl->params()) {
10701 if (Param->hasDefaultArg())
10702 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010703 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010704 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010705 }
10706 }
10707
Douglas Gregor6cf08062008-11-10 13:38:07 +000010708 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10709 { false, false, false }
10710#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10711 , { Unary, Binary, MemberOnly }
10712#include "clang/Basic/OperatorKinds.def"
10713 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010714
Douglas Gregor6cf08062008-11-10 13:38:07 +000010715 bool CanBeUnaryOperator = OperatorUses[Op][0];
10716 bool CanBeBinaryOperator = OperatorUses[Op][1];
10717 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010718
10719 // C++ [over.oper]p8:
10720 // [...] Operator functions cannot have more or fewer parameters
10721 // than the number required for the corresponding operator, as
10722 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010723 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010724 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010725 if (Op != OO_Call &&
10726 ((NumParams == 1 && !CanBeUnaryOperator) ||
10727 (NumParams == 2 && !CanBeBinaryOperator) ||
10728 (NumParams < 1) || (NumParams > 2))) {
10729 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010730 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010731 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010732 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010733 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010734 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010735 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010736 assert(CanBeBinaryOperator &&
10737 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010738 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010739 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010740
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010741 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010742 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010743 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010744
Douglas Gregord69246b2008-11-17 16:14:12 +000010745 // Overloaded operators other than operator() cannot be variadic.
10746 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010747 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010748 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010749 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010750 }
10751
10752 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010753 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10754 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010755 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010756 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010757 }
10758
10759 // C++ [over.inc]p1:
10760 // The user-defined function called operator++ implements the
10761 // prefix and postfix ++ operator. If this function is a member
10762 // function with no parameters, or a non-member function with one
10763 // parameter of class or enumeration type, it defines the prefix
10764 // increment operator ++ for objects of that type. If the function
10765 // is a member function with one parameter (which shall be of type
10766 // int) or a non-member function with two parameters (the second
10767 // of which shall be of type int), it defines the postfix
10768 // increment operator ++ for objects of that type.
10769 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10770 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000010771 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010772
Richard Smith538b52a2014-01-30 22:24:05 +000010773 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10774 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000010775 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010776 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010777 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010778 }
10779
Douglas Gregord69246b2008-11-17 16:14:12 +000010780 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010781}
Chris Lattner3b024a32008-12-17 07:09:26 +000010782
Alexis Huntc88db062010-01-13 09:01:02 +000010783/// CheckLiteralOperatorDeclaration - Check whether the declaration
10784/// of this literal operator function is well-formed. If so, returns
10785/// false; otherwise, emits appropriate diagnostics and returns true.
10786bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010787 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010788 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10789 << FnDecl->getDeclName();
10790 return true;
10791 }
10792
Richard Smith72eebee2012-03-04 09:41:16 +000010793 if (FnDecl->isExternC()) {
10794 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10795 return true;
10796 }
10797
Alexis Huntc88db062010-01-13 09:01:02 +000010798 bool Valid = false;
10799
Richard Smithbcc22fc2012-03-09 08:00:36 +000010800 // This might be the definition of a literal operator template.
10801 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10802 // This might be a specialization of a literal operator template.
10803 if (!TpDecl)
10804 TpDecl = FnDecl->getPrimaryTemplate();
10805
Richard Smithb8b41d32013-10-07 19:57:58 +000010806 // template <char...> type operator "" name() and
10807 // template <class T, T...> type operator "" name() are the only valid
10808 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010809 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010810 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000010811 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000010812 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10813 if (Params->size() == 1) {
10814 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010815 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010816
Alexis Hunt7dd26172010-04-07 23:11:06 +000010817 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010818 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10819 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10820 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000010821 } else if (Params->size() == 2) {
10822 TemplateTypeParmDecl *PmType =
10823 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10824 NonTypeTemplateParmDecl *PmArgs =
10825 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10826
10827 // The second template parameter must be a parameter pack with the
10828 // first template parameter as its type.
10829 if (PmType && PmArgs &&
10830 !PmType->isTemplateParameterPack() &&
10831 PmArgs->isTemplateParameterPack()) {
10832 const TemplateTypeParmType *TArgs =
10833 PmArgs->getType()->getAs<TemplateTypeParmType>();
10834 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10835 TArgs->getIndex() == PmType->getIndex()) {
10836 Valid = true;
10837 if (ActiveTemplateInstantiations.empty())
10838 Diag(FnDecl->getLocation(),
10839 diag::ext_string_literal_operator_template);
10840 }
10841 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000010842 }
10843 }
Richard Smith72eebee2012-03-04 09:41:16 +000010844 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010845 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010846 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10847
Richard Smith72eebee2012-03-04 09:41:16 +000010848 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010849
Alexis Hunt079a6f72010-04-07 22:57:35 +000010850 // unsigned long long int, long double, and any character type are allowed
10851 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010852 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10853 Context.hasSameType(T, Context.LongDoubleTy) ||
10854 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010855 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010856 Context.hasSameType(T, Context.Char16Ty) ||
10857 Context.hasSameType(T, Context.Char32Ty)) {
10858 if (++Param == FnDecl->param_end())
10859 Valid = true;
10860 goto FinishedParams;
10861 }
10862
Alexis Hunt079a6f72010-04-07 22:57:35 +000010863 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000010864 const PointerType *PT = T->getAs<PointerType>();
10865 if (!PT)
10866 goto FinishedParams;
10867 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000010868 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000010869 goto FinishedParams;
10870 T = T.getUnqualifiedType();
10871
10872 // Move on to the second parameter;
10873 ++Param;
10874
10875 // If there is no second parameter, the first must be a const char *
10876 if (Param == FnDecl->param_end()) {
10877 if (Context.hasSameType(T, Context.CharTy))
10878 Valid = true;
10879 goto FinishedParams;
10880 }
10881
10882 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10883 // are allowed as the first parameter to a two-parameter function
10884 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010885 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010886 Context.hasSameType(T, Context.Char16Ty) ||
10887 Context.hasSameType(T, Context.Char32Ty)))
10888 goto FinishedParams;
10889
10890 // The second and final parameter must be an std::size_t
10891 T = (*Param)->getType().getUnqualifiedType();
10892 if (Context.hasSameType(T, Context.getSizeType()) &&
10893 ++Param == FnDecl->param_end())
10894 Valid = true;
10895 }
10896
10897 // FIXME: This diagnostic is absolutely terrible.
10898FinishedParams:
10899 if (!Valid) {
10900 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10901 << FnDecl->getDeclName();
10902 return true;
10903 }
10904
Richard Smith768cecc2012-03-09 08:16:22 +000010905 // A parameter-declaration-clause containing a default argument is not
10906 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010907 for (auto Param : FnDecl->params()) {
10908 if (Param->hasDefaultArg()) {
10909 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000010910 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010911 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000010912 break;
10913 }
10914 }
10915
Richard Smith0df56f42012-03-08 02:39:21 +000010916 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000010917 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10918 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000010919 // C++11 [usrlit.suffix]p1:
10920 // Literal suffix identifiers that do not start with an underscore
10921 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000010922 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10923 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000010924 }
Richard Smith0df56f42012-03-08 02:39:21 +000010925
Alexis Huntc88db062010-01-13 09:01:02 +000010926 return false;
10927}
10928
Douglas Gregor07665a62009-01-05 19:45:36 +000010929/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10930/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000010931/// the '{'. ExternLoc is the location of the 'extern', Lang is the
10932/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000010933/// the '{' brace. Otherwise, this linkage specification does not
10934/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000010935Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000010936 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000010937 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000010938 StringLiteral *Lit = cast<StringLiteral>(LangStr);
10939 if (!Lit->isAscii()) {
10940 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
10941 << LangStr->getSourceRange();
10942 return 0;
10943 }
10944
10945 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000010946 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000010947 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000010948 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000010949 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000010950 Language = LinkageSpecDecl::lang_cxx;
10951 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000010952 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
10953 << LangStr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +000010954 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000010955 }
Mike Stump11289f42009-09-09 15:08:12 +000010956
Chris Lattner438e5012008-12-17 07:13:27 +000010957 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000010958
Richard Smith4ee696d2014-02-17 23:25:27 +000010959 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
10960 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000010961 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000010962 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000010963 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000010964 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000010965}
10966
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000010967/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000010968/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10969/// valid, it's the position of the closing '}' brace in a linkage
10970/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000010971Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000010972 Decl *LinkageSpec,
10973 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000010974 if (RBraceLoc.isValid()) {
10975 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10976 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000010977 }
Richard Smith4ee696d2014-02-17 23:25:27 +000010978 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000010979 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000010980}
10981
Michael Han84324352013-02-22 17:15:32 +000010982Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10983 AttributeList *AttrList,
10984 SourceLocation SemiLoc) {
10985 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10986 // Attribute declarations appertain to empty declaration so we handle
10987 // them here.
10988 if (AttrList)
10989 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000010990
Michael Han84324352013-02-22 17:15:32 +000010991 CurContext->addDecl(ED);
10992 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000010993}
10994
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000010995/// \brief Perform semantic analysis for the variable declaration that
10996/// occurs within a C++ catch clause, returning the newly-created
10997/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000010998VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000010999 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011000 SourceLocation StartLoc,
11001 SourceLocation Loc,
11002 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011003 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011004 QualType ExDeclType = TInfo->getType();
11005
Sebastian Redl54c04d42008-12-22 19:15:10 +000011006 // Arrays and functions decay.
11007 if (ExDeclType->isArrayType())
11008 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11009 else if (ExDeclType->isFunctionType())
11010 ExDeclType = Context.getPointerType(ExDeclType);
11011
11012 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11013 // The exception-declaration shall not denote a pointer or reference to an
11014 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011015 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011016 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011017 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011018 Invalid = true;
11019 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011020
Sebastian Redl54c04d42008-12-22 19:15:10 +000011021 QualType BaseType = ExDeclType;
11022 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011023 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011024 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011025 BaseType = Ptr->getPointeeType();
11026 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011027 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011028 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011029 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011030 BaseType = Ref->getPointeeType();
11031 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011032 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011033 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011034 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011035 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011036 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011037
Mike Stump11289f42009-09-09 15:08:12 +000011038 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011039 RequireNonAbstractType(Loc, ExDeclType,
11040 diag::err_abstract_type_in_decl,
11041 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011042 Invalid = true;
11043
John McCall2ca705e2010-07-24 00:37:23 +000011044 // Only the non-fragile NeXT runtime currently supports C++ catches
11045 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011046 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011047 QualType T = ExDeclType;
11048 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11049 T = RT->getPointeeType();
11050
11051 if (T->isObjCObjectType()) {
11052 Diag(Loc, diag::err_objc_object_catch);
11053 Invalid = true;
11054 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011055 // FIXME: should this be a test for macosx-fragile specifically?
11056 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011057 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011058 }
11059 }
11060
Abramo Bagnaradff19302011-03-08 08:55:46 +000011061 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011062 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011063 ExDecl->setExceptionVariable(true);
11064
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011065 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011066 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011067 Invalid = true;
11068
Douglas Gregor750734c2011-07-06 18:14:43 +000011069 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011070 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011071 // Insulate this from anything else we might currently be parsing.
11072 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11073
Douglas Gregor6de584c2010-03-05 23:38:39 +000011074 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011075 // The object declared in an exception-declaration or, if the
11076 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011077 // copy-initialized (8.5) from the exception object. [...]
11078 // The object is destroyed when the handler exits, after the destruction
11079 // of any automatic objects initialized within the handler.
11080 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011081 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011082 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011083 QualType initType = ExDeclType;
11084
11085 InitializedEntity entity =
11086 InitializedEntity::InitializeVariable(ExDecl);
11087 InitializationKind initKind =
11088 InitializationKind::CreateCopy(Loc, SourceLocation());
11089
11090 Expr *opaqueValue =
11091 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011092 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11093 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011094 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011095 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011096 else {
11097 // If the constructor used was non-trivial, set this as the
11098 // "initializer".
Nick Lewycky0f292892013-09-22 10:06:57 +000011099 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011100 if (!construct->getConstructor()->isTrivial()) {
11101 Expr *init = MaybeCreateExprWithCleanups(construct);
11102 ExDecl->setInit(init);
11103 }
11104
11105 // And make sure it's destructable.
11106 FinalizeVarWithDestructor(ExDecl, recordType);
11107 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011108 }
11109 }
11110
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011111 if (Invalid)
11112 ExDecl->setInvalidDecl();
11113
11114 return ExDecl;
11115}
11116
11117/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11118/// handler.
John McCall48871652010-08-21 09:40:31 +000011119Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011120 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011121 bool Invalid = D.isInvalidType();
11122
11123 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011124 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11125 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011126 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11127 D.getIdentifierLoc());
11128 Invalid = true;
11129 }
11130
Sebastian Redl54c04d42008-12-22 19:15:10 +000011131 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011132 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011133 LookupOrdinaryName,
11134 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011135 // The scope should be freshly made just for us. There is just no way
11136 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000011137 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000011138 if (PrevDecl->isTemplateParameter()) {
11139 // Maybe we will complain about the shadowed template parameter.
11140 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000011141 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011142 }
11143 }
11144
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011145 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011146 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11147 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011148 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011149 }
11150
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011151 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011152 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011153 D.getIdentifierLoc(),
11154 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011155 if (Invalid)
11156 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011157
Sebastian Redl54c04d42008-12-22 19:15:10 +000011158 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011159 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011160 PushOnScopeChains(ExDecl, S);
11161 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011162 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011163
Douglas Gregor758a8692009-06-17 21:51:59 +000011164 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011165 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011166}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011167
Abramo Bagnaraea947882011-03-08 16:41:52 +000011168Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011169 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011170 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011171 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011172 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011173
Richard Smithded9c2e2012-07-11 22:37:56 +000011174 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11175 return 0;
11176
11177 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11178 AssertMessage, RParenLoc, false);
11179}
11180
11181Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11182 Expr *AssertExpr,
11183 StringLiteral *AssertMessage,
11184 SourceLocation RParenLoc,
11185 bool Failed) {
11186 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11187 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011188 // In a static_assert-declaration, the constant-expression shall be a
11189 // constant expression that can be contextually converted to bool.
11190 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11191 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011192 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011193
Richard Smith902ca212011-12-14 23:32:26 +000011194 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011195 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011196 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011197 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011198 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011199
Richard Smithded9c2e2012-07-11 22:37:56 +000011200 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011201 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011202 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000011203 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011204 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011205 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011206 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011207 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011208 }
Mike Stump11289f42009-09-09 15:08:12 +000011209
Abramo Bagnaraea947882011-03-08 16:41:52 +000011210 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011211 AssertExpr, AssertMessage, RParenLoc,
11212 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011213
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011214 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011215 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011216}
Sebastian Redlf769df52009-03-24 22:27:57 +000011217
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011218/// \brief Perform semantic analysis of the given friend type declaration.
11219///
11220/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011221FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011222 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011223 TypeSourceInfo *TSInfo) {
11224 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11225
11226 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011227 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011228
Richard Smithc8239732011-10-18 21:39:00 +000011229 // C++03 [class.friend]p2:
11230 // An elaborated-type-specifier shall be used in a friend declaration
11231 // for a class.*
11232 //
11233 // * The class-key of the elaborated-type-specifier is required.
11234 if (!ActiveTemplateInstantiations.empty()) {
11235 // Do not complain about the form of friend template types during
11236 // template instantiation; we will already have complained when the
11237 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011238 } else {
11239 if (!T->isElaboratedTypeSpecifier()) {
11240 // If we evaluated the type to a record type, suggest putting
11241 // a tag in front.
11242 if (const RecordType *RT = T->getAs<RecordType>()) {
11243 RecordDecl *RD = RT->getDecl();
Richard Smithc8239732011-10-18 21:39:00 +000011244
Nick Lewycky36722d22013-02-06 05:59:33 +000011245 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smithc8239732011-10-18 21:39:00 +000011246
Nick Lewycky36722d22013-02-06 05:59:33 +000011247 Diag(TypeRange.getBegin(),
11248 getLangOpts().CPlusPlus11 ?
11249 diag::warn_cxx98_compat_unelaborated_friend_type :
11250 diag::ext_unelaborated_friend_type)
11251 << (unsigned) RD->getTagKind()
11252 << T
11253 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11254 InsertionText);
11255 } else {
11256 Diag(FriendLoc,
11257 getLangOpts().CPlusPlus11 ?
11258 diag::warn_cxx98_compat_nonclass_type_friend :
11259 diag::ext_nonclass_type_friend)
11260 << T
11261 << TypeRange;
11262 }
11263 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011264 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011265 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011266 diag::warn_cxx98_compat_enum_friend :
11267 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011268 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011269 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011270 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011271
Nick Lewycky36722d22013-02-06 05:59:33 +000011272 // C++11 [class.friend]p3:
11273 // A friend declaration that does not declare a function shall have one
11274 // of the following forms:
11275 // friend elaborated-type-specifier ;
11276 // friend simple-type-specifier ;
11277 // friend typename-specifier ;
11278 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11279 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11280 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011281
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011282 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011283 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011284 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000011285 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011286}
11287
John McCallace48cd2010-10-19 01:40:49 +000011288/// Handle a friend tag declaration where the scope specifier was
11289/// templated.
11290Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11291 unsigned TagSpec, SourceLocation TagLoc,
11292 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011293 IdentifierInfo *Name,
11294 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011295 AttributeList *Attr,
11296 MultiTemplateParamsArg TempParamLists) {
11297 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11298
11299 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011300 bool Invalid = false;
11301
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011302 if (TemplateParameterList *TemplateParams =
11303 MatchTemplateParametersToScopeSpecifier(
11304 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11305 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011306 if (TemplateParams->size() > 0) {
11307 // This is a declaration of a class template.
11308 if (Invalid)
11309 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011310
Eric Christopher6f228b52011-07-21 05:34:24 +000011311 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11312 SS, Name, NameLoc, Attr,
11313 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011314 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011315 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011316 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000011317 } else {
11318 // The "template<>" header is extraneous.
11319 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11320 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11321 isExplicitSpecialization = true;
11322 }
11323 }
11324
11325 if (Invalid) return 0;
11326
John McCallace48cd2010-10-19 01:40:49 +000011327 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011328 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011329 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011330 isAllExplicitSpecializations = false;
11331 break;
11332 }
11333 }
11334
11335 // FIXME: don't ignore attributes.
11336
11337 // If it's explicit specializations all the way down, just forget
11338 // about the template header and build an appropriate non-templated
11339 // friend. TODO: for source fidelity, remember the headers.
11340 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011341 if (SS.isEmpty()) {
11342 bool Owned = false;
11343 bool IsDependent = false;
11344 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011345 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011346 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011347 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011348 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011349 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011350 /*UnderlyingType=*/TypeResult(),
11351 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011352 }
Richard Smith649c7b062014-01-08 00:56:48 +000011353
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011354 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011355 ElaboratedTypeKeyword Keyword
11356 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011357 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011358 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011359 if (T.isNull())
11360 return 0;
11361
11362 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11363 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011364 DependentNameTypeLoc TL =
11365 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011366 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011367 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011368 TL.setNameLoc(NameLoc);
11369 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011370 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011371 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011372 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011373 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011374 }
11375
11376 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011377 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011378 Friend->setAccess(AS_public);
11379 CurContext->addDecl(Friend);
11380 return Friend;
11381 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011382
11383 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11384
11385
John McCallace48cd2010-10-19 01:40:49 +000011386
11387 // Handle the case of a templated-scope friend class. e.g.
11388 // template <class T> class A<T>::B;
11389 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011390 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11391 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011392 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11393 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11394 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011395 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011396 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011397 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011398 TL.setNameLoc(NameLoc);
11399
11400 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011401 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011402 Friend->setAccess(AS_public);
11403 Friend->setUnsupportedFriend(true);
11404 CurContext->addDecl(Friend);
11405 return Friend;
11406}
11407
11408
John McCall11083da2009-09-16 22:47:08 +000011409/// Handle a friend type declaration. This works in tandem with
11410/// ActOnTag.
11411///
11412/// Notes on friend class templates:
11413///
11414/// We generally treat friend class declarations as if they were
11415/// declaring a class. So, for example, the elaborated type specifier
11416/// in a friend declaration is required to obey the restrictions of a
11417/// class-head (i.e. no typedefs in the scope chain), template
11418/// parameters are required to match up with simple template-ids, &c.
11419/// However, unlike when declaring a template specialization, it's
11420/// okay to refer to a template specialization without an empty
11421/// template parameter declaration, e.g.
11422/// friend class A<T>::B<unsigned>;
11423/// We permit this as a special case; if there are any template
11424/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011425/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011426Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011427 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011428 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011429
11430 assert(DS.isFriendSpecified());
11431 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11432
John McCall11083da2009-09-16 22:47:08 +000011433 // Try to convert the decl specifier to a type. This works for
11434 // friend templates because ActOnTag never produces a ClassTemplateDecl
11435 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011436 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011437 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11438 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011439 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011440 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011441
Douglas Gregor6c110f32010-12-16 01:14:37 +000011442 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11443 return 0;
11444
John McCall11083da2009-09-16 22:47:08 +000011445 // This is definitely an error in C++98. It's probably meant to
11446 // be forbidden in C++0x, too, but the specification is just
11447 // poorly written.
11448 //
11449 // The problem is with declarations like the following:
11450 // template <T> friend A<T>::foo;
11451 // where deciding whether a class C is a friend or not now hinges
11452 // on whether there exists an instantiation of A that causes
11453 // 'foo' to equal C. There are restrictions on class-heads
11454 // (which we declare (by fiat) elaborated friend declarations to
11455 // be) that makes this tractable.
11456 //
11457 // FIXME: handle "template <> friend class A<T>;", which
11458 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011459 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011460 Diag(Loc, diag::err_tagless_friend_type_template)
11461 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011462 return 0;
John McCall11083da2009-09-16 22:47:08 +000011463 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011464
John McCallaa74a0c2009-08-28 07:59:38 +000011465 // C++98 [class.friend]p1: A friend of a class is a function
11466 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011467 // This is fixed in DR77, which just barely didn't make the C++03
11468 // deadline. It's also a very silly restriction that seriously
11469 // affects inner classes and which nobody else seems to implement;
11470 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011471 //
11472 // But note that we could warn about it: it's always useless to
11473 // friend one of your own members (it's not, however, worthless to
11474 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011475
John McCall11083da2009-09-16 22:47:08 +000011476 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011477 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011478 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011479 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011480 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011481 TSI,
John McCall11083da2009-09-16 22:47:08 +000011482 DS.getFriendSpecLoc());
11483 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011484 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011485
11486 if (!D)
John McCall48871652010-08-21 09:40:31 +000011487 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011488
John McCall11083da2009-09-16 22:47:08 +000011489 D->setAccess(AS_public);
11490 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011491
John McCall48871652010-08-21 09:40:31 +000011492 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011493}
11494
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011495NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11496 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011497 const DeclSpec &DS = D.getDeclSpec();
11498
11499 assert(DS.isFriendSpecified());
11500 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11501
11502 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011503 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011504
11505 // C++ [class.friend]p1
11506 // A friend of a class is a function or class....
11507 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011508 // It *doesn't* see through dependent types, which is correct
11509 // according to [temp.arg.type]p3:
11510 // If a declaration acquires a function type through a
11511 // type dependent on a template-parameter and this causes
11512 // a declaration that does not use the syntactic form of a
11513 // function declarator to have a function type, the program
11514 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011515 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011516 Diag(Loc, diag::err_unexpected_friend);
11517
11518 // It might be worthwhile to try to recover by creating an
11519 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011520 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011521 }
11522
11523 // C++ [namespace.memdef]p3
11524 // - If a friend declaration in a non-local class first declares a
11525 // class or function, the friend class or function is a member
11526 // of the innermost enclosing namespace.
11527 // - The name of the friend is not found by simple name lookup
11528 // until a matching declaration is provided in that namespace
11529 // scope (either before or after the class declaration granting
11530 // friendship).
11531 // - If a friend function is called, its name may be found by the
11532 // name lookup that considers functions from namespaces and
11533 // classes associated with the types of the function arguments.
11534 // - When looking for a prior declaration of a class or a function
11535 // declared as a friend, scopes outside the innermost enclosing
11536 // namespace scope are not considered.
11537
John McCallde3fd222010-10-12 23:13:28 +000011538 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011539 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11540 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011541 assert(Name);
11542
Douglas Gregor6c110f32010-12-16 01:14:37 +000011543 // Check for unexpanded parameter packs.
11544 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11545 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11546 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11547 return 0;
11548
John McCall07e91c02009-08-06 02:15:43 +000011549 // The context we found the declaration in, or in which we should
11550 // create the declaration.
11551 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011552 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011553 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011554 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011555
Richard Smith114394f2013-08-09 04:35:01 +000011556 // There are five cases here.
11557 // - There's no scope specifier and we're in a local class. Only look
11558 // for functions declared in the immediately-enclosing block scope.
11559 // We recover from invalid scope qualifiers as if they just weren't there.
11560 FunctionDecl *FunctionContainingLocalClass = 0;
11561 if ((SS.isInvalid() || !SS.isSet()) &&
11562 (FunctionContainingLocalClass =
11563 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11564 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011565 // If a friend declaration appears in a local class and the name
11566 // specified is an unqualified name, a prior declaration is
11567 // looked up without considering scopes that are outside the
11568 // innermost enclosing non-class scope. For a friend function
11569 // declaration, if there is no prior declaration, the program is
11570 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011571
11572 // Find the innermost enclosing non-class scope. This is the block
11573 // scope containing the local class definition (or for a nested class,
11574 // the outer local class).
11575 DCScope = S->getFnParent();
11576
11577 // Look up the function name in the scope.
11578 Previous.clear(LookupLocalFriendName);
11579 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11580
11581 if (!Previous.empty()) {
11582 // All possible previous declarations must have the same context:
11583 // either they were declared at block scope or they are members of
11584 // one of the enclosing local classes.
11585 DC = Previous.getRepresentativeDecl()->getDeclContext();
11586 } else {
11587 // This is ill-formed, but provide the context that we would have
11588 // declared the function in, if we were permitted to, for error recovery.
11589 DC = FunctionContainingLocalClass;
11590 }
Richard Smith541b38b2013-09-20 01:15:31 +000011591 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011592
11593 // C++ [class.friend]p6:
11594 // A function can be defined in a friend declaration of a class if and
11595 // only if the class is a non-local class (9.8), the function name is
11596 // unqualified, and the function has namespace scope.
11597 if (D.isFunctionDefinition()) {
11598 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11599 }
11600
11601 // - There's no scope specifier, in which case we just go to the
11602 // appropriate scope and look for a function or function template
11603 // there as appropriate.
11604 } else if (SS.isInvalid() || !SS.isSet()) {
11605 // C++11 [namespace.memdef]p3:
11606 // If the name in a friend declaration is neither qualified nor
11607 // a template-id and the declaration is a function or an
11608 // elaborated-type-specifier, the lookup to determine whether
11609 // the entity has been previously declared shall not consider
11610 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011611 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011612
John McCallf7cfb222010-10-13 05:45:15 +000011613 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011614 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011615
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011616 // Skip class contexts. If someone can cite chapter and verse
11617 // for this behavior, that would be nice --- it's what GCC and
11618 // EDG do, and it seems like a reasonable intent, but the spec
11619 // really only says that checks for unqualified existing
11620 // declarations should stop at the nearest enclosing namespace,
11621 // not that they should only consider the nearest enclosing
11622 // namespace.
11623 while (DC->isRecord())
11624 DC = DC->getParent();
11625
11626 DeclContext *LookupDC = DC;
11627 while (LookupDC->isTransparentContext())
11628 LookupDC = LookupDC->getParent();
11629
11630 while (true) {
11631 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011632
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011633 if (!Previous.empty()) {
11634 DC = LookupDC;
11635 break;
John McCallf4776592010-10-14 22:22:28 +000011636 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011637
11638 if (isTemplateId) {
11639 if (isa<TranslationUnitDecl>(LookupDC)) break;
11640 } else {
11641 if (LookupDC->isFileContext()) break;
11642 }
11643 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011644 }
11645
John McCallccbc0322010-10-13 06:22:15 +000011646 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011647
John McCallde3fd222010-10-12 23:13:28 +000011648 // - There's a non-dependent scope specifier, in which case we
11649 // compute it and do a previous lookup there for a function
11650 // or function template.
11651 } else if (!SS.getScopeRep()->isDependent()) {
11652 DC = computeDeclContext(SS);
11653 if (!DC) return 0;
11654
11655 if (RequireCompleteDeclContext(SS, DC)) return 0;
11656
11657 LookupQualifiedName(Previous, DC);
11658
11659 // Ignore things found implicitly in the wrong scope.
11660 // TODO: better diagnostics for this case. Suggesting the right
11661 // qualified scope would be nice...
11662 LookupResult::Filter F = Previous.makeFilter();
11663 while (F.hasNext()) {
11664 NamedDecl *D = F.next();
11665 if (!DC->InEnclosingNamespaceSetOf(
11666 D->getDeclContext()->getRedeclContext()))
11667 F.erase();
11668 }
11669 F.done();
11670
11671 if (Previous.empty()) {
11672 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011673 Diag(Loc, diag::err_qualified_friend_not_found)
11674 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011675 return 0;
11676 }
11677
11678 // C++ [class.friend]p1: A friend of a class is a function or
11679 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011680 if (DC->Equals(CurContext))
11681 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011682 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011683 diag::warn_cxx98_compat_friend_is_member :
11684 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011685
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011686 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011687 // C++ [class.friend]p6:
11688 // A function can be defined in a friend declaration of a class if and
11689 // only if the class is a non-local class (9.8), the function name is
11690 // unqualified, and the function has namespace scope.
11691 SemaDiagnosticBuilder DB
11692 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11693
11694 DB << SS.getScopeRep();
11695 if (DC->isFileContext())
11696 DB << FixItHint::CreateRemoval(SS.getRange());
11697 SS.clear();
11698 }
John McCallde3fd222010-10-12 23:13:28 +000011699
11700 // - There's a scope specifier that does not match any template
11701 // parameter lists, in which case we use some arbitrary context,
11702 // create a method or method template, and wait for instantiation.
11703 // - There's a scope specifier that does match some template
11704 // parameter lists, which we don't handle right now.
11705 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011706 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011707 // C++ [class.friend]p6:
11708 // A function can be defined in a friend declaration of a class if and
11709 // only if the class is a non-local class (9.8), the function name is
11710 // unqualified, and the function has namespace scope.
11711 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11712 << SS.getScopeRep();
11713 }
11714
John McCallde3fd222010-10-12 23:13:28 +000011715 DC = CurContext;
11716 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011717 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011718
John McCallf7cfb222010-10-13 05:45:15 +000011719 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011720 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011721 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11722 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11723 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011724 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011725 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11726 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011727 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011728 }
John McCall07e91c02009-08-06 02:15:43 +000011729 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011730
Douglas Gregordd847ba2011-11-03 16:37:14 +000011731 // FIXME: This is an egregious hack to cope with cases where the scope stack
11732 // does not contain the declaration context, i.e., in an out-of-line
11733 // definition of a class.
11734 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11735 if (!DCScope) {
11736 FakeDCScope.setEntity(DC);
11737 DCScope = &FakeDCScope;
11738 }
Richard Smith114394f2013-08-09 04:35:01 +000011739
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011740 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011741 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011742 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011743 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011744
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011745 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011746
Richard Smith114394f2013-08-09 04:35:01 +000011747 // If we performed typo correction, we might have added a scope specifier
11748 // and changed the decl context.
11749 DC = ND->getDeclContext();
11750
John McCall759e32b2009-08-31 22:39:49 +000011751 // Add the function declaration to the appropriate lookup tables,
11752 // adjusting the redeclarations list as necessary. We don't
11753 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011754 //
John McCall759e32b2009-08-31 22:39:49 +000011755 // Also update the scope-based lookup if the target context's
11756 // lookup context is in lexical scope.
11757 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011758 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011759 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011760 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011761 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011762 }
John McCallaa74a0c2009-08-28 07:59:38 +000011763
11764 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011765 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011766 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011767 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011768 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011769
John McCalla0a96892012-08-10 03:15:35 +000011770 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011771 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011772 } else {
11773 if (DC->isRecord()) CheckFriendAccess(ND);
11774
John McCall2c2eb122010-10-16 06:59:13 +000011775 FunctionDecl *FD;
11776 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11777 FD = FTD->getTemplatedDecl();
11778 else
11779 FD = cast<FunctionDecl>(ND);
11780
David Majnemer502b0ed2013-06-25 23:09:30 +000011781 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11782 // default argument expression, that declaration shall be a definition
11783 // and shall be the only declaration of the function or function
11784 // template in the translation unit.
11785 if (functionDeclHasDefaultArgument(FD)) {
11786 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11787 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11788 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11789 } else if (!D.isFunctionDefinition())
11790 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11791 }
11792
John McCall2c2eb122010-10-16 06:59:13 +000011793 // Mark templated-scope function declarations as unsupported.
11794 if (FD->getNumTemplateParameterLists())
11795 FrD->setUnsupportedFriend(true);
11796 }
John McCallde3fd222010-10-12 23:13:28 +000011797
John McCall48871652010-08-21 09:40:31 +000011798 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011799}
11800
John McCall48871652010-08-21 09:40:31 +000011801void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11802 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011803
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011804 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011805 if (!Fn) {
11806 Diag(DelLoc, diag::err_deleted_non_function);
11807 return;
11808 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011809
Douglas Gregorec9fd132012-01-14 16:38:05 +000011810 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011811 // Don't consider the implicit declaration we generate for explicit
11812 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000011813 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11814 Prev->getPreviousDecl()) &&
11815 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011816 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000011817 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11818 Prev->isImplicit() ? diag::note_previous_implicit_declaration
11819 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000011820 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011821 // If the declaration wasn't the first, we delete the function anyway for
11822 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011823 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011824 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011825
11826 if (Fn->isDeleted())
11827 return;
11828
11829 // See if we're deleting a function which is already known to override a
11830 // non-deleted virtual function.
11831 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11832 bool IssuedDiagnostic = false;
11833 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11834 E = MD->end_overridden_methods();
11835 I != E; ++I) {
11836 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11837 if (!IssuedDiagnostic) {
11838 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11839 IssuedDiagnostic = true;
11840 }
11841 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11842 }
11843 }
11844 }
11845
Richard Smithb63b6ee2014-01-22 01:43:19 +000011846 // C++11 [basic.start.main]p3:
11847 // A program that defines main as deleted [...] is ill-formed.
11848 if (Fn->isMain())
11849 Diag(DelLoc, diag::err_deleted_main);
11850
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011851 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011852}
Sebastian Redl4c018662009-04-27 21:33:24 +000011853
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011854void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011855 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011856
11857 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000011858 if (MD->getParent()->isDependentType()) {
11859 MD->setDefaulted();
11860 MD->setExplicitlyDefaulted();
11861 return;
11862 }
11863
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011864 CXXSpecialMember Member = getSpecialMember(MD);
11865 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000011866 if (!MD->isInvalidDecl())
11867 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011868 return;
11869 }
11870
11871 MD->setDefaulted();
11872 MD->setExplicitlyDefaulted();
11873
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011874 // If this definition appears within the record, do the checking when
11875 // the record is complete.
11876 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000011877 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011878 // Find the uninstantiated declaration that actually had the '= default'
11879 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000011880 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011881
Richard Smith3901dfe2013-03-27 00:22:47 +000011882 // If the method was defaulted on its first declaration, we will have
11883 // already performed the checking in CheckCompletedCXXClass. Such a
11884 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011885 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011886 return;
11887
Richard Smithd3b5c9082012-07-27 04:22:15 +000011888 CheckExplicitlyDefaultedSpecialMember(MD);
11889
Richard Smithbd305122012-12-11 01:14:52 +000011890 // The exception specification is needed because we are defining the
11891 // function.
11892 ResolveExceptionSpec(DefaultLoc,
11893 MD->getType()->castAs<FunctionProtoType>());
11894
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011895 if (MD->isInvalidDecl())
11896 return;
11897
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011898 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011899 case CXXDefaultConstructor:
11900 DefineImplicitDefaultConstructor(DefaultLoc,
11901 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000011902 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011903 case CXXCopyConstructor:
11904 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011905 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011906 case CXXCopyAssignment:
11907 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000011908 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011909 case CXXDestructor:
11910 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000011911 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011912 case CXXMoveConstructor:
11913 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000011914 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011915 case CXXMoveAssignment:
11916 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011917 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011918 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000011919 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011920 }
11921 } else {
11922 Diag(DefaultLoc, diag::err_default_special_members);
11923 }
11924}
11925
Sebastian Redl4c018662009-04-27 21:33:24 +000011926static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000011927 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000011928 Stmt *SubStmt = *CI;
11929 if (!SubStmt)
11930 continue;
11931 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011932 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000011933 diag::err_return_in_constructor_handler);
11934 if (!isa<Expr>(SubStmt))
11935 SearchForReturnInStmt(Self, SubStmt);
11936 }
11937}
11938
11939void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11940 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11941 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11942 SearchForReturnInStmt(*this, Handler);
11943 }
11944}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011945
David Blaikie68f71a32013-01-18 23:03:15 +000011946bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000011947 const CXXMethodDecl *Old) {
11948 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11949 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11950
11951 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11952
11953 // If the calling conventions match, everything is fine
11954 if (NewCC == OldCC)
11955 return false;
11956
Hans Wennborg2545efe2013-12-11 17:42:11 +000011957 // If the calling conventions mismatch because the new function is static,
11958 // suppress the calling convention mismatch error; the error about static
11959 // function override (err_static_overrides_virtual from
11960 // Sema::CheckFunctionDeclaration) is more clear.
11961 if (New->getStorageClass() == SC_Static)
11962 return false;
11963
Reid Kleckner78af0702013-08-27 23:08:25 +000011964 Diag(New->getLocation(),
11965 diag::err_conflicting_overriding_cc_attributes)
11966 << New->getDeclName() << New->getType() << Old->getType();
11967 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11968 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000011969}
11970
Mike Stump11289f42009-09-09 15:08:12 +000011971bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011972 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000011973 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
11974 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011975
Chandler Carruth284bb2e2010-02-15 11:53:20 +000011976 if (Context.hasSameType(NewTy, OldTy) ||
11977 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011978 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011979
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011980 // Check if the return types are covariant
11981 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000011982
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011983 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000011984 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11985 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011986 NewClassTy = NewPT->getPointeeType();
11987 OldClassTy = OldPT->getPointeeType();
11988 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000011989 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11990 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11991 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11992 NewClassTy = NewRT->getPointeeType();
11993 OldClassTy = OldRT->getPointeeType();
11994 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011995 }
11996 }
Mike Stump11289f42009-09-09 15:08:12 +000011997
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011998 // The return types aren't either both pointers or references to a class type.
11999 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012000 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012001 diag::err_different_return_type_for_overriding_virtual_function)
12002 << New->getDeclName() << NewTy << OldTy;
12003 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012004
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012005 return true;
12006 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012007
Anders Carlssone60365b2009-12-31 18:34:24 +000012008 // C++ [class.virtual]p6:
12009 // If the return type of D::f differs from the return type of B::f, the
12010 // class type in the return type of D::f shall be complete at the point of
12011 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012012 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12013 if (!RT->isBeingDefined() &&
12014 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012015 diag::err_covariant_return_incomplete,
12016 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012017 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012018 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012019
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012020 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012021 // Check if the new class derives from the old class.
12022 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12023 Diag(New->getLocation(),
12024 diag::err_covariant_return_not_derived)
12025 << New->getDeclName() << NewTy << OldTy;
12026 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12027 return true;
12028 }
Mike Stump11289f42009-09-09 15:08:12 +000012029
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012030 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012031 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012032 diag::err_covariant_return_inaccessible_base,
12033 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12034 // FIXME: Should this point to the return type?
12035 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000012036 // FIXME: this note won't trigger for delayed access control
12037 // diagnostics, and it's impossible to get an undelayed error
12038 // here from access control during the original parse because
12039 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012040 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12041 return true;
12042 }
12043 }
Mike Stump11289f42009-09-09 15:08:12 +000012044
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012045 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012046 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012047 Diag(New->getLocation(),
12048 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012049 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012050 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12051 return true;
12052 };
Mike Stump11289f42009-09-09 15:08:12 +000012053
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012054
12055 // The new class type must have the same or less qualifiers as the old type.
12056 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12057 Diag(New->getLocation(),
12058 diag::err_covariant_return_type_class_type_more_qualified)
12059 << New->getDeclName() << NewTy << OldTy;
12060 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12061 return true;
12062 };
Mike Stump11289f42009-09-09 15:08:12 +000012063
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012064 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012065}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012066
Douglas Gregor21920e372009-12-01 17:24:26 +000012067/// \brief Mark the given method pure.
12068///
12069/// \param Method the method to be marked pure.
12070///
12071/// \param InitRange the source range that covers the "0" initializer.
12072bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012073 SourceLocation EndLoc = InitRange.getEnd();
12074 if (EndLoc.isValid())
12075 Method->setRangeEnd(EndLoc);
12076
Douglas Gregor21920e372009-12-01 17:24:26 +000012077 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12078 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012079 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012080 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012081
12082 if (!Method->isInvalidDecl())
12083 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12084 << Method->getDeclName() << InitRange;
12085 return true;
12086}
12087
Douglas Gregor926410d2012-02-21 02:22:07 +000012088/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012089static bool isStaticDataMember(const Decl *D) {
12090 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12091 return Var->isStaticDataMember();
12092
12093 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012094}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012095
John McCall1f4ee7b2009-12-19 09:28:58 +000012096/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12097/// an initializer for the out-of-line declaration 'Dcl'. The scope
12098/// is a fresh scope pushed for just this purpose.
12099///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012100/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12101/// static data member of class X, names should be looked up in the scope of
12102/// class X.
John McCall48871652010-08-21 09:40:31 +000012103void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012104 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012105 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012106
Richard Smitha2302242013-12-05 07:51:02 +000012107 // We will always have a nested name specifier here, but this declaration
12108 // might not be out of line if the specifier names the current namespace:
12109 // extern int n;
12110 // int ::n = 0;
12111 if (D->isOutOfLine())
12112 EnterDeclaratorContext(S, D->getDeclContext());
12113
Douglas Gregor926410d2012-02-21 02:22:07 +000012114 // If we are parsing the initializer for a static data member, push a
12115 // new expression evaluation context that is associated with this static
12116 // data member.
12117 if (isStaticDataMember(D))
12118 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012119}
12120
12121/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012122/// initializer for the out-of-line declaration 'D'.
12123void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012124 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012125 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012126
Douglas Gregor926410d2012-02-21 02:22:07 +000012127 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012128 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012129
Richard Smitha2302242013-12-05 07:51:02 +000012130 if (D->isOutOfLine())
12131 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012132}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012133
12134/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12135/// C++ if/switch/while/for statement.
12136/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012137DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012138 // C++ 6.4p2:
12139 // The declarator shall not specify a function or an array.
12140 // The type-specifier-seq shall not contain typedef and shall not declare a
12141 // new class or enumeration.
12142 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12143 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012144
12145 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012146 if (!Dcl)
12147 return true;
12148
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012149 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12150 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012151 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012152 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012153 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012154
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012155 return Dcl;
12156}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012157
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012158void Sema::LoadExternalVTableUses() {
12159 if (!ExternalSource)
12160 return;
12161
12162 SmallVector<ExternalVTableUse, 4> VTables;
12163 ExternalSource->ReadUsedVTables(VTables);
12164 SmallVector<VTableUse, 4> NewUses;
12165 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12166 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12167 = VTablesUsed.find(VTables[I].Record);
12168 // Even if a definition wasn't required before, it may be required now.
12169 if (Pos != VTablesUsed.end()) {
12170 if (!Pos->second && VTables[I].DefinitionRequired)
12171 Pos->second = true;
12172 continue;
12173 }
12174
12175 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12176 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12177 }
12178
12179 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12180}
12181
Douglas Gregor88d292c2010-05-13 16:44:06 +000012182void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12183 bool DefinitionRequired) {
12184 // Ignore any vtable uses in unevaluated operands or for classes that do
12185 // not have a vtable.
12186 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012187 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012188 return;
12189
Douglas Gregor88d292c2010-05-13 16:44:06 +000012190 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012191 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012192 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12193 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12194 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12195 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012196 // If we already had an entry, check to see if we are promoting this vtable
12197 // to required a definition. If so, we need to reappend to the VTableUses
12198 // list, since we may have already processed the first entry.
12199 if (DefinitionRequired && !Pos.first->second) {
12200 Pos.first->second = true;
12201 } else {
12202 // Otherwise, we can early exit.
12203 return;
12204 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012205 } else {
12206 // The Microsoft ABI requires that we perform the destructor body
12207 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12208 // the deleting destructor is emitted with the vtable, not with the
12209 // destructor definition as in the Itanium ABI.
12210 // If it has a definition, we do the check at that point instead.
12211 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12212 Class->hasUserDeclaredDestructor() &&
12213 !Class->getDestructor()->isDefined() &&
12214 !Class->getDestructor()->isDeleted()) {
12215 CheckDestructor(Class->getDestructor());
12216 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012217 }
12218
12219 // Local classes need to have their virtual members marked
12220 // immediately. For all other classes, we mark their virtual members
12221 // at the end of the translation unit.
12222 if (Class->isLocalClass())
12223 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012224 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012225 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012226}
12227
Douglas Gregor88d292c2010-05-13 16:44:06 +000012228bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012229 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012230 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012231 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012232
Douglas Gregor88d292c2010-05-13 16:44:06 +000012233 // Note: The VTableUses vector could grow as a result of marking
12234 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012235 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012236 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012237 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012238 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012239 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012240 if (!Class)
12241 continue;
12242
12243 SourceLocation Loc = VTableUses[I].second;
12244
Richard Smithd3b5c9082012-07-27 04:22:15 +000012245 bool DefineVTable = true;
12246
Douglas Gregor88d292c2010-05-13 16:44:06 +000012247 // If this class has a key function, but that key function is
12248 // defined in another translation unit, we don't need to emit the
12249 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012250 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012251 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012252 // The key function is in another translation unit.
12253 DefineVTable = false;
12254 TemplateSpecializationKind TSK =
12255 KeyFunction->getTemplateSpecializationKind();
12256 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12257 TSK != TSK_ImplicitInstantiation &&
12258 "Instantiations don't have key functions");
12259 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012260 } else if (!KeyFunction) {
12261 // If we have a class with no key function that is the subject
12262 // of an explicit instantiation declaration, suppress the
12263 // vtable; it will live with the explicit instantiation
12264 // definition.
12265 bool IsExplicitInstantiationDeclaration
12266 = Class->getTemplateSpecializationKind()
12267 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012268 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012269 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012270 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012271 if (TSK == TSK_ExplicitInstantiationDeclaration)
12272 IsExplicitInstantiationDeclaration = true;
12273 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12274 IsExplicitInstantiationDeclaration = false;
12275 break;
12276 }
12277 }
12278
12279 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012280 DefineVTable = false;
12281 }
12282
12283 // The exception specifications for all virtual members may be needed even
12284 // if we are not providing an authoritative form of the vtable in this TU.
12285 // We may choose to emit it available_externally anyway.
12286 if (!DefineVTable) {
12287 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12288 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012289 }
12290
12291 // Mark all of the virtual members of this class as referenced, so
12292 // that we can build a vtable. Then, tell the AST consumer that a
12293 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012294 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012295 MarkVirtualMembersReferenced(Loc, Class);
12296 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12297 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12298
12299 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012300 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012301 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012302 const FunctionDecl *KeyFunctionDef = 0;
12303 if (!KeyFunction ||
12304 (KeyFunction->hasBody(KeyFunctionDef) &&
12305 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012306 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12307 TSK_ExplicitInstantiationDefinition
12308 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12309 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012310 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012311 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012312 VTableUses.clear();
12313
Douglas Gregor97509692011-04-22 22:25:37 +000012314 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012315}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012316
Richard Smithd3b5c9082012-07-27 04:22:15 +000012317void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12318 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012319 for (const auto *I : RD->methods())
12320 if (I->isVirtual() && !I->isPure())
12321 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012322}
12323
Rafael Espindola5b334082010-03-26 00:36:59 +000012324void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12325 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012326 // Mark all functions which will appear in RD's vtable as used.
12327 CXXFinalOverriderMap FinalOverriders;
12328 RD->getFinalOverriders(FinalOverriders);
12329 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12330 E = FinalOverriders.end();
12331 I != E; ++I) {
12332 for (OverridingMethods::const_iterator OI = I->second.begin(),
12333 OE = I->second.end();
12334 OI != OE; ++OI) {
12335 assert(OI->second.size() > 0 && "no final overrider");
12336 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012337
Richard Smith4ff9ff92012-07-07 06:59:51 +000012338 // C++ [basic.def.odr]p2:
12339 // [...] A virtual member function is used if it is not pure. [...]
12340 if (!Overrider->isPure())
12341 MarkFunctionReferenced(Loc, Overrider);
12342 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012343 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012344
12345 // Only classes that have virtual bases need a VTT.
12346 if (RD->getNumVBases() == 0)
12347 return;
12348
Aaron Ballman574705e2014-03-13 15:41:46 +000012349 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012350 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012351 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012352 if (Base->getNumVBases() == 0)
12353 continue;
12354 MarkVirtualMembersReferenced(Loc, Base);
12355 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012356}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012357
12358/// SetIvarInitializers - This routine builds initialization ASTs for the
12359/// Objective-C implementation whose ivars need be initialized.
12360void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012361 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012362 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012363 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012364 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012365 CollectIvarsToConstructOrDestruct(OID, ivars);
12366 if (ivars.empty())
12367 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012368 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012369 for (unsigned i = 0; i < ivars.size(); i++) {
12370 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012371 if (Field->isInvalidDecl())
12372 continue;
12373
Alexis Hunt1d792652011-01-08 20:30:50 +000012374 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012375 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12376 InitializationKind InitKind =
12377 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012378
12379 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12380 ExprResult MemberInit =
12381 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012382 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012383 // Note, MemberInit could actually come back empty if no initialization
12384 // is required (e.g., because it would call a trivial default constructor)
12385 if (!MemberInit.get() || MemberInit.isInvalid())
12386 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012387
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012388 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012389 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12390 SourceLocation(),
12391 MemberInit.takeAs<Expr>(),
12392 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012393 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012394
12395 // Be sure that the destructor is accessible and is marked as referenced.
12396 if (const RecordType *RecordTy
12397 = Context.getBaseElementType(Field->getType())
12398 ->getAs<RecordType>()) {
12399 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012400 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012401 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012402 CheckDestructorAccess(Field->getLocation(), Destructor,
12403 PDiag(diag::err_access_dtor_ivar)
12404 << Context.getBaseElementType(Field->getType()));
12405 }
12406 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012407 }
12408 ObjCImplementation->setIvarInitializers(Context,
12409 AllToInit.data(), AllToInit.size());
12410 }
12411}
Alexis Hunt6118d662011-05-04 05:57:24 +000012412
Alexis Hunt27a761d2011-05-04 23:29:54 +000012413static
12414void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12415 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12416 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12417 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12418 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012419 if (Ctor->isInvalidDecl())
12420 return;
12421
Richard Smith802c4b72012-08-23 06:16:52 +000012422 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12423
12424 // Target may not be determinable yet, for instance if this is a dependent
12425 // call in an uninstantiated template.
12426 if (Target) {
12427 const FunctionDecl *FNTarget = 0;
12428 (void)Target->hasBody(FNTarget);
12429 Target = const_cast<CXXConstructorDecl*>(
12430 cast_or_null<CXXConstructorDecl>(FNTarget));
12431 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012432
12433 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12434 // Avoid dereferencing a null pointer here.
12435 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12436
12437 if (!Current.insert(Canonical))
12438 return;
12439
12440 // We know that beyond here, we aren't chaining into a cycle.
12441 if (!Target || !Target->isDelegatingConstructor() ||
12442 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012443 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012444 Current.clear();
12445 // We've hit a cycle.
12446 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12447 Current.count(TCanonical)) {
12448 // If we haven't diagnosed this cycle yet, do so now.
12449 if (!Invalid.count(TCanonical)) {
12450 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012451 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012452 << Ctor;
12453
Richard Smith802c4b72012-08-23 06:16:52 +000012454 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012455 if (TCanonical != Canonical)
12456 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12457
12458 CXXConstructorDecl *C = Target;
12459 while (C->getCanonicalDecl() != Canonical) {
Richard Smith802c4b72012-08-23 06:16:52 +000012460 const FunctionDecl *FNTarget = 0;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012461 (void)C->getTargetConstructor()->hasBody(FNTarget);
12462 assert(FNTarget && "Ctor cycle through bodiless function");
12463
Richard Smith802c4b72012-08-23 06:16:52 +000012464 C = const_cast<CXXConstructorDecl*>(
12465 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012466 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12467 }
12468 }
12469
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012470 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012471 Current.clear();
12472 } else {
12473 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12474 }
12475}
12476
12477
Alexis Hunt6118d662011-05-04 05:57:24 +000012478void Sema::CheckDelegatingCtorCycles() {
12479 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12480
Douglas Gregorbae31202011-07-27 21:57:17 +000012481 for (DelegatingCtorDeclsType::iterator
12482 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012483 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012484 I != E; ++I)
12485 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012486
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012487 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12488 CE = Invalid.end();
12489 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012490 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012491}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012492
Douglas Gregor3024f072012-04-16 07:05:22 +000012493namespace {
12494 /// \brief AST visitor that finds references to the 'this' expression.
12495 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12496 Sema &S;
12497
12498 public:
12499 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12500
12501 bool VisitCXXThisExpr(CXXThisExpr *E) {
12502 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12503 << E->isImplicit();
12504 return false;
12505 }
12506 };
12507}
12508
12509bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12510 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12511 if (!TSInfo)
12512 return false;
12513
12514 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012515 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012516 if (!ProtoTL)
12517 return false;
12518
12519 // C++11 [expr.prim.general]p3:
12520 // [The expression this] shall not appear before the optional
12521 // cv-qualifier-seq and it shall not appear within the declaration of a
12522 // static member function (although its type and value category are defined
12523 // within a static member function as they are within a non-static member
12524 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012525 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012526 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012527 FindCXXThisExpr Finder(*this);
12528
12529 // If the return type came after the cv-qualifier-seq, check it now.
12530 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012531 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012532 return true;
12533
12534 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012535 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12536 return true;
12537
12538 return checkThisInStaticMemberFunctionAttributes(Method);
12539}
12540
12541bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12542 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12543 if (!TSInfo)
12544 return false;
12545
12546 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012547 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012548 if (!ProtoTL)
12549 return false;
12550
David Blaikie6adc78e2013-02-18 22:06:02 +000012551 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012552 FindCXXThisExpr Finder(*this);
12553
Douglas Gregor3024f072012-04-16 07:05:22 +000012554 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012555 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012556 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012557 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012558 case EST_DynamicNone:
12559 case EST_MSAny:
12560 case EST_None:
12561 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012562
Douglas Gregor3024f072012-04-16 07:05:22 +000012563 case EST_ComputedNoexcept:
12564 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12565 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012566
Douglas Gregor3024f072012-04-16 07:05:22 +000012567 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012568 for (const auto &E : Proto->exceptions()) {
12569 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012570 return true;
12571 }
12572 break;
12573 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012574
12575 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012576}
12577
12578bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12579 FindCXXThisExpr Finder(*this);
12580
12581 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012582 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012583 // FIXME: This should be emitted by tblgen.
12584 Expr *Arg = 0;
12585 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012586 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012587 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012588 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012589 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012590 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012591 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012592 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012593 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012594 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012595 Arg = ETLF->getSuccessValue();
12596 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012597 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012598 Arg = STLF->getSuccessValue();
12599 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000012600 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012601 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012602 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012603 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012604 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012605 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012606 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012607 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012608 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12609 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12610 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012611 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012612
12613 if (Arg && !Finder.TraverseStmt(Arg))
12614 return true;
12615
12616 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12617 if (!Finder.TraverseStmt(Args[I]))
12618 return true;
12619 }
12620 }
12621
12622 return false;
12623}
12624
Douglas Gregor433e0532012-04-16 18:27:27 +000012625void
12626Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12627 ArrayRef<ParsedType> DynamicExceptions,
12628 ArrayRef<SourceRange> DynamicExceptionRanges,
12629 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012630 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012631 FunctionProtoType::ExtProtoInfo &EPI) {
12632 Exceptions.clear();
12633 EPI.ExceptionSpecType = EST;
12634 if (EST == EST_Dynamic) {
12635 Exceptions.reserve(DynamicExceptions.size());
12636 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12637 // FIXME: Preserve type source info.
12638 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12639
12640 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12641 collectUnexpandedParameterPacks(ET, Unexpanded);
12642 if (!Unexpanded.empty()) {
12643 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12644 UPPC_ExceptionType,
12645 Unexpanded);
12646 continue;
12647 }
12648
12649 // Check that the type is valid for an exception spec, and
12650 // drop it if not.
12651 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12652 Exceptions.push_back(ET);
12653 }
12654 EPI.NumExceptions = Exceptions.size();
12655 EPI.Exceptions = Exceptions.data();
12656 return;
12657 }
12658
12659 if (EST == EST_ComputedNoexcept) {
12660 // If an error occurred, there's no expression here.
12661 if (NoexceptExpr) {
12662 assert((NoexceptExpr->isTypeDependent() ||
12663 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12664 Context.BoolTy) &&
12665 "Parser should have made sure that the expression is boolean");
12666 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12667 EPI.ExceptionSpecType = EST_BasicNoexcept;
12668 return;
12669 }
12670
12671 if (!NoexceptExpr->isValueDependent())
12672 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012673 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012674 /*AllowFold*/ false).take();
12675 EPI.NoexceptExpr = NoexceptExpr;
12676 }
12677 return;
12678 }
12679}
12680
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012681/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12682Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12683 // Implicitly declared functions (e.g. copy constructors) are
12684 // __host__ __device__
12685 if (D->isImplicit())
12686 return CFT_HostDevice;
12687
12688 if (D->hasAttr<CUDAGlobalAttr>())
12689 return CFT_Global;
12690
12691 if (D->hasAttr<CUDADeviceAttr>()) {
12692 if (D->hasAttr<CUDAHostAttr>())
12693 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012694 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012695 }
12696
12697 return CFT_Host;
12698}
12699
12700bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12701 CUDAFunctionTarget CalleeTarget) {
12702 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12703 // Callable from the device only."
12704 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12705 return true;
12706
12707 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12708 // Callable from the host only."
12709 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12710 // Callable from the host only."
12711 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12712 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12713 return true;
12714
12715 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12716 return true;
12717
12718 return false;
12719}
John McCall5e77d762013-04-16 07:28:30 +000012720
12721/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12722///
12723MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12724 SourceLocation DeclStart,
12725 Declarator &D, Expr *BitWidth,
12726 InClassInitStyle InitStyle,
12727 AccessSpecifier AS,
12728 AttributeList *MSPropertyAttr) {
12729 IdentifierInfo *II = D.getIdentifier();
12730 if (!II) {
12731 Diag(DeclStart, diag::err_anonymous_property);
12732 return NULL;
12733 }
12734 SourceLocation Loc = D.getIdentifierLoc();
12735
12736 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12737 QualType T = TInfo->getType();
12738 if (getLangOpts().CPlusPlus) {
12739 CheckExtraCXXDefaultArguments(D);
12740
12741 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12742 UPPC_DataMemberType)) {
12743 D.setInvalidType();
12744 T = Context.IntTy;
12745 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12746 }
12747 }
12748
12749 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12750
12751 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12752 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12753 diag::err_invalid_thread)
12754 << DeclSpec::getSpecifierName(TSCS);
12755
12756 // Check to see if this name was declared as a member previously
12757 NamedDecl *PrevDecl = 0;
12758 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12759 LookupName(Previous, S);
12760 switch (Previous.getResultKind()) {
12761 case LookupResult::Found:
12762 case LookupResult::FoundUnresolvedValue:
12763 PrevDecl = Previous.getAsSingle<NamedDecl>();
12764 break;
12765
12766 case LookupResult::FoundOverloaded:
12767 PrevDecl = Previous.getRepresentativeDecl();
12768 break;
12769
12770 case LookupResult::NotFound:
12771 case LookupResult::NotFoundInCurrentInstantiation:
12772 case LookupResult::Ambiguous:
12773 break;
12774 }
12775
12776 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12777 // Maybe we will complain about the shadowed template parameter.
12778 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12779 // Just pretend that we didn't see the previous declaration.
12780 PrevDecl = 0;
12781 }
12782
12783 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12784 PrevDecl = 0;
12785
12786 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000012787 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000012788 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12789 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000012790 ProcessDeclAttributes(TUScope, NewPD, D);
12791 NewPD->setAccess(AS);
12792
12793 if (NewPD->isInvalidDecl())
12794 Record->setInvalidDecl();
12795
12796 if (D.getDeclSpec().isModulePrivateSpecified())
12797 NewPD->setModulePrivate();
12798
12799 if (NewPD->isInvalidDecl() && PrevDecl) {
12800 // Don't introduce NewFD into scope; there's already something
12801 // with the same name in the same scope.
12802 } else if (II) {
12803 PushOnScopeChains(NewPD, S);
12804 } else
12805 Record->addDecl(NewPD);
12806
12807 return NewPD;
12808}