blob: d49e68e027e5fe5ad45fff8e5463b3d1c66632ea [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000030#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000031#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/CXXFieldCollector.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/ScopeInfo.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000042#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000043#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner58258242008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattnerb0d38442008-04-12 23:52:44 +000051namespace {
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000061
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 public:
Mike Stump11289f42009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000065
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 };
Chris Lattner58258242008-04-10 02:22:51 +000072
Chris Lattnerb0d38442008-04-12 23:52:44 +000073 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000079 }
80
Chris Lattnerb0d38442008-04-12 23:52:44 +000081 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000086 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107
Douglas Gregor8e12c382008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110
Douglas Gregor97a9c812008-11-04 14:32:21 +0000111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000119 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000120
John McCall7353c862013-04-09 01:56:28 +0000121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
Douglas Gregorf0d49512012-02-10 23:30:22 +0000138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
Chris Lattner58258242008-04-10 02:22:51 +0000148}
149
Richard Smithb7151b92013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If this function can throw any exceptions, make a note of that.
Richard Smithd3b5c9082012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith938f40b2011-06-11 17:19:42 +0000172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
174
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
177 return;
178
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
181 return;
182
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
188 return;
189 }
190
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
Richard Smithf623c962012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
200
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
209
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000215 for (const auto &E : Proto->exceptions())
216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
217 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000218}
219
Richard Smith938f40b2011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithf623c962012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssonc80a1272009-08-25 02:29:20 +0000249bool
John McCallb268a282010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssonc80a1272009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000271 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000273
Richard Smithc406cb72013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Anders Carlssonc80a1272009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000279
Douglas Gregor758cb672010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000292 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000293}
294
Chris Lattner58258242008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000298void
John McCall48871652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000302 return;
Mike Stump11289f42009-09-09 15:08:12 +0000303
John McCall48871652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner199abbc2008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlssonf1c26952009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump11289f42009-09-09 15:08:12 +0000327
John McCallb268a282010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000329}
330
Douglas Gregor58354032008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump11289f42009-09-09 15:08:12 +0000340
John McCall48871652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000342 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000343 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000344}
345
Douglas Gregor4d87df52008-12-16 21:30:33 +0000346/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000348void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000349 if (!param)
350 return;
Mike Stump11289f42009-09-09 15:08:12 +0000351
John McCall48871652010-08-21 09:40:31 +0000352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000353 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000354 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000355}
356
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000357/// CheckExtraCXXDefaultArguments - Check for any extra default
358/// arguments in the declarator, which is not a function declaration
359/// or definition and therefore is not permitted to have default
360/// arguments. This routine should be invoked for every declarator
361/// that is not a function declaration or definition.
362void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
363 // C++ [dcl.fct.default]p3
364 // A default argument expression shall be specified only in the
365 // parameter-declaration-clause of a function declaration or in a
366 // template-parameter (14.1). It shall not be specified for a
367 // parameter pack. If it is specified in a
368 // parameter-declaration-clause, it shall not occur within a
369 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000370 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000371 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000372 DeclaratorChunk &chunk = D.getTypeObject(i);
373 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000374 if (MightBeFunction) {
375 // This is a function declaration. It can have default arguments, but
376 // keep looking in case its return type is a function type with default
377 // arguments.
378 MightBeFunction = false;
379 continue;
380 }
Alp Tokerc5350722014-02-26 22:27:52 +0000381 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
382 ++argIdx) {
383 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000384 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000385 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000386 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000387 << SourceRange((*Toks)[1].getLocation(),
388 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000389 delete Toks;
Alp Tokerc5350722014-02-26 22:27:52 +0000390 chunk.Fun.Params[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000391 } else if (Param->getDefaultArg()) {
392 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
393 << Param->getDefaultArg()->getSourceRange();
394 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000395 }
396 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000397 } else if (chunk.Kind != DeclaratorChunk::Paren) {
398 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000399 }
400 }
401}
402
David Majnemer502b0ed2013-06-25 23:09:30 +0000403static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
404 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
405 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
406 if (!PVD->hasDefaultArg())
407 return false;
408 if (!PVD->hasInheritedDefaultArg())
409 return true;
410 }
411 return false;
412}
413
Craig Toppere4794282012-09-21 04:33:26 +0000414/// MergeCXXFunctionDecl - Merge two declarations of the same C++
415/// function, once we already know that they have the same
416/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
417/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000418bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
419 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000420 bool Invalid = false;
421
Chris Lattner199abbc2008-04-08 05:04:30 +0000422 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000423 // For non-template functions, default arguments can be added in
424 // later declarations of a function in the same
425 // scope. Declarations in different scopes have completely
426 // distinct sets of default arguments. That is, declarations in
427 // inner scopes do not acquire default arguments from
428 // declarations in outer scopes, and vice versa. In a given
429 // function declaration, all parameters subsequent to a
430 // parameter with a default argument shall have default
431 // arguments supplied in this or previous declarations. A
432 // default argument shall not be redefined by a later
433 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000434 //
435 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000436 // Except for member functions of class templates, the default arguments
437 // in a member function definition that appears outside of the class
438 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000439 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000440 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
441 ParmVarDecl *OldParam = Old->getParamDecl(p);
442 ParmVarDecl *NewParam = New->getParamDecl(p);
443
James Molloye9430032012-03-13 08:55:35 +0000444 bool OldParamHasDfl = OldParam->hasDefaultArg();
445 bool NewParamHasDfl = NewParam->hasDefaultArg();
446
447 NamedDecl *ND = Old;
Richard Smith541b38b2013-09-20 01:15:31 +0000448
449 // The declaration context corresponding to the scope is the semantic
450 // parent, unless this is a local function declaration, in which case
451 // it is that surrounding function.
452 DeclContext *ScopeDC = New->getLexicalDeclContext();
453 if (!ScopeDC->isFunctionOrMethod())
454 ScopeDC = New->getDeclContext();
455 if (S && !isDeclInScope(ND, ScopeDC, S) &&
456 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000457 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000458 // the same scope and this is not an out-of-line definition of
459 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000460 OldParamHasDfl = false;
461
462 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000463
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000464 unsigned DiagDefaultParamID =
465 diag::err_param_default_argument_redefinition;
466
467 // MSVC accepts that default parameters be redefined for member functions
468 // of template class. The new default parameter's value is ignored.
469 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000470 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000471 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
472 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000473 // Merge the old default argument into the new parameter.
474 NewParam->setHasInheritedDefaultArg();
475 if (OldParam->hasUninstantiatedDefaultArg())
476 NewParam->setUninstantiatedDefaultArg(
477 OldParam->getUninstantiatedDefaultArg());
478 else
479 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000480 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000481 Invalid = false;
482 }
483 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000484
Francois Pichet8cb243a2011-04-10 04:58:30 +0000485 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
486 // hint here. Alternatively, we could walk the type-source information
487 // for NewParam to find the last source location in the type... but it
488 // isn't worth the effort right now. This is the kind of test case that
489 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000490 // int f(int);
491 // void g(int (*fp)(int) = f);
492 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000493 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000494 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000495
496 // Look for the function declaration where the default argument was
497 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000498 for (FunctionDecl *Older = Old->getPreviousDecl();
499 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000500 if (!Older->getParamDecl(p)->hasDefaultArg())
501 break;
502
503 OldParam = Older->getParamDecl(p);
504 }
505
506 Diag(OldParam->getLocation(), diag::note_previous_definition)
507 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000508 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000509 // Merge the old default argument into the new parameter.
510 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000511 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000512 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000513 if (OldParam->hasUninstantiatedDefaultArg())
514 NewParam->setUninstantiatedDefaultArg(
515 OldParam->getUninstantiatedDefaultArg());
516 else
John McCalle61b02b2010-05-04 01:53:42 +0000517 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000518 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000519 if (New->getDescribedFunctionTemplate()) {
520 // Paragraph 4, quoted above, only applies to non-template functions.
521 Diag(NewParam->getLocation(),
522 diag::err_param_default_argument_template_redecl)
523 << NewParam->getDefaultArgRange();
524 Diag(Old->getLocation(), diag::note_template_prev_declaration)
525 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000526 } else if (New->getTemplateSpecializationKind()
527 != TSK_ImplicitInstantiation &&
528 New->getTemplateSpecializationKind() != TSK_Undeclared) {
529 // C++ [temp.expr.spec]p21:
530 // Default function arguments shall not be specified in a declaration
531 // or a definition for one of the following explicit specializations:
532 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000533 // - the explicit specialization of a member function template;
534 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000535 // template where the class template specialization to which the
536 // member function specialization belongs is implicitly
537 // instantiated.
538 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
539 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
540 << New->getDeclName()
541 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000542 } else if (New->getDeclContext()->isDependentContext()) {
543 // C++ [dcl.fct.default]p6 (DR217):
544 // Default arguments for a member function of a class template shall
545 // be specified on the initial declaration of the member function
546 // within the class template.
547 //
548 // Reading the tea leaves a bit in DR217 and its reference to DR205
549 // leads me to the conclusion that one cannot add default function
550 // arguments for an out-of-line definition of a member function of a
551 // dependent type.
552 int WhichKind = 2;
553 if (CXXRecordDecl *Record
554 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
555 if (Record->getDescribedClassTemplate())
556 WhichKind = 0;
557 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
558 WhichKind = 1;
559 else
560 WhichKind = 2;
561 }
562
563 Diag(NewParam->getLocation(),
564 diag::err_param_default_argument_member_template_redecl)
565 << WhichKind
566 << NewParam->getDefaultArgRange();
567 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000568 }
569 }
570
Richard Smith58c3cc12012-11-28 03:45:24 +0000571 // DR1344: If a default argument is added outside a class definition and that
572 // default argument makes the function a special member function, the program
573 // is ill-formed. This can only happen for constructors.
574 if (isa<CXXConstructorDecl>(New) &&
575 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
576 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
577 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
578 if (NewSM != OldSM) {
579 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
580 assert(NewParam->hasDefaultArg());
581 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
582 << NewParam->getDefaultArgRange() << NewSM;
583 Diag(Old->getLocation(), diag::note_previous_declaration);
584 }
585 }
586
David Majnemeree4f4022014-03-30 06:44:54 +0000587 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000588 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000589 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000590 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000591 if (New->isConstexpr() != Old->isConstexpr()) {
592 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
593 << New << New->isConstexpr();
594 Diag(Old->getLocation(), diag::note_previous_declaration);
595 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000596 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
597 // C++11 [dcl.fcn.spec]p4:
598 // If the definition of a function appears in a translation unit before its
599 // first declaration as inline, the program is ill-formed.
600 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
601 Diag(Def->getLocation(), diag::note_previous_definition);
602 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000603 }
604
David Majnemer502b0ed2013-06-25 23:09:30 +0000605 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000606 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000607 // the only declaration of the function or function template in the
608 // translation unit.
609 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
610 functionDeclHasDefaultArgument(Old)) {
611 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
612 Diag(Old->getLocation(), diag::note_previous_declaration);
613 Invalid = true;
614 }
615
Douglas Gregorf40863c2010-02-12 07:32:17 +0000616 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000617 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000618
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000619 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000620}
621
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000622/// \brief Merge the exception specifications of two variable declarations.
623///
624/// This is called when there's a redeclaration of a VarDecl. The function
625/// checks if the redeclaration might have an exception specification and
626/// validates compatibility and merges the specs if necessary.
627void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
628 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000629 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000630 return;
631
632 assert(Context.hasSameType(New->getType(), Old->getType()) &&
633 "Should only be called if types are otherwise the same.");
634
635 QualType NewType = New->getType();
636 QualType OldType = Old->getType();
637
638 // We're only interested in pointers and references to functions, as well
639 // as pointers to member functions.
640 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
641 NewType = R->getPointeeType();
642 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
643 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
644 NewType = P->getPointeeType();
645 OldType = OldType->getAs<PointerType>()->getPointeeType();
646 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
647 NewType = M->getPointeeType();
648 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
649 }
650
651 if (!NewType->isFunctionProtoType())
652 return;
653
654 // There's lots of special cases for functions. For function pointers, system
655 // libraries are hopefully not as broken so that we don't need these
656 // workarounds.
657 if (CheckEquivalentExceptionSpec(
658 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
659 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
660 New->setInvalidDecl();
661 }
662}
663
Chris Lattner199abbc2008-04-08 05:04:30 +0000664/// CheckCXXDefaultArguments - Verify that the default arguments for a
665/// function declaration are well-formed according to C++
666/// [dcl.fct.default].
667void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
668 unsigned NumParams = FD->getNumParams();
669 unsigned p;
670
671 // Find first parameter with a default argument
672 for (p = 0; p < NumParams; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000674 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000675 break;
676 }
677
678 // C++ [dcl.fct.default]p4:
679 // In a given function declaration, all parameters
680 // subsequent to a parameter with a default argument shall
681 // have default arguments supplied in this or previous
682 // declarations. A default argument shall not be redefined
683 // by a later declaration (not even to the same value).
684 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000685 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000686 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000687 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000688 if (Param->isInvalidDecl())
689 /* We already complained about this parameter. */;
690 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000691 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000692 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000693 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000694 else
Mike Stump11289f42009-09-09 15:08:12 +0000695 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000696 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner199abbc2008-04-08 05:04:30 +0000698 LastMissingDefaultArg = p;
699 }
700 }
701
702 if (LastMissingDefaultArg > 0) {
703 // Some default arguments were missing. Clear out all of the
704 // default arguments up to (and including) the last missing
705 // default argument, so that we leave the function parameters
706 // in a semantically valid state.
707 for (p = 0; p <= LastMissingDefaultArg; ++p) {
708 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000709 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000710 Param->setDefaultArg(0);
711 }
712 }
713 }
714}
Douglas Gregor556877c2008-04-13 21:30:24 +0000715
Richard Smitheb3c10c2011-10-01 02:31:28 +0000716// CheckConstexprParameterTypes - Check whether a function's parameter types
717// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000718// diagnostic and return false.
719static bool CheckConstexprParameterTypes(Sema &SemaRef,
720 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000721 unsigned ArgIndex = 0;
722 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000723 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
724 e = FT->param_type_end();
725 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000726 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
727 SourceLocation ParamLoc = PD->getLocation();
728 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000729 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000730 diag::err_constexpr_non_literal_param,
731 ArgIndex+1, PD->getSourceRange(),
732 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000733 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000734 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000735 return true;
736}
737
738/// \brief Get diagnostic %select index for tag kind for
739/// record diagnostic message.
740/// WARNING: Indexes apply to particular diagnostics only!
741///
742/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000743static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000744 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000745 case TTK_Struct: return 0;
746 case TTK_Interface: return 1;
747 case TTK_Class: return 2;
748 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000749 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000750}
751
752// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
753// the requirements of a constexpr function definition or a constexpr
754// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000755// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000756//
Richard Smith3607ffe2012-02-13 03:54:03 +0000757// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
758bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000759 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
760 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000761 // C++11 [dcl.constexpr]p4:
762 // The definition of a constexpr constructor shall satisfy the following
763 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000764 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000765 const CXXRecordDecl *RD = MD->getParent();
766 if (RD->getNumVBases()) {
767 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
768 << isa<CXXConstructorDecl>(NewFD)
769 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000770 for (const auto &I : RD->vbases())
771 Diag(I.getLocStart(),
772 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000773 return false;
774 }
Richard Smith7971b692012-01-13 04:54:00 +0000775 }
776
777 if (!isa<CXXConstructorDecl>(NewFD)) {
778 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000779 // The definition of a constexpr function shall satisfy the following
780 // constraints:
781 // - it shall not be virtual;
782 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
783 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000784 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000785
Richard Smith3607ffe2012-02-13 03:54:03 +0000786 // If it's not obvious why this function is virtual, find an overridden
787 // function which uses the 'virtual' keyword.
788 const CXXMethodDecl *WrittenVirtual = Method;
789 while (!WrittenVirtual->isVirtualAsWritten())
790 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
791 if (WrittenVirtual != Method)
792 Diag(WrittenVirtual->getLocation(),
793 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000794 return false;
795 }
796
797 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000798 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000799 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000800 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000801 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000802 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000803 }
804
Richard Smith7971b692012-01-13 04:54:00 +0000805 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000806 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000807 return false;
808
Richard Smitheb3c10c2011-10-01 02:31:28 +0000809 return true;
810}
811
812/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000813/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000814///
Richard Smithd9f663b2013-04-22 15:31:51 +0000815/// \return true if the body is OK (maybe only as an extension), false if we
816/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000817static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000818 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
819 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000820 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
821 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000822 for (const auto *DclIt : DS->decls()) {
823 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000824 case Decl::StaticAssert:
825 case Decl::Using:
826 case Decl::UsingShadow:
827 case Decl::UsingDirective:
828 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000829 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000830 // - static_assert-declarations
831 // - using-declarations,
832 // - using-directives,
833 continue;
834
835 case Decl::Typedef:
836 case Decl::TypeAlias: {
837 // - typedef declarations and alias-declarations that do not define
838 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000839 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000840 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
841 // Don't allow variably-modified types in constexpr functions.
842 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
843 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
844 << TL.getSourceRange() << TL.getType()
845 << isa<CXXConstructorDecl>(Dcl);
846 return false;
847 }
848 continue;
849 }
850
851 case Decl::Enum:
852 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000853 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000854 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000855 SemaRef.Diag(DS->getLocStart(),
856 SemaRef.getLangOpts().CPlusPlus1y
857 ? diag::warn_cxx11_compat_constexpr_type_definition
858 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000859 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000860 continue;
861
Richard Smithd9f663b2013-04-22 15:31:51 +0000862 case Decl::EnumConstant:
863 case Decl::IndirectField:
864 case Decl::ParmVar:
865 // These can only appear with other declarations which are banned in
866 // C++11 and permitted in C++1y, so ignore them.
867 continue;
868
869 case Decl::Var: {
870 // C++1y [dcl.constexpr]p3 allows anything except:
871 // a definition of a variable of non-literal type or of static or
872 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000873 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000874 if (VD->isThisDeclarationADefinition()) {
875 if (VD->isStaticLocal()) {
876 SemaRef.Diag(VD->getLocation(),
877 diag::err_constexpr_local_var_static)
878 << isa<CXXConstructorDecl>(Dcl)
879 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
880 return false;
881 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000882 if (!VD->getType()->isDependentType() &&
883 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000884 VD->getLocation(), VD->getType(),
885 diag::err_constexpr_local_var_non_literal_type,
886 isa<CXXConstructorDecl>(Dcl)))
887 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000888 if (!VD->getType()->isDependentType() &&
889 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000890 SemaRef.Diag(VD->getLocation(),
891 diag::err_constexpr_local_var_no_init)
892 << isa<CXXConstructorDecl>(Dcl);
893 return false;
894 }
895 }
896 SemaRef.Diag(VD->getLocation(),
897 SemaRef.getLangOpts().CPlusPlus1y
898 ? diag::warn_cxx11_compat_constexpr_local_var
899 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000900 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000901 continue;
902 }
903
904 case Decl::NamespaceAlias:
905 case Decl::Function:
906 // These are disallowed in C++11 and permitted in C++1y. Allow them
907 // everywhere as an extension.
908 if (!Cxx1yLoc.isValid())
909 Cxx1yLoc = DS->getLocStart();
910 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000911
912 default:
913 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
914 << isa<CXXConstructorDecl>(Dcl);
915 return false;
916 }
917 }
918
919 return true;
920}
921
922/// Check that the given field is initialized within a constexpr constructor.
923///
924/// \param Dcl The constexpr constructor being checked.
925/// \param Field The field being checked. This may be a member of an anonymous
926/// struct or union nested within the class being checked.
927/// \param Inits All declarations, including anonymous struct/union members and
928/// indirect members, for which any initialization was provided.
929/// \param Diagnosed Set to true if an error is produced.
930static void CheckConstexprCtorInitializer(Sema &SemaRef,
931 const FunctionDecl *Dcl,
932 FieldDecl *Field,
933 llvm::SmallSet<Decl*, 16> &Inits,
934 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000935 if (Field->isInvalidDecl())
936 return;
937
Douglas Gregor556e5862011-10-10 17:22:13 +0000938 if (Field->isUnnamedBitfield())
939 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000940
Richard Smithab44d5b2013-12-10 08:25:00 +0000941 // Anonymous unions with no variant members and empty anonymous structs do not
942 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
943 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000944 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000945 (Field->getType()->isUnionType()
946 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
947 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000948 return;
949
Richard Smitheb3c10c2011-10-01 02:31:28 +0000950 if (!Inits.count(Field)) {
951 if (!Diagnosed) {
952 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
953 Diagnosed = true;
954 }
955 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
956 } else if (Field->isAnonymousStructOrUnion()) {
957 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000958 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000959 // If an anonymous union contains an anonymous struct of which any member
960 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000961 if (!RD->isUnion() || Inits.count(I))
962 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000963 }
964}
965
Richard Smithd9f663b2013-04-22 15:31:51 +0000966/// Check the provided statement is allowed in a constexpr function
967/// definition.
968static bool
969CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000970 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000971 SourceLocation &Cxx1yLoc) {
972 // - its function-body shall be [...] a compound-statement that contains only
973 switch (S->getStmtClass()) {
974 case Stmt::NullStmtClass:
975 // - null statements,
976 return true;
977
978 case Stmt::DeclStmtClass:
979 // - static_assert-declarations
980 // - using-declarations,
981 // - using-directives,
982 // - typedef declarations and alias-declarations that do not define
983 // classes or enumerations,
984 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
985 return false;
986 return true;
987
988 case Stmt::ReturnStmtClass:
989 // - and exactly one return statement;
990 if (isa<CXXConstructorDecl>(Dcl)) {
991 // C++1y allows return statements in constexpr constructors.
992 if (!Cxx1yLoc.isValid())
993 Cxx1yLoc = S->getLocStart();
994 return true;
995 }
996
997 ReturnStmts.push_back(S->getLocStart());
998 return true;
999
1000 case Stmt::CompoundStmtClass: {
1001 // C++1y allows compound-statements.
1002 if (!Cxx1yLoc.isValid())
1003 Cxx1yLoc = S->getLocStart();
1004
1005 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001006 for (auto *BodyIt : CompStmt->body()) {
1007 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001008 Cxx1yLoc))
1009 return false;
1010 }
1011 return true;
1012 }
1013
1014 case Stmt::AttributedStmtClass:
1015 if (!Cxx1yLoc.isValid())
1016 Cxx1yLoc = S->getLocStart();
1017 return true;
1018
1019 case Stmt::IfStmtClass: {
1020 // C++1y allows if-statements.
1021 if (!Cxx1yLoc.isValid())
1022 Cxx1yLoc = S->getLocStart();
1023
1024 IfStmt *If = cast<IfStmt>(S);
1025 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1026 Cxx1yLoc))
1027 return false;
1028 if (If->getElse() &&
1029 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1030 Cxx1yLoc))
1031 return false;
1032 return true;
1033 }
1034
1035 case Stmt::WhileStmtClass:
1036 case Stmt::DoStmtClass:
1037 case Stmt::ForStmtClass:
1038 case Stmt::CXXForRangeStmtClass:
1039 case Stmt::ContinueStmtClass:
1040 // C++1y allows all of these. We don't allow them as extensions in C++11,
1041 // because they don't make sense without variable mutation.
1042 if (!SemaRef.getLangOpts().CPlusPlus1y)
1043 break;
1044 if (!Cxx1yLoc.isValid())
1045 Cxx1yLoc = S->getLocStart();
1046 for (Stmt::child_range Children = S->children(); Children; ++Children)
1047 if (*Children &&
1048 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1049 Cxx1yLoc))
1050 return false;
1051 return true;
1052
1053 case Stmt::SwitchStmtClass:
1054 case Stmt::CaseStmtClass:
1055 case Stmt::DefaultStmtClass:
1056 case Stmt::BreakStmtClass:
1057 // C++1y allows switch-statements, and since they don't need variable
1058 // mutation, we can reasonably allow them in C++11 as an extension.
1059 if (!Cxx1yLoc.isValid())
1060 Cxx1yLoc = S->getLocStart();
1061 for (Stmt::child_range Children = S->children(); Children; ++Children)
1062 if (*Children &&
1063 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1064 Cxx1yLoc))
1065 return false;
1066 return true;
1067
1068 default:
1069 if (!isa<Expr>(S))
1070 break;
1071
1072 // C++1y allows expression-statements.
1073 if (!Cxx1yLoc.isValid())
1074 Cxx1yLoc = S->getLocStart();
1075 return true;
1076 }
1077
1078 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1079 << isa<CXXConstructorDecl>(Dcl);
1080 return false;
1081}
1082
Richard Smitheb3c10c2011-10-01 02:31:28 +00001083/// Check the body for the given constexpr function declaration only contains
1084/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1085///
1086/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001087bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001088 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001089 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001090 // The definition of a constexpr function shall satisfy the following
1091 // constraints: [...]
1092 // - its function-body shall be = delete, = default, or a
1093 // compound-statement
1094 //
Richard Smith74388b42012-02-04 00:33:54 +00001095 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001096 // In the definition of a constexpr constructor, [...]
1097 // - its function-body shall not be a function-try-block;
1098 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1099 << isa<CXXConstructorDecl>(Dcl);
1100 return false;
1101 }
1102
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001103 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001104
1105 // - its function-body shall be [...] a compound-statement that contains only
1106 // [... list of cases ...]
1107 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1108 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001109 for (auto *BodyIt : CompBody->body()) {
1110 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001111 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001112 }
1113
Richard Smithd9f663b2013-04-22 15:31:51 +00001114 if (Cxx1yLoc.isValid())
1115 Diag(Cxx1yLoc,
1116 getLangOpts().CPlusPlus1y
1117 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1118 : diag::ext_constexpr_body_invalid_stmt)
1119 << isa<CXXConstructorDecl>(Dcl);
1120
Richard Smitheb3c10c2011-10-01 02:31:28 +00001121 if (const CXXConstructorDecl *Constructor
1122 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1123 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001124 // DR1359:
1125 // - every non-variant non-static data member and base class sub-object
1126 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001127 // DR1460:
1128 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001129 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001130 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001131 if (Constructor->getNumCtorInitializers() == 0 &&
1132 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001133 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1134 return false;
1135 }
Richard Smithf368fb42011-10-10 16:38:04 +00001136 } else if (!Constructor->isDependentContext() &&
1137 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001138 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1139
1140 // Skip detailed checking if we have enough initializers, and we would
1141 // allow at most one initializer per member.
1142 bool AnyAnonStructUnionMembers = false;
1143 unsigned Fields = 0;
1144 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1145 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001146 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001147 AnyAnonStructUnionMembers = true;
1148 break;
1149 }
1150 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001151 // DR1460:
1152 // - if the class is a union-like class, but is not a union, for each of
1153 // its anonymous union members having variant members, exactly one of
1154 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001155 if (AnyAnonStructUnionMembers ||
1156 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1157 // Check initialization of non-static data members. Base classes are
1158 // always initialized so do not need to be checked. Dependent bases
1159 // might not have initializers in the member initializer list.
1160 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001161 for (const auto *I: Constructor->inits()) {
1162 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001163 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001164 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001165 Inits.insert(ID->chain_begin(), ID->chain_end());
1166 }
1167
1168 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001169 for (auto *I : RD->fields())
1170 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001171 if (Diagnosed)
1172 return false;
1173 }
1174 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001175 } else {
1176 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001177 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001178 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001179 // otherwise if there's no return statement, the function cannot
1180 // be used in a core constant expression.
Richard Smith06ffb452014-04-22 23:14:23 +00001181 bool OK = getLangOpts().CPlusPlus1y &&
1182 (Dcl->getReturnType()->isVoidType() ||
1183 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001184 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001185 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1186 : diag::err_constexpr_body_no_return);
1187 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001188 }
1189 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001190 Diag(ReturnStmts.back(),
1191 getLangOpts().CPlusPlus1y
1192 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1193 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001194 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1195 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001196 }
1197 }
1198
Richard Smith74388b42012-02-04 00:33:54 +00001199 // C++11 [dcl.constexpr]p5:
1200 // if no function argument values exist such that the function invocation
1201 // substitution would produce a constant expression, the program is
1202 // ill-formed; no diagnostic required.
1203 // C++11 [dcl.constexpr]p3:
1204 // - every constructor call and implicit conversion used in initializing the
1205 // return value shall be one of those allowed in a constant expression.
1206 // C++11 [dcl.constexpr]p4:
1207 // - every constructor involved in initializing non-static data members and
1208 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001209 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001210 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001211 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001212 << isa<CXXConstructorDecl>(Dcl);
1213 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1214 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001215 // Don't return false here: we allow this for compatibility in
1216 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001217 }
1218
Richard Smitheb3c10c2011-10-01 02:31:28 +00001219 return true;
1220}
1221
Douglas Gregor61956c42008-10-31 09:07:45 +00001222/// isCurrentClassName - Determine whether the identifier II is the
1223/// name of the class type currently being defined. In the case of
1224/// nested classes, this will only return true if II is the name of
1225/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001226bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1227 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001228 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001229
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001230 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001231 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001232 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001233 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1234 } else
1235 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1236
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001237 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001238 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001239 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001240}
1241
Richard Smithfb8b7b92013-10-15 00:00:26 +00001242/// \brief Determine whether the identifier II is a typo for the name of
1243/// the class type currently being defined. If so, update it to the identifier
1244/// that should have been used.
1245bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1246 assert(getLangOpts().CPlusPlus && "No class names in C!");
1247
1248 if (!getLangOpts().SpellChecking)
1249 return false;
1250
1251 CXXRecordDecl *CurDecl;
1252 if (SS && SS->isSet() && !SS->isInvalid()) {
1253 DeclContext *DC = computeDeclContext(*SS, true);
1254 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1255 } else
1256 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1257
1258 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1259 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1260 < II->getLength()) {
1261 II = CurDecl->getIdentifier();
1262 return true;
1263 }
1264
1265 return false;
1266}
1267
Douglas Gregordc974572012-11-10 07:24:09 +00001268/// \brief Determine whether the given class is a base class of the given
1269/// class, including looking at dependent bases.
1270static bool findCircularInheritance(const CXXRecordDecl *Class,
1271 const CXXRecordDecl *Current) {
1272 SmallVector<const CXXRecordDecl*, 8> Queue;
1273
1274 Class = Class->getCanonicalDecl();
1275 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001276 for (const auto &I : Current->bases()) {
1277 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001278 if (!Base)
1279 continue;
1280
1281 Base = Base->getDefinition();
1282 if (!Base)
1283 continue;
1284
1285 if (Base->getCanonicalDecl() == Class)
1286 return true;
1287
1288 Queue.push_back(Base);
1289 }
1290
1291 if (Queue.empty())
1292 return false;
1293
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001294 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001295 }
1296
1297 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001298}
1299
Mike Stump11289f42009-09-09 15:08:12 +00001300/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001301///
1302/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1303/// and returns NULL otherwise.
1304CXXBaseSpecifier *
1305Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1306 SourceRange SpecifierRange,
1307 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001308 TypeSourceInfo *TInfo,
1309 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001310 QualType BaseType = TInfo->getType();
1311
Douglas Gregor463421d2009-03-03 04:44:36 +00001312 // C++ [class.union]p1:
1313 // A union shall not have base classes.
1314 if (Class->isUnion()) {
1315 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1316 << SpecifierRange;
1317 return 0;
1318 }
1319
Douglas Gregor752a5952011-01-03 22:36:02 +00001320 if (EllipsisLoc.isValid() &&
1321 !TInfo->getType()->containsUnexpandedParameterPack()) {
1322 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1323 << TInfo->getTypeLoc().getSourceRange();
1324 EllipsisLoc = SourceLocation();
1325 }
Douglas Gregor62004702012-11-10 01:18:17 +00001326
1327 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1328
1329 if (BaseType->isDependentType()) {
1330 // Make sure that we don't have circular inheritance among our dependent
1331 // bases. For non-dependent bases, the check for completeness below handles
1332 // this.
1333 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1334 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1335 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001336 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001337 Diag(BaseLoc, diag::err_circular_inheritance)
1338 << BaseType << Context.getTypeDeclType(Class);
1339
1340 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1341 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1342 << BaseType;
1343
1344 return 0;
1345 }
1346 }
1347
Mike Stump11289f42009-09-09 15:08:12 +00001348 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001349 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001350 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001351 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001352
1353 // Base specifiers must be record types.
1354 if (!BaseType->isRecordType()) {
1355 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1356 return 0;
1357 }
1358
1359 // C++ [class.union]p1:
1360 // A union shall not be used as a base class.
1361 if (BaseType->isUnionType()) {
1362 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1363 return 0;
1364 }
1365
1366 // C++ [class.derived]p2:
1367 // The class-name in a base-specifier shall not be an incompletely
1368 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001369 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001370 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001371 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001372 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001373 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001374
Eli Friedmanc96d4962009-08-15 21:55:26 +00001375 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001376 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001377 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001378 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001379 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001380 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001381 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001382
David Majnemer9b1754d2013-11-02 12:00:36 +00001383 // A class which contains a flexible array member is not suitable for use as a
1384 // base class:
1385 // - If the layout determines that a base comes before another base,
1386 // the flexible array member would index into the subsequent base.
1387 // - If the layout determines that base comes before the derived class,
1388 // the flexible array member would index into the derived class.
1389 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1390 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1391 << CXXBaseDecl->getDeclName();
1392 return 0;
1393 }
1394
Anders Carlsson65c76d32011-03-25 14:55:14 +00001395 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001396 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001397 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001398 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001399 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001400 << CXXBaseDecl->getDeclName()
1401 << FA->isSpelledAsSealed();
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001402 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1403 << CXXBaseDecl->getDeclName();
1404 return 0;
1405 }
1406
John McCall3696dcb2010-08-17 07:23:57 +00001407 if (BaseDecl->isInvalidDecl())
1408 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001409
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001410 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001411 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001412 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001413 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001414}
1415
Douglas Gregor556877c2008-04-13 21:30:24 +00001416/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1417/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001418/// example:
1419/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001420/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001421BaseResult
John McCall48871652010-08-21 09:40:31 +00001422Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001423 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001424 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001425 ParsedType basetype, SourceLocation BaseLoc,
1426 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001427 if (!classdecl)
1428 return true;
1429
Douglas Gregorc40290e2009-03-09 23:48:35 +00001430 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001431 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001432 if (!Class)
1433 return true;
1434
Richard Smith4c96e992013-02-19 23:47:15 +00001435 // We do not support any C++11 attributes on base-specifiers yet.
1436 // Diagnose any attributes we see.
1437 if (!Attributes.empty()) {
1438 for (AttributeList *Attr = Attributes.getList(); Attr;
1439 Attr = Attr->getNext()) {
1440 if (Attr->isInvalid() ||
1441 Attr->getKind() == AttributeList::IgnoredAttribute)
1442 continue;
1443 Diag(Attr->getLoc(),
1444 Attr->getKind() == AttributeList::UnknownAttribute
1445 ? diag::warn_unknown_attribute_ignored
1446 : diag::err_base_specifier_attribute)
1447 << Attr->getName();
1448 }
1449 }
1450
Nick Lewycky19b9f952010-07-26 16:56:01 +00001451 TypeSourceInfo *TInfo = 0;
1452 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001453
Douglas Gregor752a5952011-01-03 22:36:02 +00001454 if (EllipsisLoc.isInvalid() &&
1455 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001456 UPPC_BaseType))
1457 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001458
Douglas Gregor463421d2009-03-03 04:44:36 +00001459 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001460 Virtual, Access, TInfo,
1461 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001462 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001463 else
1464 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001465
Douglas Gregor463421d2009-03-03 04:44:36 +00001466 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001467}
Douglas Gregor556877c2008-04-13 21:30:24 +00001468
Douglas Gregor463421d2009-03-03 04:44:36 +00001469/// \brief Performs the actual work of attaching the given base class
1470/// specifiers to a C++ class.
1471bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1472 unsigned NumBases) {
1473 if (NumBases == 0)
1474 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001475
1476 // Used to keep track of which base types we have already seen, so
1477 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001478 // that the key is always the unqualified canonical type of the base
1479 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001480 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1481
1482 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001483 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001484 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001485 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001486 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001487 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001488 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001489
1490 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1491 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001492 // C++ [class.mi]p3:
1493 // A class shall not be specified as a direct base class of a
1494 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001495 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001496 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001497 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001498 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001499
1500 // Delete the duplicate base class specifier; we're going to
1501 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001502 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001503
1504 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001505 } else {
1506 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001507 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001508 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001509 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1510 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1511 if (Class->isInterface() &&
1512 (!RD->isInterface() ||
1513 KnownBase->getAccessSpecifier() != AS_public)) {
1514 // The Microsoft extension __interface does not permit bases that
1515 // are not themselves public interfaces.
1516 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1517 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1518 << RD->getSourceRange();
1519 Invalid = true;
1520 }
1521 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001522 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001523 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001524 }
1525 }
1526
1527 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001528 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001529
1530 // Delete the remaining (good) base class specifiers, since their
1531 // data has been copied into the CXXRecordDecl.
1532 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001533 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001534
1535 return Invalid;
1536}
1537
1538/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1539/// class, after checking whether there are any duplicate base
1540/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001541void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001542 unsigned NumBases) {
1543 if (!ClassDecl || !Bases || !NumBases)
1544 return;
1545
1546 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001547 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001548}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001549
Douglas Gregor36d1b142009-10-06 17:59:45 +00001550/// \brief Determine whether the type \p Derived is a C++ class that is
1551/// derived from the type \p Base.
1552bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001553 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001554 return false;
John McCalle78aac42010-03-10 03:28:59 +00001555
Douglas Gregor45bb4832013-03-26 23:36:30 +00001556 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001557 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001558 return false;
1559
Douglas Gregor45bb4832013-03-26 23:36:30 +00001560 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001561 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001562 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001563
1564 // If either the base or the derived type is invalid, don't try to
1565 // check whether one is derived from the other.
1566 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1567 return false;
1568
John McCall67da35c2010-02-04 22:26:26 +00001569 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1570 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001571}
1572
1573/// \brief Determine whether the type \p Derived is a C++ class that is
1574/// derived from the type \p Base.
1575bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001576 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001577 return false;
1578
Douglas Gregor45bb4832013-03-26 23:36:30 +00001579 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001580 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001581 return false;
1582
Douglas Gregor45bb4832013-03-26 23:36:30 +00001583 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001584 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001585 return false;
1586
Douglas Gregor36d1b142009-10-06 17:59:45 +00001587 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1588}
1589
Anders Carlssona70cff62010-04-24 19:06:50 +00001590void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001591 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001592 assert(BasePathArray.empty() && "Base path array must be empty!");
1593 assert(Paths.isRecordingPaths() && "Must record paths!");
1594
1595 const CXXBasePath &Path = Paths.front();
1596
1597 // We first go backward and check if we have a virtual base.
1598 // FIXME: It would be better if CXXBasePath had the base specifier for
1599 // the nearest virtual base.
1600 unsigned Start = 0;
1601 for (unsigned I = Path.size(); I != 0; --I) {
1602 if (Path[I - 1].Base->isVirtual()) {
1603 Start = I - 1;
1604 break;
1605 }
1606 }
1607
1608 // Now add all bases.
1609 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001610 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001611}
1612
Douglas Gregor88d292c2010-05-13 16:44:06 +00001613/// \brief Determine whether the given base path includes a virtual
1614/// base class.
John McCallcf142162010-08-07 06:22:56 +00001615bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1616 for (CXXCastPath::const_iterator B = BasePath.begin(),
1617 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001618 B != BEnd; ++B)
1619 if ((*B)->isVirtual())
1620 return true;
1621
1622 return false;
1623}
1624
Douglas Gregor36d1b142009-10-06 17:59:45 +00001625/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1626/// conversion (where Derived and Base are class types) is
1627/// well-formed, meaning that the conversion is unambiguous (and
1628/// that all of the base classes are accessible). Returns true
1629/// and emits a diagnostic if the code is ill-formed, returns false
1630/// otherwise. Loc is the location where this routine should point to
1631/// if there is an error, and Range is the source range to highlight
1632/// if there is an error.
1633bool
1634Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001635 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001636 unsigned AmbigiousBaseConvID,
1637 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001638 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001639 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001640 // First, determine whether the path from Derived to Base is
1641 // ambiguous. This is slightly more expensive than checking whether
1642 // the Derived to Base conversion exists, because here we need to
1643 // explore multiple paths to determine if there is an ambiguity.
1644 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1645 /*DetectVirtual=*/false);
1646 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1647 assert(DerivationOkay &&
1648 "Can only be used with a derived-to-base conversion");
1649 (void)DerivationOkay;
1650
1651 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001652 if (InaccessibleBaseID) {
1653 // Check that the base class can be accessed.
1654 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1655 InaccessibleBaseID)) {
1656 case AR_inaccessible:
1657 return true;
1658 case AR_accessible:
1659 case AR_dependent:
1660 case AR_delayed:
1661 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001662 }
John McCall5b0829a2010-02-10 09:31:12 +00001663 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001664
1665 // Build a base path if necessary.
1666 if (BasePath)
1667 BuildBasePathArray(Paths, *BasePath);
1668 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001669 }
1670
David Majnemer626032f2013-06-22 06:43:58 +00001671 if (AmbigiousBaseConvID) {
1672 // We know that the derived-to-base conversion is ambiguous, and
1673 // we're going to produce a diagnostic. Perform the derived-to-base
1674 // search just one more time to compute all of the possible paths so
1675 // that we can print them out. This is more expensive than any of
1676 // the previous derived-to-base checks we've done, but at this point
1677 // performance isn't as much of an issue.
1678 Paths.clear();
1679 Paths.setRecordingPaths(true);
1680 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1681 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1682 (void)StillOkay;
1683
1684 // Build up a textual representation of the ambiguous paths, e.g.,
1685 // D -> B -> A, that will be used to illustrate the ambiguous
1686 // conversions in the diagnostic. We only print one of the paths
1687 // to each base class subobject.
1688 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1689
1690 Diag(Loc, AmbigiousBaseConvID)
1691 << Derived << Base << PathDisplayStr << Range << Name;
1692 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001693 return true;
1694}
1695
1696bool
1697Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001698 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001699 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001700 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001701 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001702 IgnoreAccess ? 0
1703 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001704 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001705 Loc, Range, DeclarationName(),
1706 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001707}
1708
1709
1710/// @brief Builds a string representing ambiguous paths from a
1711/// specific derived class to different subobjects of the same base
1712/// class.
1713///
1714/// This function builds a string that can be used in error messages
1715/// to show the different paths that one can take through the
1716/// inheritance hierarchy to go from the derived class to different
1717/// subobjects of a base class. The result looks something like this:
1718/// @code
1719/// struct D -> struct B -> struct A
1720/// struct D -> struct C -> struct A
1721/// @endcode
1722std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1723 std::string PathDisplayStr;
1724 std::set<unsigned> DisplayedPaths;
1725 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1726 Path != Paths.end(); ++Path) {
1727 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1728 // We haven't displayed a path to this particular base
1729 // class subobject yet.
1730 PathDisplayStr += "\n ";
1731 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1732 for (CXXBasePath::const_iterator Element = Path->begin();
1733 Element != Path->end(); ++Element)
1734 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1735 }
1736 }
1737
1738 return PathDisplayStr;
1739}
1740
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001741//===----------------------------------------------------------------------===//
1742// C++ class member Handling
1743//===----------------------------------------------------------------------===//
1744
Abramo Bagnarad7340582010-06-05 05:09:32 +00001745/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001746bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1747 SourceLocation ASLoc,
1748 SourceLocation ColonLoc,
1749 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001750 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001751 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001752 ASLoc, ColonLoc);
1753 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001754 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001755}
1756
Richard Smith18f07db2012-08-06 03:25:17 +00001757/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001758void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001759 if (D->isInvalidDecl())
1760 return;
1761
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001762 // We only care about "override" and "final" declarations.
1763 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1764 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001765
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001766 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001767
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001768 // We can't check dependent instance methods.
1769 if (MD && MD->isInstance() &&
1770 (MD->getParent()->hasAnyDependentBases() ||
1771 MD->getType()->isDependentType()))
1772 return;
1773
1774 if (MD && !MD->isVirtual()) {
1775 // If we have a non-virtual method, check if if hides a virtual method.
1776 // (In that case, it's most likely the method has the wrong type.)
1777 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1778 FindHiddenVirtualMethods(MD, OverloadedMethods);
1779
1780 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001781 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1782 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001783 diag::override_keyword_hides_virtual_member_function)
1784 << "override" << (OverloadedMethods.size() > 1);
1785 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001786 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001787 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001788 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1789 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001790 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001791 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1792 MD->setInvalidDecl();
1793 return;
1794 }
1795 // Fall through into the general case diagnostic.
1796 // FIXME: We might want to attempt typo correction here.
1797 }
1798
1799 if (!MD || !MD->isVirtual()) {
1800 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1801 Diag(OA->getLocation(),
1802 diag::override_keyword_only_allowed_on_virtual_member_functions)
1803 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1804 D->dropAttr<OverrideAttr>();
1805 }
1806 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1807 Diag(FA->getLocation(),
1808 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001809 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1810 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001811 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001812 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001813 return;
1814 }
Richard Smith18f07db2012-08-06 03:25:17 +00001815
Richard Smith18f07db2012-08-06 03:25:17 +00001816 // C++11 [class.virtual]p5:
1817 // If a virtual function is marked with the virt-specifier override and
1818 // does not override a member function of a base class, the program is
1819 // ill-formed.
1820 bool HasOverriddenMethods =
1821 MD->begin_overridden_methods() != MD->end_overridden_methods();
1822 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1823 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1824 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001825}
1826
Richard Smith18f07db2012-08-06 03:25:17 +00001827/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001828/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001829/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001830bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1831 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001832 FinalAttr *FA = Old->getAttr<FinalAttr>();
1833 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001834 return false;
1835
1836 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001837 << New->getDeclName()
1838 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001839 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1840 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001841}
1842
Daniel Jasper0baec5492012-06-06 08:32:04 +00001843static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001844 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1845 // FIXME: Destruction of ObjC lifetime types has side-effects.
1846 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1847 return !RD->isCompleteDefinition() ||
1848 !RD->hasTrivialDefaultConstructor() ||
1849 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001850 return false;
1851}
1852
John McCall5e77d762013-04-16 07:28:30 +00001853static AttributeList *getMSPropertyAttr(AttributeList *list) {
1854 for (AttributeList* it = list; it != 0; it = it->getNext())
1855 if (it->isDeclspecPropertyAttribute())
1856 return it;
1857 return 0;
1858}
1859
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001860/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1861/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001862/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001863/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1864/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001865NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001866Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001867 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001868 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001869 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001870 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001871 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1872 DeclarationName Name = NameInfo.getName();
1873 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001874
1875 // For anonymous bitfields, the location should point to the type.
1876 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001877 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001878
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001879 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001880
John McCallb1cd7da2010-06-04 08:34:12 +00001881 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001882 assert(!DS.isFriendSpecified());
1883
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001884 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001885
John McCalldb632ac2012-09-25 07:32:39 +00001886 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1887 // The Microsoft extension __interface only permits public member functions
1888 // and prohibits constructors, destructors, operators, non-public member
1889 // functions, static methods and data members.
1890 unsigned InvalidDecl;
1891 bool ShowDeclName = true;
1892 if (!isFunc)
1893 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1894 else if (AS != AS_public)
1895 InvalidDecl = 2;
1896 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1897 InvalidDecl = 3;
1898 else switch (Name.getNameKind()) {
1899 case DeclarationName::CXXConstructorName:
1900 InvalidDecl = 4;
1901 ShowDeclName = false;
1902 break;
1903
1904 case DeclarationName::CXXDestructorName:
1905 InvalidDecl = 5;
1906 ShowDeclName = false;
1907 break;
1908
1909 case DeclarationName::CXXOperatorName:
1910 case DeclarationName::CXXConversionFunctionName:
1911 InvalidDecl = 6;
1912 break;
1913
1914 default:
1915 InvalidDecl = 0;
1916 break;
1917 }
1918
1919 if (InvalidDecl) {
1920 if (ShowDeclName)
1921 Diag(Loc, diag::err_invalid_member_in_interface)
1922 << (InvalidDecl-1) << Name;
1923 else
1924 Diag(Loc, diag::err_invalid_member_in_interface)
1925 << (InvalidDecl-1) << "";
1926 return 0;
1927 }
1928 }
1929
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001930 // C++ 9.2p6: A member shall not be declared to have automatic storage
1931 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001932 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1933 // data members and cannot be applied to names declared const or static,
1934 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001935 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001936 case DeclSpec::SCS_unspecified:
1937 case DeclSpec::SCS_typedef:
1938 case DeclSpec::SCS_static:
1939 break;
1940 case DeclSpec::SCS_mutable:
1941 if (isFunc) {
1942 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001943
Richard Smithb4a9e862013-04-12 22:46:28 +00001944 // FIXME: It would be nicer if the keyword was ignored only for this
1945 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001946 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001947 }
1948 break;
1949 default:
1950 Diag(DS.getStorageClassSpecLoc(),
1951 diag::err_storageclass_invalid_for_member);
1952 D.getMutableDeclSpec().ClearStorageClassSpecs();
1953 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001954 }
1955
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001956 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1957 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001958 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001959
David Blaikie35506f82013-01-30 01:22:18 +00001960 if (DS.isConstexprSpecified() && isInstField) {
1961 SemaDiagnosticBuilder B =
1962 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1963 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1964 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00001965 B << 0 << 0;
1966 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
1967 B << FixItHint::CreateRemoval(ConstexprLoc);
1968 else {
1969 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
1970 D.getMutableDeclSpec().ClearConstexprSpec();
1971 const char *PrevSpec;
1972 unsigned DiagID;
1973 bool Failed = D.getMutableDeclSpec().SetTypeQual(
1974 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
1975 (void)Failed;
1976 assert(!Failed && "Making a constexpr member const shouldn't fail");
1977 }
David Blaikie35506f82013-01-30 01:22:18 +00001978 } else {
1979 B << 1;
1980 const char *PrevSpec;
1981 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001982 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001983 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1984 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001985 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001986 "This is the only DeclSpec that should fail to be applied");
1987 B << 1;
1988 } else {
1989 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1990 isInstField = false;
1991 }
1992 }
1993 }
1994
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001995 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001996 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001997 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001998
1999 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002000 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002001 Diag(Loc, diag::err_bad_variable_name)
2002 << Name;
2003 return 0;
2004 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002005
Benjamin Kramer365082d2012-05-19 16:34:46 +00002006 IdentifierInfo *II = Name.getAsIdentifierInfo();
2007
Douglas Gregor7c26c042011-09-21 14:40:46 +00002008 // Member field could not be with "template" keyword.
2009 // So TemplateParameterLists should be empty in this case.
2010 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002011 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002012 if (TemplateParams->size()) {
2013 // There is no such thing as a member field template.
2014 Diag(D.getIdentifierLoc(), diag::err_template_member)
2015 << II
2016 << SourceRange(TemplateParams->getTemplateLoc(),
2017 TemplateParams->getRAngleLoc());
2018 } else {
2019 // There is an extraneous 'template<>' for this member.
2020 Diag(TemplateParams->getTemplateLoc(),
2021 diag::err_template_member_noparams)
2022 << II
2023 << SourceRange(TemplateParams->getTemplateLoc(),
2024 TemplateParams->getRAngleLoc());
2025 }
2026 return 0;
2027 }
2028
Douglas Gregora007d362010-10-13 22:19:53 +00002029 if (SS.isSet() && !SS.isInvalid()) {
2030 // The user provided a superfluous scope specifier inside a class
2031 // definition:
2032 //
2033 // class X {
2034 // int X::member;
2035 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002036 if (DeclContext *DC = computeDeclContext(SS, false))
2037 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002038 else
2039 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2040 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002041
Douglas Gregora007d362010-10-13 22:19:53 +00002042 SS.clear();
2043 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002044
John McCall5e77d762013-04-16 07:28:30 +00002045 AttributeList *MSPropertyAttr =
2046 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002047 if (MSPropertyAttr) {
2048 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2049 BitWidth, InitStyle, AS, MSPropertyAttr);
2050 if (!Member)
2051 return 0;
2052 isInstField = false;
2053 } else {
2054 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2055 BitWidth, InitStyle, AS);
2056 assert(Member && "HandleField never returns null");
2057 }
2058 } else {
2059 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2060
2061 Member = HandleDeclarator(S, D, TemplateParameterLists);
2062 if (!Member)
2063 return 0;
2064
2065 // Non-instance-fields can't have a bitfield.
2066 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002067 if (Member->isInvalidDecl()) {
2068 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002069 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002070 // C++ 9.6p3: A bit-field shall not be a static member.
2071 // "static member 'A' cannot be a bit-field"
2072 Diag(Loc, diag::err_static_not_bitfield)
2073 << Name << BitWidth->getSourceRange();
2074 } else if (isa<TypedefDecl>(Member)) {
2075 // "typedef member 'x' cannot be a bit-field"
2076 Diag(Loc, diag::err_typedef_not_bitfield)
2077 << Name << BitWidth->getSourceRange();
2078 } else {
2079 // A function typedef ("typedef int f(); f a;").
2080 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2081 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002082 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002083 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002084 }
Mike Stump11289f42009-09-09 15:08:12 +00002085
Chris Lattnerd26760a2009-03-05 23:01:03 +00002086 BitWidth = 0;
2087 Member->setInvalidDecl();
2088 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002089
2090 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002091
Larisse Voufo39a1e502013-08-06 01:03:05 +00002092 // If we have declared a member function template or static data member
2093 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002094 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2095 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002096 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2097 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002098 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002099
Richard Smith18f07db2012-08-06 03:25:17 +00002100 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002101 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002102 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002103 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2104 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002105
Douglas Gregorf2f08062011-03-08 17:10:18 +00002106 if (VS.getLastLocation().isValid()) {
2107 // Update the end location of a method that has a virt-specifiers.
2108 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2109 MD->setRangeEnd(VS.getLastLocation());
2110 }
Richard Smith18f07db2012-08-06 03:25:17 +00002111
Anders Carlssonc87f8612011-01-20 06:29:02 +00002112 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002113
Douglas Gregor92751d42008-11-17 22:58:34 +00002114 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002115
Daniel Jasper0baec5492012-06-06 08:32:04 +00002116 if (isInstField) {
2117 FieldDecl *FD = cast<FieldDecl>(Member);
2118 FieldCollector->Add(FD);
2119
2120 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2121 FD->getLocation())
2122 != DiagnosticsEngine::Ignored) {
2123 // Remember all explicit private FieldDecls that have a name, no side
2124 // effects and are not part of a dependent type declaration.
2125 if (!FD->isImplicit() && FD->getDeclName() &&
2126 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002127 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002128 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002129 !InitializationHasSideEffects(*FD))
2130 UnusedPrivateFields.insert(FD);
2131 }
2132 }
2133
John McCall48871652010-08-21 09:40:31 +00002134 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002135}
2136
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002137namespace {
2138 class UninitializedFieldVisitor
2139 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2140 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002141 // List of Decls to generate a warning on. Also remove Decls that become
2142 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002143 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002144 // If non-null, add a note to the warning pointing back to the constructor.
2145 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002146 public:
2147 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002148 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002149 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002150 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002151 : Inherited(S.Context), S(S), Decls(Decls),
2152 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002153
Richard Trieufd687772013-09-16 20:46:50 +00002154 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002155 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2156 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002157
Richard Trieu1bc22c12013-09-13 03:20:53 +00002158 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2159 // or union.
2160 MemberExpr *FieldME = ME;
2161
2162 Expr *Base = ME;
2163 while (isa<MemberExpr>(Base)) {
2164 ME = cast<MemberExpr>(Base);
2165
2166 if (isa<VarDecl>(ME->getMemberDecl()))
2167 return;
2168
2169 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2170 if (!FD->isAnonymousStructOrUnion())
2171 FieldME = ME;
2172
2173 Base = ME->getBase();
2174 }
2175
Richard Trieufd687772013-09-16 20:46:50 +00002176 if (!isa<CXXThisExpr>(Base))
2177 return;
2178
Richard Trieu406e65c2013-09-20 03:03:06 +00002179 ValueDecl* FoundVD = FieldME->getMemberDecl();
2180
Richard Trieuef64e942013-10-25 00:56:00 +00002181 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002182 return;
2183
Richard Trieuef64e942013-10-25 00:56:00 +00002184 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002185
Richard Trieuef64e942013-10-25 00:56:00 +00002186 // Prevent double warnings on use of unbounded references.
2187 if (IsReference != CheckReferenceOnly)
2188 return;
2189
2190 unsigned diag = IsReference
2191 ? diag::warn_reference_field_is_uninit
2192 : diag::warn_field_is_uninit;
2193 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2194 if (Constructor)
2195 S.Diag(Constructor->getLocation(),
2196 diag::note_uninit_in_this_constructor)
2197 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2198
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002199 }
2200
2201 void HandleValue(Expr *E) {
2202 E = E->IgnoreParens();
2203
2204 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002205 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002206 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002207 }
2208
2209 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2210 HandleValue(CO->getTrueExpr());
2211 HandleValue(CO->getFalseExpr());
2212 return;
2213 }
2214
2215 if (BinaryConditionalOperator *BCO =
2216 dyn_cast<BinaryConditionalOperator>(E)) {
2217 HandleValue(BCO->getCommon());
2218 HandleValue(BCO->getFalseExpr());
2219 return;
2220 }
2221
2222 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2223 switch (BO->getOpcode()) {
2224 default:
2225 return;
2226 case(BO_PtrMemD):
2227 case(BO_PtrMemI):
2228 HandleValue(BO->getLHS());
2229 return;
2230 case(BO_Comma):
2231 HandleValue(BO->getRHS());
2232 return;
2233 }
2234 }
2235 }
2236
Richard Trieu1bc22c12013-09-13 03:20:53 +00002237 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002238 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002239 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002240
2241 Inherited::VisitMemberExpr(ME);
2242 }
2243
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002244 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2245 if (E->getCastKind() == CK_LValueToRValue)
2246 HandleValue(E->getSubExpr());
2247
2248 Inherited::VisitImplicitCastExpr(E);
2249 }
2250
Richard Trieu1bc22c12013-09-13 03:20:53 +00002251 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002252 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002253 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2254 if (ICE->getCastKind() == CK_NoOp)
2255 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002256 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002257
2258 Inherited::VisitCXXConstructExpr(E);
2259 }
2260
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002261 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2262 Expr *Callee = E->getCallee();
2263 if (isa<MemberExpr>(Callee))
2264 HandleValue(Callee);
2265
2266 Inherited::VisitCXXMemberCallExpr(E);
2267 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002268
2269 void VisitBinaryOperator(BinaryOperator *E) {
2270 // If a field assignment is detected, remove the field from the
2271 // uninitiailized field set.
2272 if (E->getOpcode() == BO_Assign)
2273 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2274 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002275 if (!FD->getType()->isReferenceType())
2276 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002277
2278 Inherited::VisitBinaryOperator(E);
2279 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002280 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002281 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002282 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2283 const CXXConstructorDecl *Constructor) {
2284 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002285 return;
2286
Richard Trieuef64e942013-10-25 00:56:00 +00002287 if (!E)
2288 return;
2289
2290 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2291 E = Default->getExpr();
2292 if (!E)
2293 return;
2294 // In class initializers will point to the constructor.
2295 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2296 } else {
2297 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2298 }
2299 }
2300
2301 // Diagnose value-uses of fields to initialize themselves, e.g.
2302 // foo(foo)
2303 // where foo is not also a parameter to the constructor.
2304 // Also diagnose across field uninitialized use such as
2305 // x(y), y(x)
2306 // TODO: implement -Wuninitialized and fold this into that framework.
2307 static void DiagnoseUninitializedFields(
2308 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2309
2310 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2311 Constructor->getLocation())
2312 == DiagnosticsEngine::Ignored) {
2313 return;
2314 }
2315
2316 if (Constructor->isInvalidDecl())
2317 return;
2318
2319 const CXXRecordDecl *RD = Constructor->getParent();
2320
2321 // Holds fields that are uninitialized.
2322 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2323
2324 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002325 for (auto *I : RD->decls()) {
2326 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002327 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002328 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002329 UninitializedFields.insert(IFD->getAnonField());
2330 }
2331 }
2332
Aaron Ballman0ad78302014-03-13 17:34:31 +00002333 for (const auto *FieldInit : Constructor->inits()) {
2334 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002335
2336 CheckInitExprContainsUninitializedFields(
2337 SemaRef, InitExpr, UninitializedFields, Constructor);
2338
Aaron Ballman0ad78302014-03-13 17:34:31 +00002339 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002340 UninitializedFields.erase(Field);
2341 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002342 }
2343} // namespace
2344
Richard Smith74108172014-01-17 03:11:34 +00002345/// \brief Enter a new C++ default initializer scope. After calling this, the
2346/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2347/// parsing or instantiating the initializer failed.
2348void Sema::ActOnStartCXXInClassMemberInitializer() {
2349 // Create a synthetic function scope to represent the call to the constructor
2350 // that notionally surrounds a use of this initializer.
2351 PushFunctionScope();
2352}
2353
2354/// \brief This is invoked after parsing an in-class initializer for a
2355/// non-static C++ class member, and after instantiating an in-class initializer
2356/// in a class template. Such actions are deferred until the class is complete.
2357void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2358 SourceLocation InitLoc,
2359 Expr *InitExpr) {
2360 // Pop the notional constructor scope we created earlier.
2361 PopFunctionScopeInfo(0, D);
2362
Richard Smith938f40b2011-06-11 17:19:42 +00002363 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002364 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2365 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002366
2367 if (!InitExpr) {
2368 FD->setInvalidDecl();
2369 FD->removeInClassInitializer();
2370 return;
2371 }
2372
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002373 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2374 FD->setInvalidDecl();
2375 FD->removeInClassInitializer();
2376 return;
2377 }
2378
Richard Smith938f40b2011-06-11 17:19:42 +00002379 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002380 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002381 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002382 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002383 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002384 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002385 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2386 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002387 if (Init.isInvalid()) {
2388 FD->setInvalidDecl();
2389 return;
2390 }
Richard Smith938f40b2011-06-11 17:19:42 +00002391 }
2392
Richard Smith945f8d32013-01-14 22:39:08 +00002393 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002394 // The initialization of each base and member constitutes a
2395 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002396 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002397 if (Init.isInvalid()) {
2398 FD->setInvalidDecl();
2399 return;
2400 }
2401
2402 InitExpr = Init.release();
2403
2404 FD->setInClassInitializer(InitExpr);
2405}
2406
Douglas Gregor15e77a22009-12-31 09:10:24 +00002407/// \brief Find the direct and/or virtual base specifiers that
2408/// correspond to the given base type, for use in base initialization
2409/// within a constructor.
2410static bool FindBaseInitializer(Sema &SemaRef,
2411 CXXRecordDecl *ClassDecl,
2412 QualType BaseType,
2413 const CXXBaseSpecifier *&DirectBaseSpec,
2414 const CXXBaseSpecifier *&VirtualBaseSpec) {
2415 // First, check for a direct base class.
2416 DirectBaseSpec = 0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002417 for (const auto &Base : ClassDecl->bases()) {
2418 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002419 // We found a direct base of this type. That's what we're
2420 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002421 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002422 break;
2423 }
2424 }
2425
2426 // Check for a virtual base class.
2427 // FIXME: We might be able to short-circuit this if we know in advance that
2428 // there are no virtual bases.
2429 VirtualBaseSpec = 0;
2430 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2431 // We haven't found a base yet; search the class hierarchy for a
2432 // virtual base class.
2433 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2434 /*DetectVirtual=*/false);
2435 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2436 BaseType, Paths)) {
2437 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2438 Path != Paths.end(); ++Path) {
2439 if (Path->back().Base->isVirtual()) {
2440 VirtualBaseSpec = Path->back().Base;
2441 break;
2442 }
2443 }
2444 }
2445 }
2446
2447 return DirectBaseSpec || VirtualBaseSpec;
2448}
2449
Sebastian Redla74948d2011-09-24 17:48:25 +00002450/// \brief Handle a C++ member initializer using braced-init-list syntax.
2451MemInitResult
2452Sema::ActOnMemInitializer(Decl *ConstructorD,
2453 Scope *S,
2454 CXXScopeSpec &SS,
2455 IdentifierInfo *MemberOrBase,
2456 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002457 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002458 SourceLocation IdLoc,
2459 Expr *InitList,
2460 SourceLocation EllipsisLoc) {
2461 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002462 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002463 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002464}
2465
2466/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002467MemInitResult
John McCall48871652010-08-21 09:40:31 +00002468Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002469 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002470 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002471 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002472 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002473 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002474 SourceLocation IdLoc,
2475 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002476 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002477 SourceLocation RParenLoc,
2478 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002479 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002480 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002481 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002482 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002483}
2484
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002485namespace {
2486
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002487// Callback to only accept typo corrections that can be a valid C++ member
2488// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002489class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002490public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002491 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2492 : ClassDecl(ClassDecl) {}
2493
Craig Toppera798a9d2014-03-02 09:32:10 +00002494 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002495 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2496 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2497 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002498 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002499 }
2500 return false;
2501 }
2502
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002503private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002504 CXXRecordDecl *ClassDecl;
2505};
2506
2507}
2508
Sebastian Redla74948d2011-09-24 17:48:25 +00002509/// \brief Handle a C++ member initializer.
2510MemInitResult
2511Sema::BuildMemInitializer(Decl *ConstructorD,
2512 Scope *S,
2513 CXXScopeSpec &SS,
2514 IdentifierInfo *MemberOrBase,
2515 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002516 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002517 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002518 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002519 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002520 if (!ConstructorD)
2521 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002522
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002523 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002524
2525 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002526 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002527 if (!Constructor) {
2528 // The user wrote a constructor initializer on a function that is
2529 // not a C++ constructor. Ignore the error for now, because we may
2530 // have more member initializers coming; we'll diagnose it just
2531 // once in ActOnMemInitializers.
2532 return true;
2533 }
2534
2535 CXXRecordDecl *ClassDecl = Constructor->getParent();
2536
2537 // C++ [class.base.init]p2:
2538 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002539 // constructor's class and, if not found in that scope, are looked
2540 // up in the scope containing the constructor's definition.
2541 // [Note: if the constructor's class contains a member with the
2542 // same name as a direct or virtual base class of the class, a
2543 // mem-initializer-id naming the member or base class and composed
2544 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002545 // mem-initializer-id for the hidden base class may be specified
2546 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002547 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002548 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002549 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002550 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002551 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002552 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002553 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2554 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002555 if (EllipsisLoc.isValid())
2556 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002557 << MemberOrBase
2558 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002559
Sebastian Redla9351792012-02-11 23:51:47 +00002560 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002561 }
Francois Pichetd583da02010-12-04 09:14:42 +00002562 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002563 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002564 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002565 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002566 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002567
2568 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002569 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002570 } else if (DS.getTypeSpecType() == TST_decltype) {
2571 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002572 } else {
2573 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2574 LookupParsedName(R, S, &SS);
2575
2576 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2577 if (!TyD) {
2578 if (R.isAmbiguous()) return true;
2579
John McCallda6841b2010-04-09 19:01:14 +00002580 // We don't want access-control diagnostics here.
2581 R.suppressDiagnostics();
2582
Douglas Gregora3b624a2010-01-19 06:46:48 +00002583 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2584 bool NotUnknownSpecialization = false;
2585 DeclContext *DC = computeDeclContext(SS, false);
2586 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2587 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2588
2589 if (!NotUnknownSpecialization) {
2590 // When the scope specifier can refer to a member of an unknown
2591 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002592 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2593 SS.getWithLocInContext(Context),
2594 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002595 if (BaseType.isNull())
2596 return true;
2597
Douglas Gregora3b624a2010-01-19 06:46:48 +00002598 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002599 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002600 }
2601 }
2602
Douglas Gregor15e77a22009-12-31 09:10:24 +00002603 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002604 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002605 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002606 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002607 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00002608 Validator, CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002609 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002610 // We have found a non-static data member with a similar
2611 // name to what was typed; complain and initialize that
2612 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002613 diagnoseTypo(Corr,
2614 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2615 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002616 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002617 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002618 const CXXBaseSpecifier *DirectBaseSpec;
2619 const CXXBaseSpecifier *VirtualBaseSpec;
2620 if (FindBaseInitializer(*this, ClassDecl,
2621 Context.getTypeDeclType(Type),
2622 DirectBaseSpec, VirtualBaseSpec)) {
2623 // We have found a direct or virtual base class with a
2624 // similar name to what was typed; complain and initialize
2625 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002626 diagnoseTypo(Corr,
2627 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2628 << MemberOrBase << false,
2629 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002630
Richard Smithf9b15102013-08-17 00:46:16 +00002631 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2632 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002633 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002634 diag::note_base_class_specified_here)
2635 << BaseSpec->getType()
2636 << BaseSpec->getSourceRange();
2637
Douglas Gregor15e77a22009-12-31 09:10:24 +00002638 TyD = Type;
2639 }
2640 }
2641 }
2642
Douglas Gregora3b624a2010-01-19 06:46:48 +00002643 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002644 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002645 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002646 return true;
2647 }
John McCallb5a0d312009-12-21 10:41:20 +00002648 }
2649
Douglas Gregora3b624a2010-01-19 06:46:48 +00002650 if (BaseType.isNull()) {
2651 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002652 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002653 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002654 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2655 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002656 }
2657 }
Mike Stump11289f42009-09-09 15:08:12 +00002658
John McCallbcd03502009-12-07 02:54:59 +00002659 if (!TInfo)
2660 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002661
Sebastian Redla9351792012-02-11 23:51:47 +00002662 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002663}
2664
Chandler Carruth599deef2011-09-03 01:14:15 +00002665/// Checks a member initializer expression for cases where reference (or
2666/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002667static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2668 Expr *Init,
2669 SourceLocation IdLoc) {
2670 QualType MemberTy = Member->getType();
2671
2672 // We only handle pointers and references currently.
2673 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2674 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2675 return;
2676
2677 const bool IsPointer = MemberTy->isPointerType();
2678 if (IsPointer) {
2679 if (const UnaryOperator *Op
2680 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2681 // The only case we're worried about with pointers requires taking the
2682 // address.
2683 if (Op->getOpcode() != UO_AddrOf)
2684 return;
2685
2686 Init = Op->getSubExpr();
2687 } else {
2688 // We only handle address-of expression initializers for pointers.
2689 return;
2690 }
2691 }
2692
Richard Smithe3b28bc2013-06-12 21:51:50 +00002693 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002694 // We only warn when referring to a non-reference parameter declaration.
2695 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2696 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002697 return;
2698
2699 S.Diag(Init->getExprLoc(),
2700 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2701 : diag::warn_bind_ref_member_to_parameter)
2702 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002703 } else {
2704 // Other initializers are fine.
2705 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002706 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002707
2708 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2709 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002710}
2711
John McCallfaf5fb42010-08-26 23:41:50 +00002712MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002713Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002714 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002715 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2716 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2717 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002718 "Member must be a FieldDecl or IndirectFieldDecl");
2719
Sebastian Redla9351792012-02-11 23:51:47 +00002720 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002721 return true;
2722
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002723 if (Member->isInvalidDecl())
2724 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002725
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002726 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002727 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002728 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002729 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002730 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002731 } else {
2732 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002733 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002734 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002735
Sebastian Redla9351792012-02-11 23:51:47 +00002736 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002737
Sebastian Redla9351792012-02-11 23:51:47 +00002738 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002739 // Can't check initialization for a member of dependent type or when
2740 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002741 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002742 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002743 bool InitList = false;
2744 if (isa<InitListExpr>(Init)) {
2745 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002746 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002747 }
2748
Chandler Carruthd44c3102010-12-06 09:23:57 +00002749 // Initialize the member.
2750 InitializedEntity MemberEntity =
2751 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2752 : InitializedEntity::InitializeMember(IndirectMember, 0);
2753 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002754 InitList ? InitializationKind::CreateDirectList(IdLoc)
2755 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2756 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002757
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002758 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2759 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002760 if (MemberInit.isInvalid())
2761 return true;
2762
Richard Smith736a9472013-06-12 20:42:33 +00002763 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2764
Richard Smith945f8d32013-01-14 22:39:08 +00002765 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002766 // The initialization of each base and member constitutes a
2767 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002768 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002769 if (MemberInit.isInvalid())
2770 return true;
2771
Richard Smithd59b8322012-12-19 01:39:02 +00002772 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002773 }
2774
Chandler Carruthd44c3102010-12-06 09:23:57 +00002775 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002776 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2777 InitRange.getBegin(), Init,
2778 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002779 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002780 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2781 InitRange.getBegin(), Init,
2782 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002783 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002784}
2785
John McCallfaf5fb42010-08-26 23:41:50 +00002786MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002787Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002788 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002789 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002790 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002791 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002792 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002793 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002794
Sebastian Redl0501c632012-02-12 16:37:36 +00002795 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002796 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002797 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2798 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002799 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002800 }
2801
Sebastian Redla9351792012-02-11 23:51:47 +00002802 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002803 // Initialize the object.
2804 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2805 QualType(ClassDecl->getTypeForDecl(), 0));
2806 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002807 InitList ? InitializationKind::CreateDirectList(NameLoc)
2808 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2809 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002810 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002811 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002812 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002813 if (DelegationInit.isInvalid())
2814 return true;
2815
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002816 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2817 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002818
Richard Smith945f8d32013-01-14 22:39:08 +00002819 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002820 // The initialization of each base and member constitutes a
2821 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002822 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2823 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002824 if (DelegationInit.isInvalid())
2825 return true;
2826
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002827 // If we are in a dependent context, template instantiation will
2828 // perform this type-checking again. Just save the arguments that we
2829 // received in a ParenListExpr.
2830 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2831 // of the information that we have about the base
2832 // initializer. However, deconstructing the ASTs is a dicey process,
2833 // and this approach is far more likely to get the corner cases right.
2834 if (CurContext->isDependentContext())
2835 DelegationInit = Owned(Init);
2836
Sebastian Redla9351792012-02-11 23:51:47 +00002837 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002838 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002839 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002840}
2841
2842MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002843Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002844 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002845 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002846 SourceLocation BaseLoc
2847 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002848
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002849 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2850 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2851 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2852
2853 // C++ [class.base.init]p2:
2854 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002855 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002856 // of that class, the mem-initializer is ill-formed. A
2857 // mem-initializer-list can initialize a base class using any
2858 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002859 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002860
Sebastian Redla9351792012-02-11 23:51:47 +00002861 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002862 if (EllipsisLoc.isValid()) {
2863 // This is a pack expansion.
2864 if (!BaseType->containsUnexpandedParameterPack()) {
2865 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002866 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002867
Douglas Gregor44e7df62011-01-04 00:32:56 +00002868 EllipsisLoc = SourceLocation();
2869 }
2870 } else {
2871 // Check for any unexpanded parameter packs.
2872 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2873 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002874
Sebastian Redla9351792012-02-11 23:51:47 +00002875 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002876 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002877 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002878
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002879 // Check for direct and virtual base classes.
2880 const CXXBaseSpecifier *DirectBaseSpec = 0;
2881 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2882 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002883 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2884 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002885 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002886
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002887 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2888 VirtualBaseSpec);
2889
2890 // C++ [base.class.init]p2:
2891 // Unless the mem-initializer-id names a nonstatic data member of the
2892 // constructor's class or a direct or virtual base of that class, the
2893 // mem-initializer is ill-formed.
2894 if (!DirectBaseSpec && !VirtualBaseSpec) {
2895 // If the class has any dependent bases, then it's possible that
2896 // one of those types will resolve to the same type as
2897 // BaseType. Therefore, just treat this as a dependent base
2898 // class initialization. FIXME: Should we try to check the
2899 // initialization anyway? It seems odd.
2900 if (ClassDecl->hasAnyDependentBases())
2901 Dependent = true;
2902 else
2903 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2904 << BaseType << Context.getTypeDeclType(ClassDecl)
2905 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2906 }
2907 }
2908
2909 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002910 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002911
Sebastian Redla74948d2011-09-24 17:48:25 +00002912 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2913 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002914 InitRange.getBegin(), Init,
2915 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002916 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002917
2918 // C++ [base.class.init]p2:
2919 // If a mem-initializer-id is ambiguous because it designates both
2920 // a direct non-virtual base class and an inherited virtual base
2921 // class, the mem-initializer is ill-formed.
2922 if (DirectBaseSpec && VirtualBaseSpec)
2923 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002924 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002925
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002926 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002927 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002928 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002929
2930 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002931 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002932 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002933 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002934 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002935 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002936 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002937
2938 InitializedEntity BaseEntity =
2939 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2940 InitializationKind Kind =
2941 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2942 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2943 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002944 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2945 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002946 if (BaseInit.isInvalid())
2947 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002948
Richard Smith945f8d32013-01-14 22:39:08 +00002949 // C++11 [class.base.init]p7:
2950 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002951 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002952 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002953 if (BaseInit.isInvalid())
2954 return true;
2955
2956 // If we are in a dependent context, template instantiation will
2957 // perform this type-checking again. Just save the arguments that we
2958 // received in a ParenListExpr.
2959 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2960 // of the information that we have about the base
2961 // initializer. However, deconstructing the ASTs is a dicey process,
2962 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002963 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002964 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002965
Alexis Hunt1d792652011-01-08 20:30:50 +00002966 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002967 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002968 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002969 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002970 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002971}
2972
Sebastian Redl22653ba2011-08-30 19:58:05 +00002973// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002974static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2975 if (T.isNull()) T = E->getType();
2976 QualType TargetType = SemaRef.BuildReferenceType(
2977 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002978 SourceLocation ExprLoc = E->getLocStart();
2979 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2980 TargetType, ExprLoc);
2981
2982 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2983 SourceRange(ExprLoc, ExprLoc),
2984 E->getSourceRange()).take();
2985}
2986
Anders Carlsson1b00e242010-04-23 03:10:23 +00002987/// ImplicitInitializerKind - How an implicit base or member initializer should
2988/// initialize its base or member.
2989enum ImplicitInitializerKind {
2990 IIK_Default,
2991 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002992 IIK_Move,
2993 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002994};
2995
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002996static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002997BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002998 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002999 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003000 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003001 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003002 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003003 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3004 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003005
John McCalldadc5752010-08-24 06:29:42 +00003006 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003007
3008 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003009 case IIK_Inherit: {
3010 const CXXRecordDecl *Inherited =
3011 Constructor->getInheritedConstructor()->getParent();
3012 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3013 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3014 // C++11 [class.inhctor]p8:
3015 // Each expression in the expression-list is of the form
3016 // static_cast<T&&>(p), where p is the name of the corresponding
3017 // constructor parameter and T is the declared type of p.
3018 SmallVector<Expr*, 16> Args;
3019 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3020 ParmVarDecl *PD = Constructor->getParamDecl(I);
3021 ExprResult ArgExpr =
3022 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3023 VK_LValue, SourceLocation());
3024 if (ArgExpr.isInvalid())
3025 return true;
3026 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3027 }
3028
3029 InitializationKind InitKind = InitializationKind::CreateDirect(
3030 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003031 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003032 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3033 break;
3034 }
3035 }
3036 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003037 case IIK_Default: {
3038 InitializationKind InitKind
3039 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003040 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3041 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003042 break;
3043 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003044
Sebastian Redl22653ba2011-08-30 19:58:05 +00003045 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003046 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003047 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003048 ParmVarDecl *Param = Constructor->getParamDecl(0);
3049 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003050
Anders Carlsson1b00e242010-04-23 03:10:23 +00003051 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003052 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003053 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003054 Constructor->getLocation(), ParamType,
3055 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003056
Eli Friedmanfa0df832012-02-02 03:46:19 +00003057 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3058
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003059 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003060 QualType ArgTy =
3061 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3062 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003063
Sebastian Redl22653ba2011-08-30 19:58:05 +00003064 if (Moving) {
3065 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3066 }
3067
John McCallcf142162010-08-07 06:22:56 +00003068 CXXCastPath BasePath;
3069 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003070 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3071 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003072 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003073 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003074
Anders Carlsson1b00e242010-04-23 03:10:23 +00003075 InitializationKind InitKind
3076 = InitializationKind::CreateDirect(Constructor->getLocation(),
3077 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003078 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3079 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003080 break;
3081 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003082 }
John McCallb268a282010-08-23 23:25:46 +00003083
Douglas Gregora40433a2010-12-07 00:41:46 +00003084 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003085 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003086 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003087
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003088 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003089 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003090 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3091 SourceLocation()),
3092 BaseSpec->isVirtual(),
3093 SourceLocation(),
3094 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003095 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003096 SourceLocation());
3097
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003098 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003099}
3100
Sebastian Redl22653ba2011-08-30 19:58:05 +00003101static bool RefersToRValueRef(Expr *MemRef) {
3102 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3103 return Referenced->getType()->isRValueReferenceType();
3104}
3105
Anders Carlsson3c1db572010-04-23 02:15:47 +00003106static bool
3107BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003108 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003109 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003110 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003111 if (Field->isInvalidDecl())
3112 return true;
3113
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003114 SourceLocation Loc = Constructor->getLocation();
3115
Sebastian Redl22653ba2011-08-30 19:58:05 +00003116 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3117 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003118 ParmVarDecl *Param = Constructor->getParamDecl(0);
3119 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003120
3121 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003122 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3123 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003124
Anders Carlsson423f5d82010-04-23 16:04:08 +00003125 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003126 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003127 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003128 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003129
Eli Friedmanfa0df832012-02-02 03:46:19 +00003130 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3131
Sebastian Redl22653ba2011-08-30 19:58:05 +00003132 if (Moving) {
3133 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3134 }
3135
Douglas Gregor94f9a482010-05-05 05:51:00 +00003136 // Build a reference to this field within the parameter.
3137 CXXScopeSpec SS;
3138 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3139 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003140 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3141 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003142 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003143 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003144 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003145 ParamType, Loc,
3146 /*IsArrow=*/false,
3147 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003148 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00003149 /*FirstQualifierInScope=*/0,
3150 MemberLookup,
3151 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003152 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003153 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003154
3155 // C++11 [class.copy]p15:
3156 // - if a member m has rvalue reference type T&&, it is direct-initialized
3157 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003158 if (RefersToRValueRef(CtorArg.get())) {
3159 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003160 }
3161
Douglas Gregor94f9a482010-05-05 05:51:00 +00003162 // When the field we are copying is an array, create index variables for
3163 // each dimension of the array. We use these index variables to subscript
3164 // the source array, and other clients (e.g., CodeGen) will perform the
3165 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003166 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003167 QualType BaseType = Field->getType();
3168 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003169 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003170 while (const ConstantArrayType *Array
3171 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003172 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003173 // Create the iteration variable for this array index.
3174 IdentifierInfo *IterationVarName = 0;
3175 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003176 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003177 llvm::raw_svector_ostream OS(Str);
3178 OS << "__i" << IndexVariables.size();
3179 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3180 }
3181 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003182 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003183 IterationVarName, SizeType,
3184 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003185 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003186 IndexVariables.push_back(IterationVar);
3187
3188 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003189 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003190 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003191 assert(!IterationVarRef.isInvalid() &&
3192 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003193 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3194 assert(!IterationVarRef.isInvalid() &&
3195 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003196
Douglas Gregor94f9a482010-05-05 05:51:00 +00003197 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003198 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003199 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003200 Loc);
3201 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003202 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003203
Douglas Gregor94f9a482010-05-05 05:51:00 +00003204 BaseType = Array->getElementType();
3205 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003206
3207 // The array subscript expression is an lvalue, which is wrong for moving.
3208 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003209 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003210
Douglas Gregor94f9a482010-05-05 05:51:00 +00003211 // Construct the entity that we will be initializing. For an array, this
3212 // will be first element in the array, which may require several levels
3213 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003214 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003215 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003216 if (Indirect)
3217 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3218 else
3219 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003220 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3221 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3222 0,
3223 Entities.back()));
3224
3225 // Direct-initialize to use the copy constructor.
3226 InitializationKind InitKind =
3227 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3228
Sebastian Redle9c4e842011-09-04 18:14:28 +00003229 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003230 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003231
John McCalldadc5752010-08-24 06:29:42 +00003232 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003233 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003234 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003235 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003236 if (MemberInit.isInvalid())
3237 return true;
3238
Douglas Gregor493627b2011-08-10 15:22:55 +00003239 if (Indirect) {
3240 assert(IndexVariables.size() == 0 &&
3241 "Indirect field improperly initialized");
3242 CXXMemberInit
3243 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3244 Loc, Loc,
3245 MemberInit.takeAs<Expr>(),
3246 Loc);
3247 } else
3248 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3249 Loc, MemberInit.takeAs<Expr>(),
3250 Loc,
3251 IndexVariables.data(),
3252 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003253 return false;
3254 }
3255
Richard Smithc2bc61b2013-03-18 21:12:30 +00003256 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3257 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003258
Anders Carlsson3c1db572010-04-23 02:15:47 +00003259 QualType FieldBaseElementType =
3260 SemaRef.Context.getBaseElementType(Field->getType());
3261
Anders Carlsson3c1db572010-04-23 02:15:47 +00003262 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003263 InitializedEntity InitEntity
3264 = Indirect? InitializedEntity::InitializeMember(Indirect)
3265 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003266 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003267 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003268
3269 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3270 ExprResult MemberInit =
3271 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003272
Douglas Gregora40433a2010-12-07 00:41:46 +00003273 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003274 if (MemberInit.isInvalid())
3275 return true;
3276
Douglas Gregor493627b2011-08-10 15:22:55 +00003277 if (Indirect)
3278 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3279 Indirect, Loc,
3280 Loc,
3281 MemberInit.get(),
3282 Loc);
3283 else
3284 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3285 Field, Loc, Loc,
3286 MemberInit.get(),
3287 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003288 return false;
3289 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003290
Alexis Hunt8b455182011-05-17 00:19:05 +00003291 if (!Field->getParent()->isUnion()) {
3292 if (FieldBaseElementType->isReferenceType()) {
3293 SemaRef.Diag(Constructor->getLocation(),
3294 diag::err_uninitialized_member_in_ctor)
3295 << (int)Constructor->isImplicit()
3296 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3297 << 0 << Field->getDeclName();
3298 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3299 return true;
3300 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003301
Alexis Hunt8b455182011-05-17 00:19:05 +00003302 if (FieldBaseElementType.isConstQualified()) {
3303 SemaRef.Diag(Constructor->getLocation(),
3304 diag::err_uninitialized_member_in_ctor)
3305 << (int)Constructor->isImplicit()
3306 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3307 << 1 << Field->getDeclName();
3308 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3309 return true;
3310 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003311 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003312
David Blaikiebbafb8a2012-03-11 07:00:24 +00003313 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003314 FieldBaseElementType->isObjCRetainableType() &&
3315 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3316 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003317 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003318 // Default-initialize Objective-C pointers to NULL.
3319 CXXMemberInit
3320 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3321 Loc, Loc,
3322 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3323 Loc);
3324 return false;
3325 }
3326
Anders Carlsson3c1db572010-04-23 02:15:47 +00003327 // Nothing to initialize.
3328 CXXMemberInit = 0;
3329 return false;
3330}
John McCallbc83b3f2010-05-20 23:23:51 +00003331
3332namespace {
3333struct BaseAndFieldInfo {
3334 Sema &S;
3335 CXXConstructorDecl *Ctor;
3336 bool AnyErrorsInInits;
3337 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003338 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003339 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003340 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003341
3342 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3343 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003344 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3345 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003346 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003347 else if (Generated && Ctor->isMoveConstructor())
3348 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003349 else if (Ctor->getInheritedConstructor())
3350 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003351 else
3352 IIK = IIK_Default;
3353 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003354
3355 bool isImplicitCopyOrMove() const {
3356 switch (IIK) {
3357 case IIK_Copy:
3358 case IIK_Move:
3359 return true;
3360
3361 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003362 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003363 return false;
3364 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003365
3366 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003367 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003368
3369 bool addFieldInitializer(CXXCtorInitializer *Init) {
3370 AllToInit.push_back(Init);
3371
3372 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003373 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003374 S.UnusedPrivateFields.remove(Init->getAnyMember());
3375
3376 return false;
3377 }
John McCallbc83b3f2010-05-20 23:23:51 +00003378
Richard Smithab44d5b2013-12-10 08:25:00 +00003379 bool isInactiveUnionMember(FieldDecl *Field) {
3380 RecordDecl *Record = Field->getParent();
3381 if (!Record->isUnion())
3382 return false;
3383
Richard Smith8d183852013-12-10 20:56:03 +00003384 if (FieldDecl *Active =
3385 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003386 return Active != Field->getCanonicalDecl();
3387
3388 // In an implicit copy or move constructor, ignore any in-class initializer.
3389 if (isImplicitCopyOrMove())
3390 return true;
3391
3392 // If there's no explicit initialization, the field is active only if it
3393 // has an in-class initializer...
3394 if (Field->hasInClassInitializer())
3395 return false;
3396 // ... or it's an anonymous struct or union whose class has an in-class
3397 // initializer.
3398 if (!Field->isAnonymousStructOrUnion())
3399 return true;
3400 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3401 return !FieldRD->hasInClassInitializer();
3402 }
3403
3404 /// \brief Determine whether the given field is, or is within, a union member
3405 /// that is inactive (because there was an initializer given for a different
3406 /// member of the union, or because the union was not initialized at all).
3407 bool isWithinInactiveUnionMember(FieldDecl *Field,
3408 IndirectFieldDecl *Indirect) {
3409 if (!Indirect)
3410 return isInactiveUnionMember(Field);
3411
Aaron Ballman29c94602014-03-07 18:36:15 +00003412 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003413 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003414 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003415 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003416 }
3417 return false;
3418 }
3419};
Richard Smithc94ec842011-09-19 13:34:43 +00003420}
3421
Douglas Gregor10f939c2011-11-02 23:04:16 +00003422/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3423/// array type.
3424static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3425 if (T->isIncompleteArrayType())
3426 return true;
3427
3428 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3429 if (!ArrayT->getSize())
3430 return true;
3431
3432 T = ArrayT->getElementType();
3433 }
3434
3435 return false;
3436}
3437
Richard Smith938f40b2011-06-11 17:19:42 +00003438static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003439 FieldDecl *Field,
3440 IndirectFieldDecl *Indirect = 0) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003441 if (Field->isInvalidDecl())
3442 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003443
Chandler Carruth139e9622010-06-30 02:59:29 +00003444 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003445 if (CXXCtorInitializer *Init =
3446 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003447 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003448
Richard Smithab44d5b2013-12-10 08:25:00 +00003449 // C++11 [class.base.init]p8:
3450 // if the entity is a non-static data member that has a
3451 // brace-or-equal-initializer and either
3452 // -- the constructor's class is a union and no other variant member of that
3453 // union is designated by a mem-initializer-id or
3454 // -- the constructor's class is not a union, and, if the entity is a member
3455 // of an anonymous union, no other member of that union is designated by
3456 // a mem-initializer-id,
3457 // the entity is initialized as specified in [dcl.init].
3458 //
3459 // We also apply the same rules to handle anonymous structs within anonymous
3460 // unions.
3461 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3462 return false;
3463
Douglas Gregor7db3e952011-11-28 20:03:15 +00003464 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003465 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3466 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003467 CXXCtorInitializer *Init;
3468 if (Indirect)
3469 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3470 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003471 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003472 SourceLocation());
3473 else
3474 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3475 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003476 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003477 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003478 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003479 }
3480
Douglas Gregor10f939c2011-11-02 23:04:16 +00003481 // Don't initialize incomplete or zero-length arrays.
3482 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3483 return false;
3484
John McCallbc83b3f2010-05-20 23:23:51 +00003485 // Don't try to build an implicit initializer if there were semantic
3486 // errors in any of the initializers (and therefore we might be
3487 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003488 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003489 return false;
3490
Alexis Hunt1d792652011-01-08 20:30:50 +00003491 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003492 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3493 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003494 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003495
Richard Smith0a8cfc72012-08-07 21:30:42 +00003496 if (!Init)
3497 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003498
Richard Smith0a8cfc72012-08-07 21:30:42 +00003499 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003500}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003501
3502bool
3503Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3504 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003505 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003506 Constructor->setNumCtorInitializers(1);
3507 CXXCtorInitializer **initializer =
3508 new (Context) CXXCtorInitializer*[1];
3509 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3510 Constructor->setCtorInitializers(initializer);
3511
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003512 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003513 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003514 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3515 }
3516
Alexis Hunte2622992011-05-05 00:05:47 +00003517 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003518
Alexis Hunt61bc1732011-05-01 07:04:31 +00003519 return false;
3520}
Douglas Gregor493627b2011-08-10 15:22:55 +00003521
David Blaikie3fc2f912013-01-17 05:26:25 +00003522bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3523 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003524 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003525 // Just store the initializers as written, they will be checked during
3526 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003527 if (!Initializers.empty()) {
3528 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003529 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003530 new (Context) CXXCtorInitializer*[Initializers.size()];
3531 memcpy(baseOrMemberInitializers, Initializers.data(),
3532 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003533 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003534 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003535
3536 // Let template instantiation know whether we had errors.
3537 if (AnyErrors)
3538 Constructor->setInvalidDecl();
3539
Anders Carlssondb0a9652010-04-02 06:26:44 +00003540 return false;
3541 }
3542
John McCallbc83b3f2010-05-20 23:23:51 +00003543 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003544
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003545 // We need to build the initializer AST according to order of construction
3546 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003547 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003548 if (!ClassDecl)
3549 return true;
3550
Eli Friedman9cf6b592009-11-09 19:20:36 +00003551 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003552
David Blaikie3fc2f912013-01-17 05:26:25 +00003553 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003554 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003555
Anders Carlssondb0a9652010-04-02 06:26:44 +00003556 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003557 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003558 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003559 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003560
3561 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003562 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003563 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003564 if (FD && FD->getParent()->isUnion())
3565 Info.ActiveUnionMember.insert(std::make_pair(
3566 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3567 }
3568 } else if (FieldDecl *FD = Member->getMember()) {
3569 if (FD->getParent()->isUnion())
3570 Info.ActiveUnionMember.insert(std::make_pair(
3571 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3572 }
3573 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003574 }
3575
Anders Carlsson43c64af2010-04-21 19:52:01 +00003576 // Keep track of the direct virtual bases.
3577 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003578 for (auto &I : ClassDecl->bases()) {
3579 if (I.isVirtual())
3580 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003581 }
3582
Anders Carlssondb0a9652010-04-02 06:26:44 +00003583 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003584 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003585 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003586 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003587 // [class.base.init]p7, per DR257:
3588 // A mem-initializer where the mem-initializer-id names a virtual base
3589 // class is ignored during execution of a constructor of any class that
3590 // is not the most derived class.
3591 if (ClassDecl->isAbstract()) {
3592 // FIXME: Provide a fixit to remove the base specifier. This requires
3593 // tracking the location of the associated comma for a base specifier.
3594 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003595 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003596 DiagnoseAbstractType(ClassDecl);
3597 }
3598
John McCallbc83b3f2010-05-20 23:23:51 +00003599 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003600 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3601 // [class.base.init]p8, per DR257:
3602 // If a given [...] base class is not named by a mem-initializer-id
3603 // [...] and the entity is not a virtual base class of an abstract
3604 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003605 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003606 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003607 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003608 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003609 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003610 HadError = true;
3611 continue;
3612 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003613
John McCallbc83b3f2010-05-20 23:23:51 +00003614 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003615 }
3616 }
Mike Stump11289f42009-09-09 15:08:12 +00003617
John McCallbc83b3f2010-05-20 23:23:51 +00003618 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003619 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003620 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003621 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003622 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003623
Alexis Hunt1d792652011-01-08 20:30:50 +00003624 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003625 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003626 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003627 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003628 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003629 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003630 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003631 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003632 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003633 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003634 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003635
John McCallbc83b3f2010-05-20 23:23:51 +00003636 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003637 }
3638 }
Mike Stump11289f42009-09-09 15:08:12 +00003639
John McCallbc83b3f2010-05-20 23:23:51 +00003640 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003641 for (auto *Mem : ClassDecl->decls()) {
3642 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003643 // C++ [class.bit]p2:
3644 // A declaration for a bit-field that omits the identifier declares an
3645 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3646 // initialized.
3647 if (F->isUnnamedBitfield())
3648 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003649
Sebastian Redl22653ba2011-08-30 19:58:05 +00003650 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003651 // handle anonymous struct/union fields based on their individual
3652 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003653 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003654 continue;
3655
3656 if (CollectFieldInitializer(*this, Info, F))
3657 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003658 continue;
3659 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003660
3661 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003662 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003663 continue;
3664
Aaron Ballman629afae2014-03-07 19:56:05 +00003665 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003666 if (F->getType()->isIncompleteArrayType()) {
3667 assert(ClassDecl->hasFlexibleArrayMember() &&
3668 "Incomplete array type is not valid");
3669 continue;
3670 }
3671
Douglas Gregor493627b2011-08-10 15:22:55 +00003672 // Initialize each field of an anonymous struct individually.
3673 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3674 HadError = true;
3675
3676 continue;
3677 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003678 }
Mike Stump11289f42009-09-09 15:08:12 +00003679
David Blaikie3fc2f912013-01-17 05:26:25 +00003680 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003681 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003682 Constructor->setNumCtorInitializers(NumInitializers);
3683 CXXCtorInitializer **baseOrMemberInitializers =
3684 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003685 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003686 NumInitializers * sizeof(CXXCtorInitializer*));
3687 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003688
John McCalla6309952010-03-16 21:39:52 +00003689 // Constructors implicitly reference the base and member
3690 // destructors.
3691 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3692 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003693 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003694
3695 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003696}
3697
David Blaikieb61b8152013-01-17 08:49:22 +00003698static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003699 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003700 const RecordDecl *RD = RT->getDecl();
3701 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003702 for (auto *Field : RD->fields())
3703 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003704 return;
3705 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003706 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003707 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00003708}
3709
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003710static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3711 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003712}
3713
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003714static const void *GetKeyForMember(ASTContext &Context,
3715 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003716 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003717 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003718
Richard Smithcd45dbc2014-04-19 03:48:30 +00003719 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00003720}
3721
David Blaikie3fc2f912013-01-17 05:26:25 +00003722static void DiagnoseBaseOrMemInitializerOrder(
3723 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3724 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003725 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003726 return;
Mike Stump11289f42009-09-09 15:08:12 +00003727
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003728 // Don't check initializers order unless the warning is enabled at the
3729 // location of at least one initializer.
3730 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003731 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003732 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003733 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3734 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003735 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003736 ShouldCheckOrder = true;
3737 break;
3738 }
3739 }
3740 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003741 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003742
John McCallbb7b6582010-04-10 07:37:23 +00003743 // Build the list of bases and members in the order that they'll
3744 // actually be initialized. The explicit initializers should be in
3745 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003746 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003747
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003748 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3749
John McCallbb7b6582010-04-10 07:37:23 +00003750 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003751 for (const auto &VBase : ClassDecl->vbases())
3752 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003753
John McCallbb7b6582010-04-10 07:37:23 +00003754 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003755 for (const auto &Base : ClassDecl->bases()) {
3756 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003757 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003758 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003759 }
Mike Stump11289f42009-09-09 15:08:12 +00003760
John McCallbb7b6582010-04-10 07:37:23 +00003761 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003762 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003763 if (Field->isUnnamedBitfield())
3764 continue;
3765
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003766 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003767 }
3768
John McCallbb7b6582010-04-10 07:37:23 +00003769 unsigned NumIdealInits = IdealInitKeys.size();
3770 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003771
Alexis Hunt1d792652011-01-08 20:30:50 +00003772 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003773 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003774 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003775 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003776
3777 // Scan forward to try to find this initializer in the idealized
3778 // initializers list.
3779 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3780 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003781 break;
John McCallbb7b6582010-04-10 07:37:23 +00003782
3783 // If we didn't find this initializer, it must be because we
3784 // scanned past it on a previous iteration. That can only
3785 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003786 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003787 Sema::SemaDiagnosticBuilder D =
3788 SemaRef.Diag(PrevInit->getSourceLocation(),
3789 diag::warn_initializer_out_of_order);
3790
Francois Pichetd583da02010-12-04 09:14:42 +00003791 if (PrevInit->isAnyMemberInitializer())
3792 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003793 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003794 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003795
Francois Pichetd583da02010-12-04 09:14:42 +00003796 if (Init->isAnyMemberInitializer())
3797 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003798 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003799 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003800
3801 // Move back to the initializer's location in the ideal list.
3802 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3803 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003804 break;
John McCallbb7b6582010-04-10 07:37:23 +00003805
3806 assert(IdealIndex != NumIdealInits &&
3807 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003808 }
John McCallbb7b6582010-04-10 07:37:23 +00003809
3810 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003811 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003812}
3813
John McCall23eebd92010-04-10 09:28:51 +00003814namespace {
3815bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003816 CXXCtorInitializer *Init,
3817 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003818 if (!PrevInit) {
3819 PrevInit = Init;
3820 return false;
3821 }
3822
Douglas Gregorea306a12013-03-25 23:28:23 +00003823 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003824 S.Diag(Init->getSourceLocation(),
3825 diag::err_multiple_mem_initialization)
3826 << Field->getDeclName()
3827 << Init->getSourceRange();
3828 else {
John McCall424cec92011-01-19 06:33:43 +00003829 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003830 assert(BaseClass && "neither field nor base");
3831 S.Diag(Init->getSourceLocation(),
3832 diag::err_multiple_base_initialization)
3833 << QualType(BaseClass, 0)
3834 << Init->getSourceRange();
3835 }
3836 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3837 << 0 << PrevInit->getSourceRange();
3838
3839 return true;
3840}
3841
Alexis Hunt1d792652011-01-08 20:30:50 +00003842typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003843typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3844
3845bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003846 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003847 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003848 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003849 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003850 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003851
3852 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003853 if (Parent->isUnion()) {
3854 UnionEntry &En = Unions[Parent];
3855 if (En.first && En.first != Child) {
3856 S.Diag(Init->getSourceLocation(),
3857 diag::err_multiple_mem_union_initialization)
3858 << Field->getDeclName()
3859 << Init->getSourceRange();
3860 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3861 << 0 << En.second->getSourceRange();
3862 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003863 }
3864 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003865 En.first = Child;
3866 En.second = Init;
3867 }
David Blaikie0f65d592011-11-17 06:01:57 +00003868 if (!Parent->isAnonymousStructOrUnion())
3869 return false;
John McCall23eebd92010-04-10 09:28:51 +00003870 }
3871
3872 Child = Parent;
3873 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003874 }
John McCall23eebd92010-04-10 09:28:51 +00003875
3876 return false;
3877}
3878}
3879
Anders Carlssone857b292010-04-02 03:37:03 +00003880/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003881void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003882 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003883 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003884 bool AnyErrors) {
3885 if (!ConstructorDecl)
3886 return;
3887
3888 AdjustDeclIfTemplate(ConstructorDecl);
3889
3890 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003891 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003892
3893 if (!Constructor) {
3894 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3895 return;
3896 }
3897
John McCall23eebd92010-04-10 09:28:51 +00003898 // Mapping for the duplicate initializers check.
3899 // For member initializers, this is keyed with a FieldDecl*.
3900 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003901 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003902
3903 // Mapping for the inconsistent anonymous-union initializers check.
3904 RedundantUnionMap MemberUnions;
3905
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003906 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003907 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003908 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003909
Abramo Bagnara341d7832010-05-26 18:09:23 +00003910 // Set the source order index.
3911 Init->setSourceOrder(i);
3912
Francois Pichetd583da02010-12-04 09:14:42 +00003913 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003914 const void *Key = GetKeyForMember(Context, Init);
3915 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00003916 CheckRedundantUnionInit(*this, Init, MemberUnions))
3917 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003918 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003919 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00003920 if (CheckRedundantInit(*this, Init, Members[Key]))
3921 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003922 } else {
3923 assert(Init->isDelegatingInitializer());
3924 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003925 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003926 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003927 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003928 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003929 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003930 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003931 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003932 // Return immediately as the initializer is set.
3933 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003934 }
Anders Carlssone857b292010-04-02 03:37:03 +00003935 }
3936
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003937 if (HadError)
3938 return;
3939
David Blaikie3fc2f912013-01-17 05:26:25 +00003940 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003941
David Blaikie3fc2f912013-01-17 05:26:25 +00003942 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003943
Richard Trieuef64e942013-10-25 00:56:00 +00003944 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003945}
3946
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003947void
John McCalla6309952010-03-16 21:39:52 +00003948Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3949 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003950 // Ignore dependent contexts. Also ignore unions, since their members never
3951 // have destructors implicitly called.
3952 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003953 return;
John McCall1064d7e2010-03-16 05:22:47 +00003954
3955 // FIXME: all the access-control diagnostics are positioned on the
3956 // field/base declaration. That's probably good; that said, the
3957 // user might reasonably want to know why the destructor is being
3958 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003959
Anders Carlssondee9a302009-11-17 04:44:12 +00003960 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003961 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003962 if (Field->isInvalidDecl())
3963 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003964
3965 // Don't destroy incomplete or zero-length arrays.
3966 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3967 continue;
3968
Anders Carlssondee9a302009-11-17 04:44:12 +00003969 QualType FieldType = Context.getBaseElementType(Field->getType());
3970
3971 const RecordType* RT = FieldType->getAs<RecordType>();
3972 if (!RT)
3973 continue;
3974
3975 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003976 if (FieldClassDecl->isInvalidDecl())
3977 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003978 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003979 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003980 // The destructor for an implicit anonymous union member is never invoked.
3981 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3982 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003983
Douglas Gregore71edda2010-07-01 22:47:18 +00003984 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003985 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003986 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003987 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003988 << Field->getDeclName()
3989 << FieldType);
3990
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003991 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003992 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003993 }
3994
John McCall1064d7e2010-03-16 05:22:47 +00003995 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3996
Anders Carlssondee9a302009-11-17 04:44:12 +00003997 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003998 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00003999 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004000 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004001
4002 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004003 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004004 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004005
John McCall1064d7e2010-03-16 05:22:47 +00004006 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004007 // If our base class is invalid, we probably can't get its dtor anyway.
4008 if (BaseClassDecl->isInvalidDecl())
4009 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004010 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004011 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004012
Douglas Gregore71edda2010-07-01 22:47:18 +00004013 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004014 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004015
4016 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004017 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004018 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004019 << Base.getType()
4020 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004021 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004022
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004023 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004024 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004025 }
4026
4027 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004028 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004029 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004030 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004031
4032 // Ignore direct virtual bases.
4033 if (DirectVirtualBases.count(RT))
4034 continue;
4035
John McCall1064d7e2010-03-16 05:22:47 +00004036 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004037 // If our base class is invalid, we probably can't get its dtor anyway.
4038 if (BaseClassDecl->isInvalidDecl())
4039 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004040 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004041 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004042
Douglas Gregore71edda2010-07-01 22:47:18 +00004043 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004044 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004045 if (CheckDestructorAccess(
4046 ClassDecl->getLocation(), Dtor,
4047 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004048 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004049 Context.getTypeDeclType(ClassDecl)) ==
4050 AR_accessible) {
4051 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004052 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004053 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4054 SourceRange(), DeclarationName(), 0);
4055 }
John McCall1064d7e2010-03-16 05:22:47 +00004056
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004057 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004058 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004059 }
4060}
4061
John McCall48871652010-08-21 09:40:31 +00004062void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004063 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004064 return;
Mike Stump11289f42009-09-09 15:08:12 +00004065
Mike Stump11289f42009-09-09 15:08:12 +00004066 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004067 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004068 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004069 DiagnoseUninitializedFields(*this, Constructor);
4070 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004071}
4072
Mike Stump11289f42009-09-09 15:08:12 +00004073bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004074 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004075 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4076 unsigned DiagID;
4077 AbstractDiagSelID SelID;
4078
4079 public:
4080 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4081 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004082
Craig Toppera798a9d2014-03-02 09:32:10 +00004083 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004084 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004085 if (SelID == -1)
4086 S.Diag(Loc, DiagID) << T;
4087 else
4088 S.Diag(Loc, DiagID) << SelID << T;
4089 }
4090 } Diagnoser(DiagID, SelID);
4091
4092 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004093}
4094
Anders Carlssoneabf7702009-08-27 00:13:57 +00004095bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004096 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004097 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004098 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004099
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004100 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004101 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004102
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004103 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004104 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004105 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004106 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004107
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004108 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004109 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004110 }
Mike Stump11289f42009-09-09 15:08:12 +00004111
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004112 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004113 if (!RT)
4114 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004115
John McCall67da35c2010-02-04 22:26:26 +00004116 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004117
John McCall02db245d2010-08-18 09:41:07 +00004118 // We can't answer whether something is abstract until it has a
4119 // definition. If it's currently being defined, we'll walk back
4120 // over all the declarations when we have a full definition.
4121 const CXXRecordDecl *Def = RD->getDefinition();
4122 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004123 return false;
4124
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004125 if (!RD->isAbstract())
4126 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004127
Douglas Gregorae298422012-05-04 17:09:59 +00004128 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004129 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004130
John McCall02db245d2010-08-18 09:41:07 +00004131 return true;
4132}
4133
4134void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4135 // Check if we've already emitted the list of pure virtual functions
4136 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004137 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004138 return;
Mike Stump11289f42009-09-09 15:08:12 +00004139
Richard Smithbc46e432013-07-22 02:56:56 +00004140 // If the diagnostic is suppressed, don't emit the notes. We're only
4141 // going to emit them once, so try to attach them to a diagnostic we're
4142 // actually going to show.
4143 if (Diags.isLastDiagnosticIgnored())
4144 return;
4145
Douglas Gregor4165bd62010-03-23 23:47:56 +00004146 CXXFinalOverriderMap FinalOverriders;
4147 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004148
Anders Carlssona2f74f32010-06-03 01:00:02 +00004149 // Keep a set of seen pure methods so we won't diagnose the same method
4150 // more than once.
4151 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4152
Douglas Gregor4165bd62010-03-23 23:47:56 +00004153 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4154 MEnd = FinalOverriders.end();
4155 M != MEnd;
4156 ++M) {
4157 for (OverridingMethods::iterator SO = M->second.begin(),
4158 SOEnd = M->second.end();
4159 SO != SOEnd; ++SO) {
4160 // C++ [class.abstract]p4:
4161 // A class is abstract if it contains or inherits at least one
4162 // pure virtual function for which the final overrider is pure
4163 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004164
Douglas Gregor4165bd62010-03-23 23:47:56 +00004165 //
4166 if (SO->second.size() != 1)
4167 continue;
4168
4169 if (!SO->second.front().Method->isPure())
4170 continue;
4171
Anders Carlssona2f74f32010-06-03 01:00:02 +00004172 if (!SeenPureMethods.insert(SO->second.front().Method))
4173 continue;
4174
Douglas Gregor4165bd62010-03-23 23:47:56 +00004175 Diag(SO->second.front().Method->getLocation(),
4176 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004177 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004178 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004179 }
4180
4181 if (!PureVirtualClassDiagSet)
4182 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4183 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004184}
4185
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004186namespace {
John McCall02db245d2010-08-18 09:41:07 +00004187struct AbstractUsageInfo {
4188 Sema &S;
4189 CXXRecordDecl *Record;
4190 CanQualType AbstractType;
4191 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004192
John McCall02db245d2010-08-18 09:41:07 +00004193 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4194 : S(S), Record(Record),
4195 AbstractType(S.Context.getCanonicalType(
4196 S.Context.getTypeDeclType(Record))),
4197 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004198
John McCall02db245d2010-08-18 09:41:07 +00004199 void DiagnoseAbstractType() {
4200 if (Invalid) return;
4201 S.DiagnoseAbstractType(Record);
4202 Invalid = true;
4203 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004204
John McCall02db245d2010-08-18 09:41:07 +00004205 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4206};
4207
4208struct CheckAbstractUsage {
4209 AbstractUsageInfo &Info;
4210 const NamedDecl *Ctx;
4211
4212 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4213 : Info(Info), Ctx(Ctx) {}
4214
4215 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4216 switch (TL.getTypeLocClass()) {
4217#define ABSTRACT_TYPELOC(CLASS, PARENT)
4218#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004219 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004220#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004221 }
John McCall02db245d2010-08-18 09:41:07 +00004222 }
Mike Stump11289f42009-09-09 15:08:12 +00004223
John McCall02db245d2010-08-18 09:41:07 +00004224 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004225 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004226 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4227 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004228 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004229
4230 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004231 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004232 }
John McCall02db245d2010-08-18 09:41:07 +00004233 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004234
John McCall02db245d2010-08-18 09:41:07 +00004235 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4236 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4237 }
Mike Stump11289f42009-09-09 15:08:12 +00004238
John McCall02db245d2010-08-18 09:41:07 +00004239 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4240 // Visit the type parameters from a permissive context.
4241 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4242 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4243 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4244 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4245 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4246 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004247 }
John McCall02db245d2010-08-18 09:41:07 +00004248 }
Mike Stump11289f42009-09-09 15:08:12 +00004249
John McCall02db245d2010-08-18 09:41:07 +00004250 // Visit pointee types from a permissive context.
4251#define CheckPolymorphic(Type) \
4252 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4253 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4254 }
4255 CheckPolymorphic(PointerTypeLoc)
4256 CheckPolymorphic(ReferenceTypeLoc)
4257 CheckPolymorphic(MemberPointerTypeLoc)
4258 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004259 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004260
John McCall02db245d2010-08-18 09:41:07 +00004261 /// Handle all the types we haven't given a more specific
4262 /// implementation for above.
4263 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4264 // Every other kind of type that we haven't called out already
4265 // that has an inner type is either (1) sugar or (2) contains that
4266 // inner type in some way as a subobject.
4267 if (TypeLoc Next = TL.getNextTypeLoc())
4268 return Visit(Next, Sel);
4269
4270 // If there's no inner type and we're in a permissive context,
4271 // don't diagnose.
4272 if (Sel == Sema::AbstractNone) return;
4273
4274 // Check whether the type matches the abstract type.
4275 QualType T = TL.getType();
4276 if (T->isArrayType()) {
4277 Sel = Sema::AbstractArrayType;
4278 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004279 }
John McCall02db245d2010-08-18 09:41:07 +00004280 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4281 if (CT != Info.AbstractType) return;
4282
4283 // It matched; do some magic.
4284 if (Sel == Sema::AbstractArrayType) {
4285 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4286 << T << TL.getSourceRange();
4287 } else {
4288 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4289 << Sel << T << TL.getSourceRange();
4290 }
4291 Info.DiagnoseAbstractType();
4292 }
4293};
4294
4295void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4296 Sema::AbstractDiagSelID Sel) {
4297 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4298}
4299
4300}
4301
4302/// Check for invalid uses of an abstract type in a method declaration.
4303static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4304 CXXMethodDecl *MD) {
4305 // No need to do the check on definitions, which require that
4306 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004307 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004308 return;
4309
4310 // For safety's sake, just ignore it if we don't have type source
4311 // information. This should never happen for non-implicit methods,
4312 // but...
4313 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4314 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4315}
4316
4317/// Check for invalid uses of an abstract type within a class definition.
4318static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4319 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004320 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004321 if (D->isImplicit()) continue;
4322
4323 // Methods and method templates.
4324 if (isa<CXXMethodDecl>(D)) {
4325 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4326 } else if (isa<FunctionTemplateDecl>(D)) {
4327 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4328 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4329
4330 // Fields and static variables.
4331 } else if (isa<FieldDecl>(D)) {
4332 FieldDecl *FD = cast<FieldDecl>(D);
4333 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4334 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4335 } else if (isa<VarDecl>(D)) {
4336 VarDecl *VD = cast<VarDecl>(D);
4337 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4338 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4339
4340 // Nested classes and class templates.
4341 } else if (isa<CXXRecordDecl>(D)) {
4342 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4343 } else if (isa<ClassTemplateDecl>(D)) {
4344 CheckAbstractClassUsage(Info,
4345 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4346 }
4347 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004348}
4349
Douglas Gregorc99f1552009-12-03 18:33:45 +00004350/// \brief Perform semantic checks on a class definition that has been
4351/// completing, introducing implicitly-declared members, checking for
4352/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004353void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004354 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004355 return;
4356
John McCall02db245d2010-08-18 09:41:07 +00004357 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4358 AbstractUsageInfo Info(*this, Record);
4359 CheckAbstractClassUsage(Info, Record);
4360 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004361
4362 // If this is not an aggregate type and has no user-declared constructor,
4363 // complain about any non-static data members of reference or const scalar
4364 // type, since they will never get initializers.
4365 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004366 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4367 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004368 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004369 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004370 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004371 continue;
4372
Douglas Gregor454a5b62010-04-15 00:00:53 +00004373 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004374 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004375 if (!Complained) {
4376 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4377 << Record->getTagKind() << Record;
4378 Complained = true;
4379 }
4380
4381 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4382 << F->getType()->isReferenceType()
4383 << F->getDeclName();
4384 }
4385 }
4386 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004387
Anders Carlssone771e762011-01-25 18:08:22 +00004388 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004389 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004390
4391 if (Record->getIdentifier()) {
4392 // C++ [class.mem]p13:
4393 // If T is the name of a class, then each of the following shall have a
4394 // name different from T:
4395 // - every member of every anonymous union that is a member of class T.
4396 //
4397 // C++ [class.mem]p14:
4398 // In addition, if class T has a user-declared constructor (12.1), every
4399 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004400 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4401 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4402 ++I) {
4403 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004404 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4405 isa<IndirectFieldDecl>(D)) {
4406 Diag(D->getLocation(), diag::err_member_name_of_class)
4407 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004408 break;
4409 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004410 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004411 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004412
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004413 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004414 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004415 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004416 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004417 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4418 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4419 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004420
David Majnemera5433082013-10-18 00:33:31 +00004421 if (Record->isAbstract()) {
4422 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4423 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4424 << FA->isSpelledAsSealed();
4425 DiagnoseAbstractType(Record);
4426 }
David Blaikie348df502012-09-21 03:21:07 +00004427 }
4428
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004429 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004430 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004431 // See if a method overloads virtual methods in a base
4432 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004433 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004434 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004435
4436 // Check whether the explicitly-defaulted special members are valid.
4437 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004438 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004439
4440 // For an explicitly defaulted or deleted special member, we defer
4441 // determining triviality until the class is complete. That time is now!
4442 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004443 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004444 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004445 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004446
4447 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004448 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004449 }
4450 }
4451 }
4452 }
4453
4454 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4455 // function that is not a constructor declares that member function to be
4456 // const. [...] The class of which that function is a member shall be
4457 // a literal type.
4458 //
4459 // If the class has virtual bases, any constexpr members will already have
4460 // been diagnosed by the checks performed on the member declaration, so
4461 // suppress this (less useful) diagnostic.
4462 //
4463 // We delay this until we know whether an explicitly-defaulted (or deleted)
4464 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004465 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004466 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004467 for (const auto *M : Record->methods()) {
4468 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004469 switch (Record->getTemplateSpecializationKind()) {
4470 case TSK_ImplicitInstantiation:
4471 case TSK_ExplicitInstantiationDeclaration:
4472 case TSK_ExplicitInstantiationDefinition:
4473 // If a template instantiates to a non-literal type, but its members
4474 // instantiate to constexpr functions, the template is technically
4475 // ill-formed, but we allow it for sanity.
4476 continue;
4477
4478 case TSK_Undeclared:
4479 case TSK_ExplicitSpecialization:
4480 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4481 diag::err_constexpr_method_non_literal);
4482 break;
4483 }
4484
4485 // Only produce one error per class.
4486 break;
4487 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004488 }
4489 }
Sebastian Redl08905022011-02-05 19:23:19 +00004490
John McCall95833f32014-02-27 20:30:49 +00004491 // ms_struct is a request to use the same ABI rules as MSVC. Check
4492 // whether this class uses any C++ features that are implemented
4493 // completely differently in MSVC, and if so, emit a diagnostic.
4494 // That diagnostic defaults to an error, but we allow projects to
4495 // map it down to a warning (or ignore it). It's a fairly common
4496 // practice among users of the ms_struct pragma to mass-annotate
4497 // headers, sweeping up a bunch of types that the project doesn't
4498 // really rely on MSVC-compatible layout for. We must therefore
4499 // support "ms_struct except for C++ stuff" as a secondary ABI.
4500 if (Record->isMsStruct(Context) &&
4501 (Record->isPolymorphic() || Record->getNumBases())) {
4502 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004503 }
4504
Richard Smithc2bc61b2013-03-18 21:12:30 +00004505 // Declare inheriting constructors. We do this eagerly here because:
4506 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004507 // constructors from different classes.
4508 // - The lazy declaration of the other implicit constructors is so as to not
4509 // waste space and performance on classes that are not meant to be
4510 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004511 // have inheriting constructors.
4512 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004513}
4514
Richard Smith41c35d62013-11-27 03:39:20 +00004515/// Look up the special member function that would be called by a special
4516/// member function for a subobject of class type.
4517///
4518/// \param Class The class type of the subobject.
4519/// \param CSM The kind of special member function.
4520/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4521/// \param ConstRHS True if this is a copy operation with a const object
4522/// on its RHS, that is, if the argument to the outer special member
4523/// function is 'const' and this is not a field marked 'mutable'.
4524static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4525 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4526 unsigned FieldQuals, bool ConstRHS) {
4527 unsigned LHSQuals = 0;
4528 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4529 LHSQuals = FieldQuals;
4530
4531 unsigned RHSQuals = FieldQuals;
4532 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4533 RHSQuals = 0;
4534 else if (ConstRHS)
4535 RHSQuals |= Qualifiers::Const;
4536
4537 return S.LookupSpecialMember(Class, CSM,
4538 RHSQuals & Qualifiers::Const,
4539 RHSQuals & Qualifiers::Volatile,
4540 false,
4541 LHSQuals & Qualifiers::Const,
4542 LHSQuals & Qualifiers::Volatile);
4543}
4544
Richard Smithb5800092012-06-10 05:43:50 +00004545/// Is the special member function which would be selected to perform the
4546/// specified operation on the specified class type a constexpr constructor?
4547static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4548 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004549 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004550 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004551 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004552 if (!SMOR || !SMOR->getMethod())
4553 // A constructor we wouldn't select can't be "involved in initializing"
4554 // anything.
4555 return true;
4556 return SMOR->getMethod()->isConstexpr();
4557}
4558
4559/// Determine whether the specified special member function would be constexpr
4560/// if it were implicitly defined.
4561static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4562 Sema::CXXSpecialMember CSM,
4563 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004564 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004565 return false;
4566
4567 // C++11 [dcl.constexpr]p4:
4568 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004569 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004570 switch (CSM) {
4571 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004572 // Since default constructor lookup is essentially trivial (and cannot
4573 // involve, for instance, template instantiation), we compute whether a
4574 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4575 //
4576 // This is important for performance; we need to know whether the default
4577 // constructor is constexpr to determine whether the type is a literal type.
4578 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4579
Richard Smithb5800092012-06-10 05:43:50 +00004580 case Sema::CXXCopyConstructor:
4581 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004582 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004583 break;
4584
4585 case Sema::CXXCopyAssignment:
4586 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004587 if (!S.getLangOpts().CPlusPlus1y)
4588 return false;
4589 // In C++1y, we need to perform overload resolution.
4590 Ctor = false;
4591 break;
4592
Richard Smithb5800092012-06-10 05:43:50 +00004593 case Sema::CXXDestructor:
4594 case Sema::CXXInvalid:
4595 return false;
4596 }
4597
4598 // -- if the class is a non-empty union, or for each non-empty anonymous
4599 // union member of a non-union class, exactly one non-static data member
4600 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004601 //
4602 // If we squint, this is guaranteed, since exactly one non-static data member
4603 // will be initialized (if the constructor isn't deleted), we just don't know
4604 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004605 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004606 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004607
4608 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004609 if (Ctor && ClassDecl->getNumVBases())
4610 return false;
4611
4612 // C++1y [class.copy]p26:
4613 // -- [the class] is a literal type, and
4614 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004615 return false;
4616
4617 // -- every constructor involved in initializing [...] base class
4618 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004619 // -- the assignment operator selected to copy/move each direct base
4620 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004621 for (const auto &B : ClassDecl->bases()) {
4622 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004623 if (!BaseType) continue;
4624
4625 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004626 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004627 return false;
4628 }
4629
4630 // -- every constructor involved in initializing non-static data members
4631 // [...] shall be a constexpr constructor;
4632 // -- every non-static data member and base class sub-object shall be
4633 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004634 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004635 // thereof), the assignment operator selected to copy/move that member is
4636 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004637 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004638 if (F->isInvalidDecl())
4639 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004640 QualType BaseType = S.Context.getBaseElementType(F->getType());
4641 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004642 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004643 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4644 BaseType.getCVRQualifiers(),
4645 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004646 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004647 }
4648 }
4649
4650 // All OK, it's constexpr!
4651 return true;
4652}
4653
Richard Smithd3b5c9082012-07-27 04:22:15 +00004654static Sema::ImplicitExceptionSpecification
4655computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4656 switch (S.getSpecialMember(MD)) {
4657 case Sema::CXXDefaultConstructor:
4658 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4659 case Sema::CXXCopyConstructor:
4660 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4661 case Sema::CXXCopyAssignment:
4662 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4663 case Sema::CXXMoveConstructor:
4664 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4665 case Sema::CXXMoveAssignment:
4666 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4667 case Sema::CXXDestructor:
4668 return S.ComputeDefaultedDtorExceptionSpec(MD);
4669 case Sema::CXXInvalid:
4670 break;
4671 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004672 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4673 "only special members have implicit exception specs");
4674 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004675}
4676
Reid Kleckner78af0702013-08-27 23:08:25 +00004677static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4678 CXXMethodDecl *MD) {
4679 FunctionProtoType::ExtProtoInfo EPI;
4680
4681 // Build an exception specification pointing back at this member.
4682 EPI.ExceptionSpecType = EST_Unevaluated;
4683 EPI.ExceptionSpecDecl = MD;
4684
4685 // Set the calling convention to the default for C++ instance methods.
4686 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4687 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4688 /*IsCXXMethod=*/true));
4689 return EPI;
4690}
4691
Richard Smithd3b5c9082012-07-27 04:22:15 +00004692void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4693 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4694 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4695 return;
4696
Richard Smith7f782272012-07-30 23:48:14 +00004697 // Evaluate the exception specification.
4698 ImplicitExceptionSpecification ExceptSpec =
4699 computeImplicitExceptionSpec(*this, Loc, MD);
4700
Richard Smith564417a2014-03-20 21:47:22 +00004701 FunctionProtoType::ExtProtoInfo EPI;
4702 ExceptSpec.getEPI(EPI);
4703
Richard Smith7f782272012-07-30 23:48:14 +00004704 // Update the type of the special member to use it.
Richard Smith564417a2014-03-20 21:47:22 +00004705 UpdateExceptionSpec(MD, EPI);
Richard Smith7f782272012-07-30 23:48:14 +00004706
4707 // A user-provided destructor can be defined outside the class. When that
4708 // happens, be sure to update the exception specification on both
4709 // declarations.
4710 const FunctionProtoType *CanonicalFPT =
4711 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4712 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith564417a2014-03-20 21:47:22 +00004713 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004714}
4715
Richard Smithb9e90b12012-05-15 04:39:51 +00004716void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4717 CXXRecordDecl *RD = MD->getParent();
4718 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004719
Richard Smithb9e90b12012-05-15 04:39:51 +00004720 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4721 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004722
4723 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004724 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004725 bool First = MD == MD->getCanonicalDecl();
4726
4727 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004728
4729 // C++11 [dcl.fct.def.default]p1:
4730 // A function that is explicitly defaulted shall
4731 // -- be a special member function (checked elsewhere),
4732 // -- have the same type (except for ref-qualifiers, and except that a
4733 // copy operation can take a non-const reference) as an implicit
4734 // declaration, and
4735 // -- not have default arguments.
4736 unsigned ExpectedParams = 1;
4737 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4738 ExpectedParams = 0;
4739 if (MD->getNumParams() != ExpectedParams) {
4740 // This also checks for default arguments: a copy or move constructor with a
4741 // default argument is classified as a default constructor, and assignment
4742 // operations and destructors can't have default arguments.
4743 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4744 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004745 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004746 } else if (MD->isVariadic()) {
4747 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4748 << CSM << MD->getSourceRange();
4749 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004750 }
4751
Richard Smithb9e90b12012-05-15 04:39:51 +00004752 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004753
Richard Smithb5800092012-06-10 05:43:50 +00004754 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004755 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004756 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004757 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004758 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004759
Richard Smithb9e90b12012-05-15 04:39:51 +00004760 QualType ReturnType = Context.VoidTy;
4761 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4762 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004763 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004764 QualType ExpectedReturnType =
4765 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4766 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4767 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4768 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4769 HadError = true;
4770 }
4771
4772 // A defaulted special member cannot have cv-qualifiers.
4773 if (Type->getTypeQuals()) {
4774 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004775 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004776 HadError = true;
4777 }
4778 }
4779
4780 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004781 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004782 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004783 if (ExpectedParams && ArgType->isReferenceType()) {
4784 // Argument must be reference to possibly-const T.
4785 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004786 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004787
4788 if (ReferentType.isVolatileQualified()) {
4789 Diag(MD->getLocation(),
4790 diag::err_defaulted_special_member_volatile_param) << CSM;
4791 HadError = true;
4792 }
4793
Richard Smithb5800092012-06-10 05:43:50 +00004794 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004795 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4796 Diag(MD->getLocation(),
4797 diag::err_defaulted_special_member_copy_const_param)
4798 << (CSM == CXXCopyAssignment);
4799 // FIXME: Explain why this special member can't be const.
4800 } else {
4801 Diag(MD->getLocation(),
4802 diag::err_defaulted_special_member_move_const_param)
4803 << (CSM == CXXMoveAssignment);
4804 }
4805 HadError = true;
4806 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004807 } else if (ExpectedParams) {
4808 // A copy assignment operator can take its argument by value, but a
4809 // defaulted one cannot.
4810 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004811 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004812 HadError = true;
4813 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004814
Richard Smithcc36f692011-12-22 02:22:31 +00004815 // C++11 [dcl.fct.def.default]p2:
4816 // An explicitly-defaulted function may be declared constexpr only if it
4817 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004818 // Do not apply this rule to members of class templates, since core issue 1358
4819 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004820 // functions which cannot be constexpr (for non-constructors in C++11 and for
4821 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004822 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4823 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004824 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4825 : isa<CXXConstructorDecl>(MD)) &&
4826 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004827 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4828 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004829 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004830 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004831 }
Richard Smithbd305122012-12-11 01:14:52 +00004832
Richard Smithcc36f692011-12-22 02:22:31 +00004833 // and may have an explicit exception-specification only if it is compatible
4834 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004835 if (Type->hasExceptionSpec()) {
4836 // Delay the check if this is the first declaration of the special member,
4837 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004838 if (First) {
4839 // If the exception specification needs to be instantiated, do so now,
4840 // before we clobber it with an EST_Unevaluated specification below.
4841 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4842 InstantiateExceptionSpec(MD->getLocStart(), MD);
4843 Type = MD->getType()->getAs<FunctionProtoType>();
4844 }
Richard Smithbd305122012-12-11 01:14:52 +00004845 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004846 } else
Richard Smithbd305122012-12-11 01:14:52 +00004847 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4848 }
Richard Smithcc36f692011-12-22 02:22:31 +00004849
4850 // If a function is explicitly defaulted on its first declaration,
4851 if (First) {
4852 // -- it is implicitly considered to be constexpr if the implicit
4853 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004854 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004855
Richard Smithb9e90b12012-05-15 04:39:51 +00004856 // -- it is implicitly considered to have the same exception-specification
4857 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004858 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4859 EPI.ExceptionSpecType = EST_Unevaluated;
4860 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004861 MD->setType(Context.getFunctionType(ReturnType,
4862 ArrayRef<QualType>(&ArgType,
4863 ExpectedParams),
4864 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004865 }
4866
Richard Smithb9e90b12012-05-15 04:39:51 +00004867 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004868 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004869 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004870 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004871 // C++11 [dcl.fct.def.default]p4:
4872 // [For a] user-provided explicitly-defaulted function [...] if such a
4873 // function is implicitly defined as deleted, the program is ill-formed.
4874 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00004875 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00004876 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004877 }
4878 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004879
Richard Smithb9e90b12012-05-15 04:39:51 +00004880 if (HadError)
4881 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004882}
4883
Richard Smithbd305122012-12-11 01:14:52 +00004884/// Check whether the exception specification provided for an
4885/// explicitly-defaulted special member matches the exception specification
4886/// that would have been generated for an implicit special member, per
4887/// C++11 [dcl.fct.def.default]p2.
4888void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4889 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4890 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004891 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4892 /*IsCXXMethod=*/true);
4893 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004894 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4895 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004896 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004897
4898 // Ensure that it matches.
4899 CheckEquivalentExceptionSpec(
4900 PDiag(diag::err_incorrect_defaulted_exception_spec)
4901 << getSpecialMember(MD), PDiag(),
4902 ImplicitType, SourceLocation(),
4903 SpecifiedType, MD->getLocation());
4904}
4905
Alp Tokerae3a9442013-10-18 05:54:19 +00004906void Sema::CheckDelayedMemberExceptionSpecs() {
4907 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4908 2> Checks;
4909 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00004910
Alp Tokerae3a9442013-10-18 05:54:19 +00004911 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4912 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4913
4914 // Perform any deferred checking of exception specifications for virtual
4915 // destructors.
4916 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4917 const CXXDestructorDecl *Dtor = Checks[i].first;
4918 assert(!Dtor->getParent()->isDependentType() &&
4919 "Should not ever add destructors of templates into the list.");
4920 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4921 }
4922
4923 // Check that any explicitly-defaulted methods have exception specifications
4924 // compatible with their implicit exception specifications.
4925 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4926 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4927 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00004928}
4929
Richard Smithd951a1d2012-02-18 02:02:13 +00004930namespace {
4931struct SpecialMemberDeletionInfo {
4932 Sema &S;
4933 CXXMethodDecl *MD;
4934 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004935 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004936
4937 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00004938 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00004939 SourceLocation Loc;
4940
4941 bool AllFieldsAreConst;
4942
4943 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004944 Sema::CXXSpecialMember CSM, bool Diagnose)
4945 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004946 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00004947 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00004948 AllFieldsAreConst(true) {
4949 switch (CSM) {
4950 case Sema::CXXDefaultConstructor:
4951 case Sema::CXXCopyConstructor:
4952 IsConstructor = true;
4953 break;
4954 case Sema::CXXMoveConstructor:
4955 IsConstructor = true;
4956 IsMove = true;
4957 break;
4958 case Sema::CXXCopyAssignment:
4959 IsAssignment = true;
4960 break;
4961 case Sema::CXXMoveAssignment:
4962 IsAssignment = true;
4963 IsMove = true;
4964 break;
4965 case Sema::CXXDestructor:
4966 break;
4967 case Sema::CXXInvalid:
4968 llvm_unreachable("invalid special member kind");
4969 }
4970
4971 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00004972 if (const ReferenceType *RT =
4973 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
4974 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00004975 }
4976 }
4977
4978 bool inUnion() const { return MD->getParent()->isUnion(); }
4979
4980 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00004981 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00004982 unsigned Quals, bool IsMutable) {
4983 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
4984 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00004985 }
4986
Richard Smith852265f2012-03-30 20:53:28 +00004987 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00004988
Richard Smith852265f2012-03-30 20:53:28 +00004989 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00004990 bool shouldDeleteForField(FieldDecl *FD);
4991 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00004992
Richard Smithaf136f82012-07-18 03:51:16 +00004993 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4994 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00004995 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4996 Sema::SpecialMemberOverloadResult *SMOR,
4997 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00004998
4999 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005000};
5001}
5002
John McCalld4274212012-04-09 20:53:23 +00005003/// Is the given special member inaccessible when used on the given
5004/// sub-object.
5005bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5006 CXXMethodDecl *target) {
5007 /// If we're operating on a base class, the object type is the
5008 /// type of this special member.
5009 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005010 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005011 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5012 objectTy = S.Context.getTypeDeclType(MD->getParent());
5013 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5014
5015 // If we're operating on a field, the object type is the type of the field.
5016 } else {
5017 objectTy = S.Context.getTypeDeclType(target->getParent());
5018 }
5019
5020 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5021}
5022
Richard Smith852265f2012-03-30 20:53:28 +00005023/// Check whether we should delete a special member due to the implicit
5024/// definition containing a call to a special member of a subobject.
5025bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5026 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5027 bool IsDtorCallInCtor) {
5028 CXXMethodDecl *Decl = SMOR->getMethod();
5029 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5030
5031 int DiagKind = -1;
5032
5033 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5034 DiagKind = !Decl ? 0 : 1;
5035 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5036 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005037 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005038 DiagKind = 3;
5039 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5040 !Decl->isTrivial()) {
5041 // A member of a union must have a trivial corresponding special member.
5042 // As a weird special case, a destructor call from a union's constructor
5043 // must be accessible and non-deleted, but need not be trivial. Such a
5044 // destructor is never actually called, but is semantically checked as
5045 // if it were.
5046 DiagKind = 4;
5047 }
5048
5049 if (DiagKind == -1)
5050 return false;
5051
5052 if (Diagnose) {
5053 if (Field) {
5054 S.Diag(Field->getLocation(),
5055 diag::note_deleted_special_member_class_subobject)
5056 << CSM << MD->getParent() << /*IsField*/true
5057 << Field << DiagKind << IsDtorCallInCtor;
5058 } else {
5059 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5060 S.Diag(Base->getLocStart(),
5061 diag::note_deleted_special_member_class_subobject)
5062 << CSM << MD->getParent() << /*IsField*/false
5063 << Base->getType() << DiagKind << IsDtorCallInCtor;
5064 }
5065
5066 if (DiagKind == 1)
5067 S.NoteDeletedFunction(Decl);
5068 // FIXME: Explain inaccessibility if DiagKind == 3.
5069 }
5070
5071 return true;
5072}
5073
Richard Smith921bd202012-02-26 09:11:52 +00005074/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005075/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005076bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005077 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005078 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005079 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005080
5081 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005082 // -- any direct or virtual base class, or non-static data member with no
5083 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005084 // either M has no default constructor or overload resolution as applied
5085 // to M's default constructor results in an ambiguity or in a function
5086 // that is deleted or inaccessible
5087 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5088 // -- a direct or virtual base class B that cannot be copied/moved because
5089 // overload resolution, as applied to B's corresponding special member,
5090 // results in an ambiguity or a function that is deleted or inaccessible
5091 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005092 // C++11 [class.dtor]p5:
5093 // -- any direct or virtual base class [...] has a type with a destructor
5094 // that is deleted or inaccessible
5095 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005096 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005097 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5098 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005099 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005100
Richard Smith852265f2012-03-30 20:53:28 +00005101 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5102 // -- any direct or virtual base class or non-static data member has a
5103 // type with a destructor that is deleted or inaccessible
5104 if (IsConstructor) {
5105 Sema::SpecialMemberOverloadResult *SMOR =
5106 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5107 false, false, false, false, false);
5108 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5109 return true;
5110 }
5111
Richard Smith921bd202012-02-26 09:11:52 +00005112 return false;
5113}
5114
5115/// Check whether we should delete a special member function due to the class
5116/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005117bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005118 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005119 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005120}
5121
5122/// Check whether we should delete a special member function due to the class
5123/// having a particular non-static data member.
5124bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5125 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5126 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5127
5128 if (CSM == Sema::CXXDefaultConstructor) {
5129 // For a default constructor, all references must be initialized in-class
5130 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005131 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5132 if (Diagnose)
5133 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5134 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005135 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005136 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005137 // C++11 [class.ctor]p5: any non-variant non-static data member of
5138 // const-qualified type (or array thereof) with no
5139 // brace-or-equal-initializer does not have a user-provided default
5140 // constructor.
5141 if (!inUnion() && FieldType.isConstQualified() &&
5142 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005143 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5144 if (Diagnose)
5145 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005146 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005147 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005148 }
5149
5150 if (inUnion() && !FieldType.isConstQualified())
5151 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005152 } else if (CSM == Sema::CXXCopyConstructor) {
5153 // For a copy constructor, data members must not be of rvalue reference
5154 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005155 if (FieldType->isRValueReferenceType()) {
5156 if (Diagnose)
5157 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5158 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005159 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005160 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005161 } else if (IsAssignment) {
5162 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005163 if (FieldType->isReferenceType()) {
5164 if (Diagnose)
5165 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5166 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005167 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005168 }
5169 if (!FieldRecord && FieldType.isConstQualified()) {
5170 // C++11 [class.copy]p23:
5171 // -- a non-static data member of const non-class type (or array thereof)
5172 if (Diagnose)
5173 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005174 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005175 return true;
5176 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005177 }
5178
5179 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005180 // Some additional restrictions exist on the variant members.
5181 if (!inUnion() && FieldRecord->isUnion() &&
5182 FieldRecord->isAnonymousStructOrUnion()) {
5183 bool AllVariantFieldsAreConst = true;
5184
Richard Smith5704fe82012-03-29 19:00:10 +00005185 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005186 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005187 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005188
5189 if (!UnionFieldType.isConstQualified())
5190 AllVariantFieldsAreConst = false;
5191
Richard Smith921bd202012-02-26 09:11:52 +00005192 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5193 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005194 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005195 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005196 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005197 }
5198
5199 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005200 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005201 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005202 if (Diagnose)
5203 S.Diag(FieldRecord->getLocation(),
5204 diag::note_deleted_default_ctor_all_const)
5205 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005206 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005207 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005208
Richard Smith5704fe82012-03-29 19:00:10 +00005209 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005210 // This is technically non-conformant, but sanity demands it.
5211 return false;
5212 }
5213
Richard Smithaf136f82012-07-18 03:51:16 +00005214 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5215 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005216 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005217 }
5218
5219 return false;
5220}
5221
5222/// C++11 [class.ctor] p5:
5223/// A defaulted default constructor for a class X is defined as deleted if
5224/// X is a union and all of its variant members are of const-qualified type.
5225bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005226 // This is a silly definition, because it gives an empty union a deleted
5227 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005228 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005229 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005230 if (Diagnose)
5231 S.Diag(MD->getParent()->getLocation(),
5232 diag::note_deleted_default_ctor_all_const)
5233 << MD->getParent() << /*not anonymous union*/0;
5234 return true;
5235 }
5236 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005237}
5238
5239/// Determine whether a defaulted special member function should be defined as
5240/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5241/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005242bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5243 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005244 if (MD->isInvalidDecl())
5245 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005246 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005247 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005248 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005249 return false;
5250
Richard Smithd951a1d2012-02-18 02:02:13 +00005251 // C++11 [expr.lambda.prim]p19:
5252 // The closure type associated with a lambda-expression has a
5253 // deleted (8.4.3) default constructor and a deleted copy
5254 // assignment operator.
5255 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005256 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5257 if (Diagnose)
5258 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005259 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005260 }
5261
Richard Smith6f1e2c62012-04-02 20:59:25 +00005262 // For an anonymous struct or union, the copy and assignment special members
5263 // will never be used, so skip the check. For an anonymous union declared at
5264 // namespace scope, the constructor and destructor are used.
5265 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5266 RD->isAnonymousStructOrUnion())
5267 return false;
5268
Richard Smith852265f2012-03-30 20:53:28 +00005269 // C++11 [class.copy]p7, p18:
5270 // If the class definition declares a move constructor or move assignment
5271 // operator, an implicitly declared copy constructor or copy assignment
5272 // operator is defined as deleted.
5273 if (MD->isImplicit() &&
5274 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5275 CXXMethodDecl *UserDeclaredMove = 0;
5276
5277 // In Microsoft mode, a user-declared move only causes the deletion of the
5278 // corresponding copy operation, not both copy operations.
5279 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005280 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005281 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005282
5283 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005284 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005285 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005286 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005287 break;
5288 }
5289 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005290 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005291 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005292 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005293 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005294
5295 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005296 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005297 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005298 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005299 break;
5300 }
5301 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005302 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005303 }
5304
5305 if (UserDeclaredMove) {
5306 Diag(UserDeclaredMove->getLocation(),
5307 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005308 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005309 << UserDeclaredMove->isMoveAssignmentOperator();
5310 return true;
5311 }
5312 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005313
Richard Smith6f1e2c62012-04-02 20:59:25 +00005314 // Do access control from the special member function
5315 ContextRAII MethodContext(*this, MD);
5316
Richard Smith921bd202012-02-26 09:11:52 +00005317 // C++11 [class.dtor]p5:
5318 // -- for a virtual destructor, lookup of the non-array deallocation function
5319 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005320 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005321 FunctionDecl *OperatorDelete = 0;
5322 DeclarationName Name =
5323 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5324 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005325 OperatorDelete, false)) {
5326 if (Diagnose)
5327 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005328 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005329 }
Richard Smith921bd202012-02-26 09:11:52 +00005330 }
5331
Richard Smith852265f2012-03-30 20:53:28 +00005332 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005333
Aaron Ballman574705e2014-03-13 15:41:46 +00005334 for (auto &BI : RD->bases())
5335 if (!BI.isVirtual() &&
5336 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005337 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005338
Richard Smithd1627032013-07-22 18:06:23 +00005339 // Per DR1611, do not consider virtual bases of constructors of abstract
5340 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005341 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005342 for (auto &BI : RD->vbases())
5343 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005344 return true;
5345 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005346
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005347 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005348 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005349 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005350 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005351
Richard Smithd951a1d2012-02-18 02:02:13 +00005352 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005353 return true;
5354
5355 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005356}
5357
Richard Smith92f241f2012-12-08 02:53:02 +00005358/// Perform lookup for a special member of the specified kind, and determine
5359/// whether it is trivial. If the triviality can be determined without the
5360/// lookup, skip it. This is intended for use when determining whether a
5361/// special member of a containing object is trivial, and thus does not ever
5362/// perform overload resolution for default constructors.
5363///
5364/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5365/// member that was most likely to be intended to be trivial, if any.
5366static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5367 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005368 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005369 if (Selected)
5370 *Selected = 0;
5371
5372 switch (CSM) {
5373 case Sema::CXXInvalid:
5374 llvm_unreachable("not a special member");
5375
5376 case Sema::CXXDefaultConstructor:
5377 // C++11 [class.ctor]p5:
5378 // A default constructor is trivial if:
5379 // - all the [direct subobjects] have trivial default constructors
5380 //
5381 // Note, no overload resolution is performed in this case.
5382 if (RD->hasTrivialDefaultConstructor())
5383 return true;
5384
5385 if (Selected) {
5386 // If there's a default constructor which could have been trivial, dig it
5387 // out. Otherwise, if there's any user-provided default constructor, point
5388 // to that as an example of why there's not a trivial one.
5389 CXXConstructorDecl *DefCtor = 0;
5390 if (RD->needsImplicitDefaultConstructor())
5391 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005392 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005393 if (!CI->isDefaultConstructor())
5394 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005395 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005396 if (!DefCtor->isUserProvided())
5397 break;
5398 }
5399
5400 *Selected = DefCtor;
5401 }
5402
5403 return false;
5404
5405 case Sema::CXXDestructor:
5406 // C++11 [class.dtor]p5:
5407 // A destructor is trivial if:
5408 // - all the direct [subobjects] have trivial destructors
5409 if (RD->hasTrivialDestructor())
5410 return true;
5411
5412 if (Selected) {
5413 if (RD->needsImplicitDestructor())
5414 S.DeclareImplicitDestructor(RD);
5415 *Selected = RD->getDestructor();
5416 }
5417
5418 return false;
5419
5420 case Sema::CXXCopyConstructor:
5421 // C++11 [class.copy]p12:
5422 // A copy constructor is trivial if:
5423 // - the constructor selected to copy each direct [subobject] is trivial
5424 if (RD->hasTrivialCopyConstructor()) {
5425 if (Quals == Qualifiers::Const)
5426 // We must either select the trivial copy constructor or reach an
5427 // ambiguity; no need to actually perform overload resolution.
5428 return true;
5429 } else if (!Selected) {
5430 return false;
5431 }
5432 // In C++98, we are not supposed to perform overload resolution here, but we
5433 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5434 // cases like B as having a non-trivial copy constructor:
5435 // struct A { template<typename T> A(T&); };
5436 // struct B { mutable A a; };
5437 goto NeedOverloadResolution;
5438
5439 case Sema::CXXCopyAssignment:
5440 // C++11 [class.copy]p25:
5441 // A copy assignment operator is trivial if:
5442 // - the assignment operator selected to copy each direct [subobject] is
5443 // trivial
5444 if (RD->hasTrivialCopyAssignment()) {
5445 if (Quals == Qualifiers::Const)
5446 return true;
5447 } else if (!Selected) {
5448 return false;
5449 }
5450 // In C++98, we are not supposed to perform overload resolution here, but we
5451 // treat that as a language defect.
5452 goto NeedOverloadResolution;
5453
5454 case Sema::CXXMoveConstructor:
5455 case Sema::CXXMoveAssignment:
5456 NeedOverloadResolution:
5457 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005458 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005459
5460 // The standard doesn't describe how to behave if the lookup is ambiguous.
5461 // We treat it as not making the member non-trivial, just like the standard
5462 // mandates for the default constructor. This should rarely matter, because
5463 // the member will also be deleted.
5464 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5465 return true;
5466
5467 if (!SMOR->getMethod()) {
5468 assert(SMOR->getKind() ==
5469 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5470 return false;
5471 }
5472
5473 // We deliberately don't check if we found a deleted special member. We're
5474 // not supposed to!
5475 if (Selected)
5476 *Selected = SMOR->getMethod();
5477 return SMOR->getMethod()->isTrivial();
5478 }
5479
5480 llvm_unreachable("unknown special method kind");
5481}
5482
Benjamin Kramer3e350262013-02-15 12:30:38 +00005483static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005484 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005485 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005486 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005487
5488 // Look for constructor templates.
5489 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5490 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5491 if (CXXConstructorDecl *CD =
5492 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5493 return CD;
5494 }
5495
5496 return 0;
5497}
5498
5499/// The kind of subobject we are checking for triviality. The values of this
5500/// enumeration are used in diagnostics.
5501enum TrivialSubobjectKind {
5502 /// The subobject is a base class.
5503 TSK_BaseClass,
5504 /// The subobject is a non-static data member.
5505 TSK_Field,
5506 /// The object is actually the complete object.
5507 TSK_CompleteObject
5508};
5509
5510/// Check whether the special member selected for a given type would be trivial.
5511static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005512 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005513 Sema::CXXSpecialMember CSM,
5514 TrivialSubobjectKind Kind,
5515 bool Diagnose) {
5516 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5517 if (!SubRD)
5518 return true;
5519
5520 CXXMethodDecl *Selected;
5521 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Richard Smith41c35d62013-11-27 03:39:20 +00005522 ConstRHS, Diagnose ? &Selected : 0))
Richard Smith92f241f2012-12-08 02:53:02 +00005523 return true;
5524
5525 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005526 if (ConstRHS)
5527 SubType.addConst();
5528
Richard Smith92f241f2012-12-08 02:53:02 +00005529 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5530 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5531 << Kind << SubType.getUnqualifiedType();
5532 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5533 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5534 } else if (!Selected)
5535 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5536 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5537 else if (Selected->isUserProvided()) {
5538 if (Kind == TSK_CompleteObject)
5539 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5540 << Kind << SubType.getUnqualifiedType() << CSM;
5541 else {
5542 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5543 << Kind << SubType.getUnqualifiedType() << CSM;
5544 S.Diag(Selected->getLocation(), diag::note_declared_at);
5545 }
5546 } else {
5547 if (Kind != TSK_CompleteObject)
5548 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5549 << Kind << SubType.getUnqualifiedType() << CSM;
5550
5551 // Explain why the defaulted or deleted special member isn't trivial.
5552 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5553 }
5554 }
5555
5556 return false;
5557}
5558
5559/// Check whether the members of a class type allow a special member to be
5560/// trivial.
5561static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5562 Sema::CXXSpecialMember CSM,
5563 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005564 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005565 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5566 continue;
5567
5568 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5569
5570 // Pretend anonymous struct or union members are members of this class.
5571 if (FI->isAnonymousStructOrUnion()) {
5572 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5573 CSM, ConstArg, Diagnose))
5574 return false;
5575 continue;
5576 }
5577
5578 // C++11 [class.ctor]p5:
5579 // A default constructor is trivial if [...]
5580 // -- no non-static data member of its class has a
5581 // brace-or-equal-initializer
5582 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5583 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005584 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005585 return false;
5586 }
5587
5588 // Objective C ARC 4.3.5:
5589 // [...] nontrivally ownership-qualified types are [...] not trivially
5590 // default constructible, copy constructible, move constructible, copy
5591 // assignable, move assignable, or destructible [...]
5592 if (S.getLangOpts().ObjCAutoRefCount &&
5593 FieldType.hasNonTrivialObjCLifetime()) {
5594 if (Diagnose)
5595 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5596 << RD << FieldType.getObjCLifetime();
5597 return false;
5598 }
5599
Richard Smith41c35d62013-11-27 03:39:20 +00005600 bool ConstRHS = ConstArg && !FI->isMutable();
5601 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5602 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005603 return false;
5604 }
5605
5606 return true;
5607}
5608
5609/// Diagnose why the specified class does not have a trivial special member of
5610/// the given kind.
5611void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5612 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005613
Richard Smith41c35d62013-11-27 03:39:20 +00005614 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5615 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005616 TSK_CompleteObject, /*Diagnose*/true);
5617}
5618
5619/// Determine whether a defaulted or deleted special member function is trivial,
5620/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5621/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5622bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5623 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005624 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5625
5626 CXXRecordDecl *RD = MD->getParent();
5627
5628 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005629
Richard Smith2002bfe2013-11-04 02:02:27 +00005630 // C++11 [class.copy]p12, p25: [DR1593]
5631 // A [special member] is trivial if [...] its parameter-type-list is
5632 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005633 switch (CSM) {
5634 case CXXDefaultConstructor:
5635 case CXXDestructor:
5636 // Trivial default constructors and destructors cannot have parameters.
5637 break;
5638
5639 case CXXCopyConstructor:
5640 case CXXCopyAssignment: {
5641 // Trivial copy operations always have const, non-volatile parameter types.
5642 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005643 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005644 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5645 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5646 if (Diagnose)
5647 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5648 << Param0->getSourceRange() << Param0->getType()
5649 << Context.getLValueReferenceType(
5650 Context.getRecordType(RD).withConst());
5651 return false;
5652 }
5653 break;
5654 }
5655
5656 case CXXMoveConstructor:
5657 case CXXMoveAssignment: {
5658 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005659 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005660 const RValueReferenceType *RT =
5661 Param0->getType()->getAs<RValueReferenceType>();
5662 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5663 if (Diagnose)
5664 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5665 << Param0->getSourceRange() << Param0->getType()
5666 << Context.getRValueReferenceType(Context.getRecordType(RD));
5667 return false;
5668 }
5669 break;
5670 }
5671
5672 case CXXInvalid:
5673 llvm_unreachable("not a special member");
5674 }
5675
Richard Smith92f241f2012-12-08 02:53:02 +00005676 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5677 if (Diagnose)
5678 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5679 diag::note_nontrivial_default_arg)
5680 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5681 return false;
5682 }
5683 if (MD->isVariadic()) {
5684 if (Diagnose)
5685 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5686 return false;
5687 }
5688
5689 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5690 // A copy/move [constructor or assignment operator] is trivial if
5691 // -- the [member] selected to copy/move each direct base class subobject
5692 // is trivial
5693 //
5694 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5695 // A [default constructor or destructor] is trivial if
5696 // -- all the direct base classes have trivial [default constructors or
5697 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005698 for (const auto &BI : RD->bases())
5699 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005700 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005701 return false;
5702
5703 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5704 // A copy/move [constructor or assignment operator] for a class X is
5705 // trivial if
5706 // -- for each non-static data member of X that is of class type (or array
5707 // thereof), the constructor selected to copy/move that member is
5708 // trivial
5709 //
5710 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5711 // A [default constructor or destructor] is trivial if
5712 // -- for all of the non-static data members of its class that are of class
5713 // type (or array thereof), each such class has a trivial [default
5714 // constructor or destructor]
5715 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5716 return false;
5717
5718 // C++11 [class.dtor]p5:
5719 // A destructor is trivial if [...]
5720 // -- the destructor is not virtual
5721 if (CSM == CXXDestructor && MD->isVirtual()) {
5722 if (Diagnose)
5723 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5724 return false;
5725 }
5726
5727 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5728 // A [special member] for class X is trivial if [...]
5729 // -- class X has no virtual functions and no virtual base classes
5730 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5731 if (!Diagnose)
5732 return false;
5733
5734 if (RD->getNumVBases()) {
5735 // Check for virtual bases. We already know that the corresponding
5736 // member in all bases is trivial, so vbases must all be direct.
5737 CXXBaseSpecifier &BS = *RD->vbases_begin();
5738 assert(BS.isVirtual());
5739 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5740 return false;
5741 }
5742
5743 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005744 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005745 if (MI->isVirtual()) {
5746 SourceLocation MLoc = MI->getLocStart();
5747 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5748 return false;
5749 }
5750 }
5751
5752 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5753 }
5754
5755 // Looks like it's trivial!
5756 return true;
5757}
5758
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005759/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005760namespace {
5761 struct FindHiddenVirtualMethodData {
5762 Sema *S;
5763 CXXMethodDecl *Method;
5764 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005765 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005766 };
5767}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005768
David Blaikie282c92a2012-10-19 00:53:08 +00005769/// \brief Check whether any most overriden method from MD in Methods
5770static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5771 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5772 if (MD->size_overridden_methods() == 0)
5773 return Methods.count(MD->getCanonicalDecl());
5774 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5775 E = MD->end_overridden_methods();
5776 I != E; ++I)
5777 if (CheckMostOverridenMethods(*I, Methods))
5778 return true;
5779 return false;
5780}
5781
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005782/// \brief Member lookup function that determines whether a given C++
5783/// method overloads virtual methods in a base class without overriding any,
5784/// to be used with CXXRecordDecl::lookupInBases().
5785static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5786 CXXBasePath &Path,
5787 void *UserData) {
5788 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5789
5790 FindHiddenVirtualMethodData &Data
5791 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5792
5793 DeclarationName Name = Data.Method->getDeclName();
5794 assert(Name.getNameKind() == DeclarationName::Identifier);
5795
5796 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005797 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005798 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005799 !Path.Decls.empty();
5800 Path.Decls = Path.Decls.slice(1)) {
5801 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005802 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005803 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005804 foundSameNameMethod = true;
5805 // Interested only in hidden virtual methods.
5806 if (!MD->isVirtual())
5807 continue;
5808 // If the method we are checking overrides a method from its base
5809 // don't warn about the other overloaded methods.
5810 if (!Data.S->IsOverload(Data.Method, MD, false))
5811 return true;
5812 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005813 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005814 overloadedMethods.push_back(MD);
5815 }
5816 }
5817
5818 if (foundSameNameMethod)
5819 Data.OverloadedMethods.append(overloadedMethods.begin(),
5820 overloadedMethods.end());
5821 return foundSameNameMethod;
5822}
5823
David Blaikie282c92a2012-10-19 00:53:08 +00005824/// \brief Add the most overriden methods from MD to Methods
5825static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5826 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5827 if (MD->size_overridden_methods() == 0)
5828 Methods.insert(MD->getCanonicalDecl());
5829 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5830 E = MD->end_overridden_methods();
5831 I != E; ++I)
5832 AddMostOverridenMethods(*I, Methods);
5833}
5834
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005835/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005836/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005837void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5838 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005839 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005840 return;
5841
5842 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5843 /*bool RecordPaths=*/false,
5844 /*bool DetectVirtual=*/false);
5845 FindHiddenVirtualMethodData Data;
5846 Data.Method = MD;
5847 Data.S = this;
5848
5849 // Keep the base methods that were overriden or introduced in the subclass
5850 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005851 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005852 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5853 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5854 NamedDecl *ND = *I;
5855 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005856 ND = shad->getTargetDecl();
5857 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5858 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005859 }
5860
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005861 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5862 OverloadedMethods = Data.OverloadedMethods;
5863}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005864
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005865void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5866 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5867 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5868 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5869 PartialDiagnostic PD = PDiag(
5870 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5871 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5872 Diag(overloadedMD->getLocation(), PD);
5873 }
5874}
5875
5876/// \brief Diagnose methods which overload virtual methods in a base class
5877/// without overriding any.
5878void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5879 if (MD->isInvalidDecl())
5880 return;
5881
5882 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5883 MD->getLocation()) == DiagnosticsEngine::Ignored)
5884 return;
5885
5886 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5887 FindHiddenVirtualMethods(MD, OverloadedMethods);
5888 if (!OverloadedMethods.empty()) {
5889 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5890 << MD << (OverloadedMethods.size() > 1);
5891
5892 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005893 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005894}
5895
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005896void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005897 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005898 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005899 SourceLocation RBrac,
5900 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005901 if (!TagDecl)
5902 return;
Mike Stump11289f42009-09-09 15:08:12 +00005903
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005904 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005905
Rafael Espindola06e1b132012-07-12 04:32:30 +00005906 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5907 if (l->getKind() != AttributeList::AT_Visibility)
5908 continue;
5909 l->setInvalid();
5910 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5911 l->getName();
5912 }
5913
David Blaikie751c5582011-09-22 02:58:26 +00005914 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005915 // strict aliasing violation!
5916 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005917 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005918
Douglas Gregor0be31a22010-07-02 17:43:08 +00005919 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005920 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005921}
5922
Douglas Gregor05379422008-11-03 17:51:48 +00005923/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5924/// special functions, such as the default constructor, copy
5925/// constructor, or destructor, to the given C++ class (C++
5926/// [special]p1). This routine can only be executed just before the
5927/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005928void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005929 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005930 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005931
Richard Smith6b02d462012-12-08 08:32:28 +00005932 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005933 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005934
Richard Smith6b02d462012-12-08 08:32:28 +00005935 // If the properties or semantics of the copy constructor couldn't be
5936 // determined while the class was being declared, force a declaration
5937 // of it now.
5938 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5939 DeclareImplicitCopyConstructor(ClassDecl);
5940 }
5941
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005942 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005943 ++ASTContext::NumImplicitMoveConstructors;
5944
Richard Smith6b02d462012-12-08 08:32:28 +00005945 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5946 DeclareImplicitMoveConstructor(ClassDecl);
5947 }
5948
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005949 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5950 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00005951
5952 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005953 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00005954 // it shows up in the right place in the vtable and that we diagnose
5955 // problems with the implicit exception specification.
5956 if (ClassDecl->isDynamicClass() ||
5957 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005958 DeclareImplicitCopyAssignment(ClassDecl);
5959 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005960
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005961 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005962 ++ASTContext::NumImplicitMoveAssignmentOperators;
5963
5964 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00005965 if (ClassDecl->isDynamicClass() ||
5966 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00005967 DeclareImplicitMoveAssignment(ClassDecl);
5968 }
5969
Douglas Gregor7454c562010-07-02 20:37:36 +00005970 if (!ClassDecl->hasUserDeclaredDestructor()) {
5971 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00005972
5973 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00005974 // have to declare the destructor immediately. This ensures that, e.g., it
5975 // shows up in the right place in the vtable and that we diagnose problems
5976 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00005977 if (ClassDecl->isDynamicClass() ||
5978 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00005979 DeclareImplicitDestructor(ClassDecl);
5980 }
Douglas Gregor05379422008-11-03 17:51:48 +00005981}
5982
Francois Pichet1c229c02011-04-22 22:18:13 +00005983void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5984 if (!D)
5985 return;
5986
5987 int NumParamList = D->getNumTemplateParameterLists();
5988 for (int i = 0; i < NumParamList; i++) {
5989 TemplateParameterList* Params = D->getTemplateParameterList(i);
5990 for (TemplateParameterList::iterator Param = Params->begin(),
5991 ParamEnd = Params->end();
5992 Param != ParamEnd; ++Param) {
5993 NamedDecl *Named = cast<NamedDecl>(*Param);
5994 if (Named->getDeclName()) {
5995 S->AddDecl(Named);
5996 IdResolver.AddDecl(Named);
5997 }
5998 }
5999 }
6000}
6001
John McCall48871652010-08-21 09:40:31 +00006002void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00006003 if (!D)
6004 return;
6005
6006 TemplateParameterList *Params = 0;
6007 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
6008 Params = Template->getTemplateParameters();
6009 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6010 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6011 Params = PartialSpec->getTemplateParameters();
6012 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006013 return;
6014
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006015 for (TemplateParameterList::iterator Param = Params->begin(),
6016 ParamEnd = Params->end();
6017 Param != ParamEnd; ++Param) {
6018 NamedDecl *Named = cast<NamedDecl>(*Param);
6019 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00006020 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006021 IdResolver.AddDecl(Named);
6022 }
6023 }
6024}
6025
John McCall48871652010-08-21 09:40:31 +00006026void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006027 if (!RecordD) return;
6028 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006029 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006030 PushDeclContext(S, Record);
6031}
6032
John McCall48871652010-08-21 09:40:31 +00006033void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006034 if (!RecordD) return;
6035 PopDeclContext();
6036}
6037
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006038/// This is used to implement the constant expression evaluation part of the
6039/// attribute enable_if extension. There is nothing in standard C++ which would
6040/// require reentering parameters.
6041void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6042 if (!Param)
6043 return;
6044
6045 S->AddDecl(Param);
6046 if (Param->getDeclName())
6047 IdResolver.AddDecl(Param);
6048}
6049
Douglas Gregor4d87df52008-12-16 21:30:33 +00006050/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6051/// parsing a top-level (non-nested) C++ class, and we are now
6052/// parsing those parts of the given Method declaration that could
6053/// not be parsed earlier (C++ [class.mem]p2), such as default
6054/// arguments. This action should enter the scope of the given
6055/// Method declaration as if we had just parsed the qualified method
6056/// name. However, it should not bring the parameters into scope;
6057/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006058void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006059}
6060
6061/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6062/// C++ method declaration. We're (re-)introducing the given
6063/// function parameter into scope for use in parsing later parts of
6064/// the method declaration. For example, we could see an
6065/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006066void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006067 if (!ParamD)
6068 return;
Mike Stump11289f42009-09-09 15:08:12 +00006069
John McCall48871652010-08-21 09:40:31 +00006070 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006071
6072 // If this parameter has an unparsed default argument, clear it out
6073 // to make way for the parsed default argument.
6074 if (Param->hasUnparsedDefaultArg())
6075 Param->setDefaultArg(0);
6076
John McCall48871652010-08-21 09:40:31 +00006077 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006078 if (Param->getDeclName())
6079 IdResolver.AddDecl(Param);
6080}
6081
6082/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6083/// processing the delayed method declaration for Method. The method
6084/// declaration is now considered finished. There may be a separate
6085/// ActOnStartOfFunctionDef action later (not necessarily
6086/// immediately!) for this method, if it was also defined inside the
6087/// class body.
John McCall48871652010-08-21 09:40:31 +00006088void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006089 if (!MethodD)
6090 return;
Mike Stump11289f42009-09-09 15:08:12 +00006091
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006092 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006093
John McCall48871652010-08-21 09:40:31 +00006094 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006095
6096 // Now that we have our default arguments, check the constructor
6097 // again. It could produce additional diagnostics or affect whether
6098 // the class has implicitly-declared destructors, among other
6099 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006100 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6101 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006102
6103 // Check the default arguments, which we may have added.
6104 if (!Method->isInvalidDecl())
6105 CheckCXXDefaultArguments(Method);
6106}
6107
Douglas Gregor831c93f2008-11-05 20:51:48 +00006108/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006109/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006110/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006111/// emit diagnostics and set the invalid bit to true. In any case, the type
6112/// will be updated to reflect a well-formed type for the constructor and
6113/// returned.
6114QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006115 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006116 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006117
6118 // C++ [class.ctor]p3:
6119 // A constructor shall not be virtual (10.3) or static (9.4). A
6120 // constructor can be invoked for a const, volatile or const
6121 // volatile object. A constructor shall not be declared const,
6122 // volatile, or const volatile (9.3.2).
6123 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006124 if (!D.isInvalidType())
6125 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6126 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6127 << SourceRange(D.getIdentifierLoc());
6128 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006129 }
John McCall8e7d6562010-08-26 03:08:43 +00006130 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006131 if (!D.isInvalidType())
6132 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6133 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6134 << SourceRange(D.getIdentifierLoc());
6135 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006136 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006137 }
Mike Stump11289f42009-09-09 15:08:12 +00006138
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006139 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006140 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006141 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006142 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6143 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006144 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006145 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6146 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006147 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006148 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6149 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006150 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006151 }
Mike Stump11289f42009-09-09 15:08:12 +00006152
Douglas Gregordb9d6642011-01-26 05:01:58 +00006153 // C++0x [class.ctor]p4:
6154 // A constructor shall not be declared with a ref-qualifier.
6155 if (FTI.hasRefQualifier()) {
6156 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6157 << FTI.RefQualifierIsLValueRef
6158 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6159 D.setInvalidType();
6160 }
6161
Douglas Gregor831c93f2008-11-05 20:51:48 +00006162 // Rebuild the function type "R" without any type qualifiers (in
6163 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006164 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006165 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006166 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006167 return R;
6168
6169 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6170 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006171 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006172
6173 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006174}
6175
Douglas Gregor4d87df52008-12-16 21:30:33 +00006176/// CheckConstructor - Checks a fully-formed constructor for
6177/// well-formedness, issuing any diagnostics required. Returns true if
6178/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006179void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006180 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006181 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6182 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006183 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006184
6185 // C++ [class.copy]p3:
6186 // A declaration of a constructor for a class X is ill-formed if
6187 // its first parameter is of type (optionally cv-qualified) X and
6188 // either there are no other parameters or else all other
6189 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006190 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006191 ((Constructor->getNumParams() == 1) ||
6192 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006193 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6194 Constructor->getTemplateSpecializationKind()
6195 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006196 QualType ParamType = Constructor->getParamDecl(0)->getType();
6197 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6198 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006199 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006200 const char *ConstRef
6201 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6202 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006203 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006204 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006205
6206 // FIXME: Rather that making the constructor invalid, we should endeavor
6207 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006208 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006209 }
6210 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006211}
6212
John McCalldeb646e2010-08-04 01:04:25 +00006213/// CheckDestructor - Checks a fully-formed destructor definition for
6214/// well-formedness, issuing any diagnostics required. Returns true
6215/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006216bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006217 CXXRecordDecl *RD = Destructor->getParent();
6218
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006219 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006220 SourceLocation Loc;
6221
6222 if (!Destructor->isImplicit())
6223 Loc = Destructor->getLocation();
6224 else
6225 Loc = RD->getLocation();
6226
6227 // If we have a virtual destructor, look up the deallocation function
6228 FunctionDecl *OperatorDelete = 0;
6229 DeclarationName Name =
6230 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006231 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006232 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006233 // If there's no class-specific operator delete, look up the global
6234 // non-array delete.
6235 if (!OperatorDelete)
6236 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006237
Eli Friedmanfa0df832012-02-02 03:46:19 +00006238 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006239
6240 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006241 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006242
6243 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006244}
6245
Mike Stump11289f42009-09-09 15:08:12 +00006246static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00006247FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
Alp Tokerc5350722014-02-26 22:27:52 +00006248 return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6249 FTI.Params[0].Param &&
6250 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00006251}
6252
Douglas Gregor831c93f2008-11-05 20:51:48 +00006253/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6254/// the well-formednes of the destructor declarator @p D with type @p
6255/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006256/// emit diagnostics and set the declarator to invalid. Even if this happens,
6257/// will be updated to reflect a well-formed type for the destructor and
6258/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006259QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006260 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006261 // C++ [class.dtor]p1:
6262 // [...] A typedef-name that names a class is a class-name
6263 // (7.1.3); however, a typedef-name that names a class shall not
6264 // be used as the identifier in the declarator for a destructor
6265 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006266 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006267 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006268 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006269 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006270 else if (const TemplateSpecializationType *TST =
6271 DeclaratorType->getAs<TemplateSpecializationType>())
6272 if (TST->isTypeAlias())
6273 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6274 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006275
6276 // C++ [class.dtor]p2:
6277 // A destructor is used to destroy objects of its class type. A
6278 // destructor takes no parameters, and no return type can be
6279 // specified for it (not even void). The address of a destructor
6280 // shall not be taken. A destructor shall not be static. A
6281 // destructor can be invoked for a const, volatile or const
6282 // volatile object. A destructor shall not be declared const,
6283 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006284 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006285 if (!D.isInvalidType())
6286 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6287 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006288 << SourceRange(D.getIdentifierLoc())
6289 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6290
John McCall8e7d6562010-08-26 03:08:43 +00006291 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006292 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006293 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006294 // Destructors don't have return types, but the parser will
6295 // happily parse something like:
6296 //
6297 // class X {
6298 // float ~X();
6299 // };
6300 //
6301 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006302 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6303 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6304 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006305 }
Mike Stump11289f42009-09-09 15:08:12 +00006306
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006307 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006308 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006309 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006310 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6311 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006312 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006313 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6314 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006315 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006316 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6317 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006318 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006319 }
6320
Douglas Gregordb9d6642011-01-26 05:01:58 +00006321 // C++0x [class.dtor]p2:
6322 // A destructor shall not be declared with a ref-qualifier.
6323 if (FTI.hasRefQualifier()) {
6324 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6325 << FTI.RefQualifierIsLValueRef
6326 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6327 D.setInvalidType();
6328 }
6329
Douglas Gregor831c93f2008-11-05 20:51:48 +00006330 // Make sure we don't have any parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006331 if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006332 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6333
6334 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006335 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006336 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006337 }
6338
Mike Stump11289f42009-09-09 15:08:12 +00006339 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006340 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006341 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006342 D.setInvalidType();
6343 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006344
6345 // Rebuild the function type "R" without any type qualifiers or
6346 // parameters (in case any of the errors above fired) and with
6347 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006348 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006349 if (!D.isInvalidType())
6350 return R;
6351
Douglas Gregor95755162010-07-01 05:10:53 +00006352 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006353 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6354 EPI.Variadic = false;
6355 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006356 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006357 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006358}
6359
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006360/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6361/// well-formednes of the conversion function declarator @p D with
6362/// type @p R. If there are any errors in the declarator, this routine
6363/// will emit diagnostics and return true. Otherwise, it will return
6364/// false. Either way, the type @p R will be updated to reflect a
6365/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006366void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006367 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006368 // C++ [class.conv.fct]p1:
6369 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006370 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006371 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006372 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006373 if (!D.isInvalidType())
6374 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006375 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6376 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006377 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006378 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006379 }
John McCall212fa2e2010-04-13 00:04:31 +00006380
6381 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6382
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006383 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006384 // Conversion functions don't have return types, but the parser will
6385 // happily parse something like:
6386 //
6387 // class X {
6388 // float operator bool();
6389 // };
6390 //
6391 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006392 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6393 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6394 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006395 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006396 }
6397
John McCall212fa2e2010-04-13 00:04:31 +00006398 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6399
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006400 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006401 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006402 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6403
6404 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006405 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006406 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006407 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006408 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006409 D.setInvalidType();
6410 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006411
John McCall212fa2e2010-04-13 00:04:31 +00006412 // Diagnose "&operator bool()" and other such nonsense. This
6413 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006414 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006415 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006416 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006417 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006418 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006419 }
6420
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006421 // C++ [class.conv.fct]p4:
6422 // The conversion-type-id shall not represent a function type nor
6423 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006424 if (ConvType->isArrayType()) {
6425 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6426 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006427 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006428 } else if (ConvType->isFunctionType()) {
6429 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6430 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006431 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006432 }
6433
6434 // Rebuild the function type "R" without any parameters (in case any
6435 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006436 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006437 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006438 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006439
Douglas Gregor5fb53972009-01-14 15:45:31 +00006440 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006441 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006442 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006443 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006444 diag::warn_cxx98_compat_explicit_conversion_functions :
6445 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006446 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006447}
6448
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006449/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6450/// the declaration of the given C++ conversion function. This routine
6451/// is responsible for recording the conversion function in the C++
6452/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006453Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006454 assert(Conversion && "Expected to receive a conversion function declaration");
6455
Douglas Gregor4287b372008-12-12 08:25:50 +00006456 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006457
6458 // Make sure we aren't redeclaring the conversion function.
6459 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006460
6461 // C++ [class.conv.fct]p1:
6462 // [...] A conversion function is never used to convert a
6463 // (possibly cv-qualified) object to the (possibly cv-qualified)
6464 // same object type (or a reference to it), to a (possibly
6465 // cv-qualified) base class of that type (or a reference to it),
6466 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006467 // FIXME: Suppress this warning if the conversion function ends up being a
6468 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006469 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006470 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006471 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006472 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006473 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6474 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006475 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006476 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006477 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6478 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006479 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006480 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006481 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006482 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006483 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006484 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006485 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006486 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006487 }
6488
Douglas Gregor457104e2010-09-29 04:25:11 +00006489 if (FunctionTemplateDecl *ConversionTemplate
6490 = Conversion->getDescribedFunctionTemplate())
6491 return ConversionTemplate;
6492
John McCall48871652010-08-21 09:40:31 +00006493 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006494}
6495
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006496//===----------------------------------------------------------------------===//
6497// Namespace Handling
6498//===----------------------------------------------------------------------===//
6499
Richard Smith45bb8852012-10-04 22:13:39 +00006500/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6501/// reopened.
6502static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6503 SourceLocation Loc,
6504 IdentifierInfo *II, bool *IsInline,
6505 NamespaceDecl *PrevNS) {
6506 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006507
Richard Smithf501cc32012-10-05 01:46:25 +00006508 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6509 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6510 // inline namespaces, with the intention of bringing names into namespace std.
6511 //
6512 // We support this just well enough to get that case working; this is not
6513 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006514 if (*IsInline && II && II->getName().startswith("__atomic") &&
6515 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006516 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006517 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6518 NS = NS->getPreviousDecl())
6519 NS->setInline(*IsInline);
6520 // Patch up the lookup table for the containing namespace. This isn't really
6521 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006522 for (auto *I : PrevNS->decls())
6523 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006524 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6525 return;
6526 }
6527
6528 if (PrevNS->isInline())
6529 // The user probably just forgot the 'inline', so suggest that it
6530 // be added back.
6531 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6532 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6533 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006534 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006535
6536 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6537 *IsInline = PrevNS->isInline();
6538}
John McCallb1be5232010-08-26 09:15:37 +00006539
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006540/// ActOnStartNamespaceDef - This is called at the start of a namespace
6541/// definition.
John McCall48871652010-08-21 09:40:31 +00006542Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006543 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006544 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006545 SourceLocation IdentLoc,
6546 IdentifierInfo *II,
6547 SourceLocation LBrace,
6548 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006549 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6550 // For anonymous namespace, take the location of the left brace.
6551 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006552 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006553 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006554 bool IsStd = false;
6555 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006556 Scope *DeclRegionScope = NamespcScope->getParent();
6557
Douglas Gregore57e7522012-01-07 09:11:48 +00006558 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006559 if (II) {
6560 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006561 // The identifier in an original-namespace-definition shall not
6562 // have been previously defined in the declarative region in
6563 // which the original-namespace-definition appears. The
6564 // identifier in an original-namespace-definition is the name of
6565 // the namespace. Subsequently in that declarative region, it is
6566 // treated as an original-namespace-name.
6567 //
6568 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006569 // look through using directives, just look for any ordinary names.
6570
6571 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006572 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6573 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006574 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006575 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6576 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6577 ++I) {
6578 if ((*I)->getIdentifierNamespace() & IDNS) {
6579 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006580 break;
6581 }
6582 }
6583
Douglas Gregore57e7522012-01-07 09:11:48 +00006584 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6585
6586 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006587 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006588 if (IsInline != PrevNS->isInline())
6589 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6590 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006591 } else if (PrevDecl) {
6592 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006593 Diag(Loc, diag::err_redefinition_different_kind)
6594 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006595 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006596 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006597 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006598 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006599 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006600 // This is the first "real" definition of the namespace "std", so update
6601 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006602 PrevNS = getStdNamespace();
6603 IsStd = true;
6604 AddToKnown = !IsInline;
6605 } else {
6606 // We've seen this namespace for the first time.
6607 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006608 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006609 } else {
John McCall4fa53422009-10-01 00:25:31 +00006610 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006611
6612 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006613 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006614 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006615 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006616 } else {
6617 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006618 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006619 }
6620
Richard Smith45bb8852012-10-04 22:13:39 +00006621 if (PrevNS && IsInline != PrevNS->isInline())
6622 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6623 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006624 }
6625
6626 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6627 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006628 if (IsInvalid)
6629 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006630
6631 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006632
Douglas Gregore57e7522012-01-07 09:11:48 +00006633 // FIXME: Should we be merging attributes?
6634 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006635 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006636
6637 if (IsStd)
6638 StdNamespace = Namespc;
6639 if (AddToKnown)
6640 KnownNamespaces[Namespc] = false;
6641
6642 if (II) {
6643 PushOnScopeChains(Namespc, DeclRegionScope);
6644 } else {
6645 // Link the anonymous namespace into its parent.
6646 DeclContext *Parent = CurContext->getRedeclContext();
6647 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6648 TU->setAnonymousNamespace(Namespc);
6649 } else {
6650 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006651 }
John McCall4fa53422009-10-01 00:25:31 +00006652
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006653 CurContext->addDecl(Namespc);
6654
John McCall4fa53422009-10-01 00:25:31 +00006655 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6656 // behaves as if it were replaced by
6657 // namespace unique { /* empty body */ }
6658 // using namespace unique;
6659 // namespace unique { namespace-body }
6660 // where all occurrences of 'unique' in a translation unit are
6661 // replaced by the same identifier and this identifier differs
6662 // from all other identifiers in the entire program.
6663
6664 // We just create the namespace with an empty name and then add an
6665 // implicit using declaration, just like the standard suggests.
6666 //
6667 // CodeGen enforces the "universally unique" aspect by giving all
6668 // declarations semantically contained within an anonymous
6669 // namespace internal linkage.
6670
Douglas Gregore57e7522012-01-07 09:11:48 +00006671 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006672 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006673 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006674 /* 'using' */ LBrace,
6675 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006676 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006677 /* identifier */ SourceLocation(),
6678 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006679 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006680 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006681 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006682 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006683 }
6684
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006685 ActOnDocumentableDecl(Namespc);
6686
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006687 // Although we could have an invalid decl (i.e. the namespace name is a
6688 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006689 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6690 // for the namespace has the declarations that showed up in that particular
6691 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006692 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006693 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006694}
6695
Sebastian Redla6602e92009-11-23 15:34:23 +00006696/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6697/// is a namespace alias, returns the namespace it points to.
6698static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6699 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6700 return AD->getNamespace();
6701 return dyn_cast_or_null<NamespaceDecl>(D);
6702}
6703
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006704/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6705/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006706void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006707 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6708 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006709 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006710 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006711 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006712 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006713}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006714
John McCall28a0cf72010-08-25 07:42:41 +00006715CXXRecordDecl *Sema::getStdBadAlloc() const {
6716 return cast_or_null<CXXRecordDecl>(
6717 StdBadAlloc.get(Context.getExternalSource()));
6718}
6719
6720NamespaceDecl *Sema::getStdNamespace() const {
6721 return cast_or_null<NamespaceDecl>(
6722 StdNamespace.get(Context.getExternalSource()));
6723}
6724
Douglas Gregorcdf87022010-06-29 17:53:46 +00006725/// \brief Retrieve the special "std" namespace, which may require us to
6726/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006727NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006728 if (!StdNamespace) {
6729 // The "std" namespace has not yet been defined, so build one implicitly.
6730 StdNamespace = NamespaceDecl::Create(Context,
6731 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006732 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006733 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006734 &PP.getIdentifierTable().get("std"),
6735 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006736 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006737 }
6738
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006739 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006740}
6741
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006742bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006743 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006744 "Looking for std::initializer_list outside of C++.");
6745
6746 // We're looking for implicit instantiations of
6747 // template <typename E> class std::initializer_list.
6748
6749 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6750 return false;
6751
Sebastian Redl43144e72012-01-17 22:49:58 +00006752 ClassTemplateDecl *Template = 0;
6753 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006754
Sebastian Redl43144e72012-01-17 22:49:58 +00006755 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006756
Sebastian Redl43144e72012-01-17 22:49:58 +00006757 ClassTemplateSpecializationDecl *Specialization =
6758 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6759 if (!Specialization)
6760 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006761
Sebastian Redl43144e72012-01-17 22:49:58 +00006762 Template = Specialization->getSpecializedTemplate();
6763 Arguments = Specialization->getTemplateArgs().data();
6764 } else if (const TemplateSpecializationType *TST =
6765 Ty->getAs<TemplateSpecializationType>()) {
6766 Template = dyn_cast_or_null<ClassTemplateDecl>(
6767 TST->getTemplateName().getAsTemplateDecl());
6768 Arguments = TST->getArgs();
6769 }
6770 if (!Template)
6771 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006772
6773 if (!StdInitializerList) {
6774 // Haven't recognized std::initializer_list yet, maybe this is it.
6775 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6776 if (TemplateClass->getIdentifier() !=
6777 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006778 !getStdNamespace()->InEnclosingNamespaceSetOf(
6779 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006780 return false;
6781 // This is a template called std::initializer_list, but is it the right
6782 // template?
6783 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006784 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006785 return false;
6786 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6787 return false;
6788
6789 // It's the right template.
6790 StdInitializerList = Template;
6791 }
6792
6793 if (Template != StdInitializerList)
6794 return false;
6795
6796 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006797 if (Element)
6798 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006799 return true;
6800}
6801
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006802static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6803 NamespaceDecl *Std = S.getStdNamespace();
6804 if (!Std) {
6805 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6806 return 0;
6807 }
6808
6809 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6810 Loc, Sema::LookupOrdinaryName);
6811 if (!S.LookupQualifiedName(Result, Std)) {
6812 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6813 return 0;
6814 }
6815 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6816 if (!Template) {
6817 Result.suppressDiagnostics();
6818 // We found something weird. Complain about the first thing we found.
6819 NamedDecl *Found = *Result.begin();
6820 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6821 return 0;
6822 }
6823
6824 // We found some template called std::initializer_list. Now verify that it's
6825 // correct.
6826 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006827 if (Params->getMinRequiredArguments() != 1 ||
6828 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006829 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6830 return 0;
6831 }
6832
6833 return Template;
6834}
6835
6836QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6837 if (!StdInitializerList) {
6838 StdInitializerList = LookupStdInitializerList(*this, Loc);
6839 if (!StdInitializerList)
6840 return QualType();
6841 }
6842
6843 TemplateArgumentListInfo Args(Loc, Loc);
6844 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6845 Context.getTrivialTypeSourceInfo(Element,
6846 Loc)));
6847 return Context.getCanonicalType(
6848 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6849}
6850
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006851bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6852 // C++ [dcl.init.list]p2:
6853 // A constructor is an initializer-list constructor if its first parameter
6854 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6855 // std::initializer_list<E> for some type E, and either there are no other
6856 // parameters or else all other parameters have default arguments.
6857 if (Ctor->getNumParams() < 1 ||
6858 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6859 return false;
6860
6861 QualType ArgType = Ctor->getParamDecl(0)->getType();
6862 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6863 ArgType = RT->getPointeeType().getUnqualifiedType();
6864
6865 return isStdInitializerList(ArgType, 0);
6866}
6867
Douglas Gregora172e082011-03-26 22:25:30 +00006868/// \brief Determine whether a using statement is in a context where it will be
6869/// apply in all contexts.
6870static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6871 switch (CurContext->getDeclKind()) {
6872 case Decl::TranslationUnit:
6873 return true;
6874 case Decl::LinkageSpec:
6875 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6876 default:
6877 return false;
6878 }
6879}
6880
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006881namespace {
6882
6883// Callback to only accept typo corrections that are namespaces.
6884class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006885public:
Craig Toppera798a9d2014-03-02 09:32:10 +00006886 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006887 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006888 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006889 return false;
6890 }
6891};
6892
6893}
6894
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006895static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6896 CXXScopeSpec &SS,
6897 SourceLocation IdentLoc,
6898 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006899 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006900 R.clear();
6901 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006902 R.getLookupKind(), Sc, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00006903 Validator,
6904 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006905 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006906 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6907 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006908 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006909 S.diagnoseTypo(Corrected,
6910 S.PDiag(diag::err_using_directive_member_suggest)
6911 << Ident << DC << DroppedSpecifier << SS.getRange(),
6912 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006913 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006914 S.diagnoseTypo(Corrected,
6915 S.PDiag(diag::err_using_directive_suggest) << Ident,
6916 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006917 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006918 R.addDecl(Corrected.getCorrectionDecl());
6919 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006920 }
6921 return false;
6922}
6923
John McCall48871652010-08-21 09:40:31 +00006924Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006925 SourceLocation UsingLoc,
6926 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006927 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006928 SourceLocation IdentLoc,
6929 IdentifierInfo *NamespcName,
6930 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006931 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6932 assert(NamespcName && "Invalid NamespcName.");
6933 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006934
6935 // This can only happen along a recovery path.
6936 while (S->getFlags() & Scope::TemplateParamScope)
6937 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006938 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006939
Douglas Gregor889ceb72009-02-03 19:21:40 +00006940 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006941 NestedNameSpecifier *Qualifier = 0;
6942 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00006943 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006944
Douglas Gregor34074322009-01-14 22:20:51 +00006945 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006946 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6947 LookupParsedName(R, S, &SS);
6948 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006949 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006950
Douglas Gregorcdf87022010-06-29 17:53:46 +00006951 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006952 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006953 // Allow "using namespace std;" or "using namespace ::std;" even if
6954 // "std" hasn't been defined yet, for GCC compatibility.
6955 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6956 NamespcName->isStr("std")) {
6957 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006958 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006959 R.resolveKind();
6960 }
6961 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006962 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006963 }
6964
John McCall9f3059a2009-10-09 21:13:30 +00006965 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006966 NamedDecl *Named = R.getFoundDecl();
6967 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6968 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006969 // C++ [namespace.udir]p1:
6970 // A using-directive specifies that the names in the nominated
6971 // namespace can be used in the scope in which the
6972 // using-directive appears after the using-directive. During
6973 // unqualified name lookup (3.4.1), the names appear as if they
6974 // were declared in the nearest enclosing namespace which
6975 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006976 // namespace. [Note: in this context, "contains" means "contains
6977 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006978
6979 // Find enclosing context containing both using-directive and
6980 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006981 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006982 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6983 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6984 CommonAncestor = CommonAncestor->getParent();
6985
Sebastian Redla6602e92009-11-23 15:34:23 +00006986 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006987 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006988 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006989
Douglas Gregora172e082011-03-26 22:25:30 +00006990 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00006991 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006992 Diag(IdentLoc, diag::warn_using_directive_in_header);
6993 }
6994
Douglas Gregor889ceb72009-02-03 19:21:40 +00006995 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006996 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006997 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006998 }
6999
Richard Smith54ecd982013-02-20 19:22:51 +00007000 if (UDir)
7001 ProcessDeclAttributeList(S, UDir, AttrList);
7002
John McCall48871652010-08-21 09:40:31 +00007003 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007004}
7005
7006void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007007 // If the scope has an associated entity and the using directive is at
7008 // namespace or translation unit scope, add the UsingDirectiveDecl into
7009 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007010 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007011 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007012 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007013 else
Richard Smith05afe5e2012-03-13 03:12:56 +00007014 // Otherwise, it is at block sope. The using-directives will affect lookup
7015 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007016 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007017}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007018
Douglas Gregorfec52632009-06-20 00:51:54 +00007019
John McCall48871652010-08-21 09:40:31 +00007020Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007021 AccessSpecifier AS,
7022 bool HasUsingKeyword,
7023 SourceLocation UsingLoc,
7024 CXXScopeSpec &SS,
7025 UnqualifiedId &Name,
7026 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007027 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007028 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007029 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007030
Douglas Gregor220f4272009-11-04 16:30:06 +00007031 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007032 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007033 case UnqualifiedId::IK_Identifier:
7034 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007035 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007036 case UnqualifiedId::IK_ConversionFunctionId:
7037 break;
7038
7039 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007040 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007041 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007042 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007043 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007044 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007045 diag::err_using_decl_constructor)
7046 << SS.getRange();
7047
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007048 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007049
John McCall48871652010-08-21 09:40:31 +00007050 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007051
7052 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007053 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007054 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007055 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007056
7057 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007058 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007059 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00007060 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007061 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007062
7063 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7064 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007065 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00007066 return 0;
John McCall3969e302009-12-08 07:46:18 +00007067
Richard Smithc2bc61b2013-03-18 21:12:30 +00007068 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007069 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007070 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007071 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7072 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007073 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007074 }
7075
Douglas Gregorc4356532010-12-16 00:46:58 +00007076 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7077 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7078 return 0;
7079
John McCall3f746822009-11-17 05:59:44 +00007080 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007081 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007082 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007083 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007084 if (UD)
7085 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007086
John McCall48871652010-08-21 09:40:31 +00007087 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007088}
7089
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007090/// \brief Determine whether a using declaration considers the given
7091/// declarations as "equivalent", e.g., if they are redeclarations of
7092/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007093static bool
7094IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7095 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007096 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007097
Richard Smithdda56e42011-04-15 14:24:37 +00007098 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007099 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007100 return Context.hasSameType(TD1->getUnderlyingType(),
7101 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007102
7103 return false;
7104}
7105
7106
John McCall84d87672009-12-10 09:41:52 +00007107/// Determines whether to create a using shadow decl for a particular
7108/// decl, given the set of decls existing prior to this using lookup.
7109bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007110 const LookupResult &Previous,
7111 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007112 // Diagnose finding a decl which is not from a base class of the
7113 // current class. We do this now because there are cases where this
7114 // function will silently decide not to build a shadow decl, which
7115 // will pre-empt further diagnostics.
7116 //
7117 // We don't need to do this in C++0x because we do the check once on
7118 // the qualifier.
7119 //
7120 // FIXME: diagnose the following if we care enough:
7121 // struct A { int foo; };
7122 // struct B : A { using A::foo; };
7123 // template <class T> struct C : A {};
7124 // template <class T> struct D : C<T> { using B::foo; } // <---
7125 // This is invalid (during instantiation) in C++03 because B::foo
7126 // resolves to the using decl in B, which is not a base class of D<T>.
7127 // We can't diagnose it immediately because C<T> is an unknown
7128 // specialization. The UsingShadowDecl in D<T> then points directly
7129 // to A::foo, which will look well-formed when we instantiate.
7130 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007131 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007132 DeclContext *OrigDC = Orig->getDeclContext();
7133
7134 // Handle enums and anonymous structs.
7135 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7136 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7137 while (OrigRec->isAnonymousStructOrUnion())
7138 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7139
7140 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7141 if (OrigDC == CurContext) {
7142 Diag(Using->getLocation(),
7143 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007144 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007145 Diag(Orig->getLocation(), diag::note_using_decl_target);
7146 return true;
7147 }
7148
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007149 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007150 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007151 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007152 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007153 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007154 Diag(Orig->getLocation(), diag::note_using_decl_target);
7155 return true;
7156 }
7157 }
7158
7159 if (Previous.empty()) return false;
7160
7161 NamedDecl *Target = Orig;
7162 if (isa<UsingShadowDecl>(Target))
7163 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7164
John McCalla17e83e2009-12-11 02:33:26 +00007165 // If the target happens to be one of the previous declarations, we
7166 // don't have a conflict.
7167 //
7168 // FIXME: but we might be increasing its access, in which case we
7169 // should redeclare it.
7170 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithfd8634a2013-10-23 02:17:46 +00007171 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007172 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7173 I != E; ++I) {
7174 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007175 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7176 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7177 PrevShadow = Shadow;
7178 FoundEquivalentDecl = true;
7179 }
John McCalla17e83e2009-12-11 02:33:26 +00007180
7181 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7182 }
7183
Richard Smithfd8634a2013-10-23 02:17:46 +00007184 if (FoundEquivalentDecl)
7185 return false;
7186
Alp Tokera2794f92014-01-22 07:29:52 +00007187 if (FunctionDecl *FD = Target->getAsFunction()) {
John McCall84d87672009-12-10 09:41:52 +00007188 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00007189 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007190 case Ovl_Overload:
7191 return false;
7192
7193 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007194 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007195 break;
Richard Smith18819302014-02-06 01:31:33 +00007196
John McCall84d87672009-12-10 09:41:52 +00007197 // We found a decl with the exact signature.
7198 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007199 // If we're in a record, we want to hide the target, so we
7200 // return true (without a diagnostic) to tell the caller not to
7201 // build a shadow decl.
7202 if (CurContext->isRecord())
7203 return true;
7204
7205 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007206 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007207 break;
7208 }
7209
7210 Diag(Target->getLocation(), diag::note_using_decl_target);
7211 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7212 return true;
7213 }
7214
7215 // Target is not a function.
7216
John McCall84d87672009-12-10 09:41:52 +00007217 if (isa<TagDecl>(Target)) {
7218 // No conflict between a tag and a non-tag.
7219 if (!Tag) return false;
7220
John McCalle29c5cd2009-12-10 19:51:03 +00007221 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007222 Diag(Target->getLocation(), diag::note_using_decl_target);
7223 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7224 return true;
7225 }
7226
7227 // No conflict between a tag and a non-tag.
7228 if (!NonTag) return false;
7229
John McCalle29c5cd2009-12-10 19:51:03 +00007230 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007231 Diag(Target->getLocation(), diag::note_using_decl_target);
7232 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7233 return true;
7234}
7235
John McCall3f746822009-11-17 05:59:44 +00007236/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007237UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007238 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007239 NamedDecl *Orig,
7240 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007241
7242 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007243 NamedDecl *Target = Orig;
7244 if (isa<UsingShadowDecl>(Target)) {
7245 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7246 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007247 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007248
John McCall3f746822009-11-17 05:59:44 +00007249 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007250 = UsingShadowDecl::Create(Context, CurContext,
7251 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007252 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007253
Douglas Gregor457104e2010-09-29 04:25:11 +00007254 Shadow->setAccess(UD->getAccess());
7255 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7256 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007257
7258 Shadow->setPreviousDecl(PrevDecl);
7259
John McCall3f746822009-11-17 05:59:44 +00007260 if (S)
John McCall3969e302009-12-08 07:46:18 +00007261 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007262 else
John McCall3969e302009-12-08 07:46:18 +00007263 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007264
John McCall3969e302009-12-08 07:46:18 +00007265
John McCall84d87672009-12-10 09:41:52 +00007266 return Shadow;
7267}
John McCall3969e302009-12-08 07:46:18 +00007268
John McCall84d87672009-12-10 09:41:52 +00007269/// Hides a using shadow declaration. This is required by the current
7270/// using-decl implementation when a resolvable using declaration in a
7271/// class is followed by a declaration which would hide or override
7272/// one or more of the using decl's targets; for example:
7273///
7274/// struct Base { void foo(int); };
7275/// struct Derived : Base {
7276/// using Base::foo;
7277/// void foo(int);
7278/// };
7279///
7280/// The governing language is C++03 [namespace.udecl]p12:
7281///
7282/// When a using-declaration brings names from a base class into a
7283/// derived class scope, member functions in the derived class
7284/// override and/or hide member functions with the same name and
7285/// parameter types in a base class (rather than conflicting).
7286///
7287/// There are two ways to implement this:
7288/// (1) optimistically create shadow decls when they're not hidden
7289/// by existing declarations, or
7290/// (2) don't create any shadow decls (or at least don't make them
7291/// visible) until we've fully parsed/instantiated the class.
7292/// The problem with (1) is that we might have to retroactively remove
7293/// a shadow decl, which requires several O(n) operations because the
7294/// decl structures are (very reasonably) not designed for removal.
7295/// (2) avoids this but is very fiddly and phase-dependent.
7296void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007297 if (Shadow->getDeclName().getNameKind() ==
7298 DeclarationName::CXXConversionFunctionName)
7299 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7300
John McCall84d87672009-12-10 09:41:52 +00007301 // Remove it from the DeclContext...
7302 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007303
John McCall84d87672009-12-10 09:41:52 +00007304 // ...and the scope, if applicable...
7305 if (S) {
John McCall48871652010-08-21 09:40:31 +00007306 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007307 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007308 }
7309
John McCall84d87672009-12-10 09:41:52 +00007310 // ...and the using decl.
7311 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7312
7313 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007314 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007315}
7316
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007317namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007318class UsingValidatorCCC : public CorrectionCandidateCallback {
7319public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007320 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7321 bool RequireMember)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007322 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007323 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007324
Craig Toppera798a9d2014-03-02 09:32:10 +00007325 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007326 NamedDecl *ND = Candidate.getCorrectionDecl();
7327
7328 // Keywords are not valid here.
7329 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007330 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007331
Richard Smith30a615d2014-04-30 17:40:35 +00007332 // FIXME: We should check if ND is member of base class of class having
7333 // using declaration and direct base class in case using declaration names
7334 // a constructor.
7335 if (RequireMember && !ND->isCXXClassMember())
7336 return false;
7337
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007338 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7339 !isa<TypeDecl>(ND))
7340 return false;
7341
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007342 // Completely unqualified names are invalid for a 'using' declaration.
7343 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7344 return false;
7345
7346 if (isa<TypeDecl>(ND))
7347 return HasTypenameKeyword || !IsInstantiation;
7348
7349 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007350 }
7351
7352private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007353 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007354 bool IsInstantiation;
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007355 bool RequireMember;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007356};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007357} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007358
John McCalle61f2ba2009-11-18 02:36:19 +00007359/// Builds a using declaration.
7360///
7361/// \param IsInstantiation - Whether this call arises from an
7362/// instantiation of an unresolved using declaration. We treat
7363/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007364NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7365 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007366 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007367 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007368 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007369 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007370 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007371 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007372 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007373 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007374 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007375
Anders Carlssonf038fc22009-08-28 05:49:21 +00007376 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007377
Anders Carlsson59140b32009-08-28 03:16:11 +00007378 if (SS.isEmpty()) {
7379 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007380 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007381 }
Mike Stump11289f42009-09-09 15:08:12 +00007382
John McCall84d87672009-12-10 09:41:52 +00007383 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007384 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007385 ForRedeclaration);
7386 Previous.setHideTags(false);
7387 if (S) {
7388 LookupName(Previous, S);
7389
7390 // It is really dumb that we have to do this.
7391 LookupResult::Filter F = Previous.makeFilter();
7392 while (F.hasNext()) {
7393 NamedDecl *D = F.next();
7394 if (!isDeclInScope(D, CurContext, S))
7395 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007396 // If we found a local extern declaration that's not ordinarily visible,
7397 // and this declaration is being added to a non-block scope, ignore it.
7398 // We're only checking for scope conflicts here, not also for violations
7399 // of the linkage rules.
7400 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7401 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7402 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007403 }
7404 F.done();
7405 } else {
7406 assert(IsInstantiation && "no scope in non-instantiation");
7407 assert(CurContext->isRecord() && "scope not record in instantiation");
7408 LookupQualifiedName(Previous, CurContext);
7409 }
7410
John McCall84d87672009-12-10 09:41:52 +00007411 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007412 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7413 SS, IdentLoc, Previous))
John McCall84d87672009-12-10 09:41:52 +00007414 return 0;
7415
7416 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007417 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
John McCallb96ec562009-12-04 22:46:56 +00007418 return 0;
7419
John McCall84c16cf2009-11-12 03:15:40 +00007420 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007421 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007422 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007423 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007424 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007425 // FIXME: not all declaration name kinds are legal here
7426 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7427 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007428 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007429 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007430 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007431 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7432 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007433 }
John McCallb96ec562009-12-04 22:46:56 +00007434 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007435 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007436 NameInfo, HasTypenameKeyword);
Anders Carlssonf038fc22009-08-28 05:49:21 +00007437 }
John McCallb96ec562009-12-04 22:46:56 +00007438 D->setAccess(AS);
7439 CurContext->addDecl(D);
7440
7441 if (!LookupContext) return D;
7442 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00007443
John McCall0b66eb32010-05-01 00:40:08 +00007444 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00007445 UD->setInvalidDecl();
7446 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00007447 }
7448
Richard Smith23d55872012-04-02 01:30:27 +00007449 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007450 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith23d55872012-04-02 01:30:27 +00007451 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlc1f8e492011-03-12 13:44:32 +00007452 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007453 return UD;
7454 }
7455
7456 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007457
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007458 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007459
John McCall3969e302009-12-08 07:46:18 +00007460 // Unlike most lookups, we don't always want to hide tag
7461 // declarations: tag names are visible through the using declaration
7462 // even if hidden by ordinary names, *except* in a dependent context
7463 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007464 if (!IsInstantiation)
7465 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007466
John McCall5dadb652012-04-07 03:04:20 +00007467 // For the purposes of this lookup, we have a base object type
7468 // equal to that of the current context.
7469 if (CurContext->isRecord()) {
7470 R.setBaseObjectType(
7471 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7472 }
7473
John McCall27b18f82009-11-17 02:14:36 +00007474 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007475
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007476 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007477 if (R.empty()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007478 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7479 CurContext->isRecord());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007480 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
John Thompson2255f2c2014-04-23 12:57:01 +00007481 R.getLookupKind(), S, &SS, CCC,
7482 CTK_ErrorRecovery)){
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007483 // We reject any correction for which ND would be NULL.
7484 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007485 R.setLookupName(Corrected.getCorrection());
7486 R.addDecl(ND);
Richard Smithf9b15102013-08-17 00:46:16 +00007487 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007488 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007489 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7490 << NameInfo.getName() << LookupContext << 0
7491 << SS.getRange());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007492 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007493 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007494 << NameInfo.getName() << LookupContext << SS.getRange();
7495 UD->setInvalidDecl();
7496 return UD;
7497 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007498 }
7499
John McCallb96ec562009-12-04 22:46:56 +00007500 if (R.isAmbiguous()) {
7501 UD->setInvalidDecl();
7502 return UD;
7503 }
Mike Stump11289f42009-09-09 15:08:12 +00007504
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007505 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007506 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007507 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007508 Diag(IdentLoc, diag::err_using_typename_non_type);
7509 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7510 Diag((*I)->getUnderlyingDecl()->getLocation(),
7511 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007512 UD->setInvalidDecl();
7513 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007514 }
7515 } else {
7516 // If we asked for a non-typename and we got a type, error out,
7517 // but only if this is an instantiation of an unresolved using
7518 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007519 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007520 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7521 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007522 UD->setInvalidDecl();
7523 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007524 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007525 }
7526
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007527 // C++0x N2914 [namespace.udecl]p6:
7528 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007529 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007530 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7531 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007532 UD->setInvalidDecl();
7533 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007534 }
Mike Stump11289f42009-09-09 15:08:12 +00007535
John McCall84d87672009-12-10 09:41:52 +00007536 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithfd8634a2013-10-23 02:17:46 +00007537 UsingShadowDecl *PrevDecl = 0;
7538 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7539 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007540 }
John McCall3f746822009-11-17 05:59:44 +00007541
7542 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007543}
7544
Sebastian Redl08905022011-02-05 19:23:19 +00007545/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007546bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007547 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007548
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007549 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007550 assert(SourceType &&
7551 "Using decl naming constructor doesn't have type in scope spec.");
7552 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7553
7554 // Check whether the named type is a direct base class.
7555 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7556 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7557 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7558 BaseIt != BaseE; ++BaseIt) {
7559 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7560 if (CanonicalSourceType == BaseType)
7561 break;
Richard Smith23d55872012-04-02 01:30:27 +00007562 if (BaseIt->getType()->isDependentType())
7563 break;
Sebastian Redl08905022011-02-05 19:23:19 +00007564 }
7565
7566 if (BaseIt == BaseE) {
7567 // Did not find SourceType in the bases.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007568 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007569 diag::err_using_decl_constructor_not_in_direct_base)
7570 << UD->getNameInfo().getSourceRange()
7571 << QualType(SourceType, 0) << TargetClass;
7572 return true;
7573 }
7574
Richard Smith23d55872012-04-02 01:30:27 +00007575 if (!CurContext->isDependentContext())
7576 BaseIt->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007577
7578 return false;
7579}
7580
John McCall84d87672009-12-10 09:41:52 +00007581/// Checks that the given using declaration is not an invalid
7582/// redeclaration. Note that this is checking only for the using decl
7583/// itself, not for any ill-formedness among the UsingShadowDecls.
7584bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007585 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007586 const CXXScopeSpec &SS,
7587 SourceLocation NameLoc,
7588 const LookupResult &Prev) {
7589 // C++03 [namespace.udecl]p8:
7590 // C++0x [namespace.udecl]p10:
7591 // A using-declaration is a declaration and can therefore be used
7592 // repeatedly where (and only where) multiple declarations are
7593 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007594 //
John McCall032092f2010-11-29 18:01:58 +00007595 // That's in non-member contexts.
7596 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007597 return false;
7598
Aaron Ballman4a979672014-01-03 13:56:08 +00007599 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007600
7601 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7602 NamedDecl *D = *I;
7603
7604 bool DTypename;
7605 NestedNameSpecifier *DQual;
7606 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007607 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007608 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007609 } else if (UnresolvedUsingValueDecl *UD
7610 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7611 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007612 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007613 } else if (UnresolvedUsingTypenameDecl *UD
7614 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7615 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007616 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007617 } else continue;
7618
7619 // using decls differ if one says 'typename' and the other doesn't.
7620 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007621 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007622
7623 // using decls differ if they name different scopes (but note that
7624 // template instantiation can cause this check to trigger when it
7625 // didn't before instantiation).
7626 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7627 Context.getCanonicalNestedNameSpecifier(DQual))
7628 continue;
7629
7630 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007631 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007632 return true;
7633 }
7634
7635 return false;
7636}
7637
John McCall3969e302009-12-08 07:46:18 +00007638
John McCallb96ec562009-12-04 22:46:56 +00007639/// Checks that the given nested-name qualifier used in a using decl
7640/// in the current context is appropriately related to the current
7641/// scope. If an error is found, diagnoses it and returns true.
7642bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7643 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00007644 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00007645 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007646 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007647
John McCall3969e302009-12-08 07:46:18 +00007648 if (!CurContext->isRecord()) {
7649 // C++03 [namespace.udecl]p3:
7650 // C++0x [namespace.udecl]p8:
7651 // A using-declaration for a class member shall be a member-declaration.
7652
7653 // If we weren't able to compute a valid scope, it must be a
7654 // dependent class scope.
7655 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00007656 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7657 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
7658 RD = 0;
7659
John McCall3969e302009-12-08 07:46:18 +00007660 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7661 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00007662
7663 // If we have a complete, non-dependent source type, try to suggest a
7664 // way to get the same effect.
7665 if (!RD)
7666 return true;
7667
7668 // Find what this using-declaration was referring to.
7669 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7670 R.setHideTags(false);
7671 R.suppressDiagnostics();
7672 LookupQualifiedName(R, RD);
7673
7674 if (R.getAsSingle<TypeDecl>()) {
7675 if (getLangOpts().CPlusPlus11) {
7676 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7677 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7678 << 0 // alias declaration
7679 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7680 NameInfo.getName().getAsString() +
7681 " = ");
7682 } else {
7683 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7684 SourceLocation InsertLoc =
7685 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7686 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7687 << 1 // typedef declaration
7688 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7689 << FixItHint::CreateInsertion(
7690 InsertLoc, " " + NameInfo.getName().getAsString());
7691 }
7692 } else if (R.getAsSingle<VarDecl>()) {
7693 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7694 // repeating the type of the static data member here.
7695 FixItHint FixIt;
7696 if (getLangOpts().CPlusPlus11) {
7697 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7698 FixIt = FixItHint::CreateReplacement(
7699 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7700 }
7701
7702 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7703 << 2 // reference declaration
7704 << FixIt;
7705 }
John McCall3969e302009-12-08 07:46:18 +00007706 return true;
7707 }
7708
7709 // Otherwise, everything is known to be fine.
7710 return false;
7711 }
7712
7713 // The current scope is a record.
7714
7715 // If the named context is dependent, we can't decide much.
7716 if (!NamedContext) {
7717 // FIXME: in C++0x, we can diagnose if we can prove that the
7718 // nested-name-specifier does not refer to a base class, which is
7719 // still possible in some cases.
7720
7721 // Otherwise we have to conservatively report that things might be
7722 // okay.
7723 return false;
7724 }
7725
7726 if (!NamedContext->isRecord()) {
7727 // Ideally this would point at the last name in the specifier,
7728 // but we don't have that level of source info.
7729 Diag(SS.getRange().getBegin(),
7730 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007731 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007732 return true;
7733 }
7734
Douglas Gregor7c842292010-12-21 07:41:49 +00007735 if (!NamedContext->isDependentContext() &&
7736 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7737 return true;
7738
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007739 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007740 // C++0x [namespace.udecl]p3:
7741 // In a using-declaration used as a member-declaration, the
7742 // nested-name-specifier shall name a base class of the class
7743 // being defined.
7744
7745 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7746 cast<CXXRecordDecl>(NamedContext))) {
7747 if (CurContext == NamedContext) {
7748 Diag(NameLoc,
7749 diag::err_using_decl_nested_name_specifier_is_current_class)
7750 << SS.getRange();
7751 return true;
7752 }
7753
7754 Diag(SS.getRange().getBegin(),
7755 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007756 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007757 << cast<CXXRecordDecl>(CurContext)
7758 << SS.getRange();
7759 return true;
7760 }
7761
7762 return false;
7763 }
7764
7765 // C++03 [namespace.udecl]p4:
7766 // A using-declaration used as a member-declaration shall refer
7767 // to a member of a base class of the class being defined [etc.].
7768
7769 // Salient point: SS doesn't have to name a base class as long as
7770 // lookup only finds members from base classes. Therefore we can
7771 // diagnose here only if we can prove that that can't happen,
7772 // i.e. if the class hierarchies provably don't intersect.
7773
7774 // TODO: it would be nice if "definitely valid" results were cached
7775 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7776 // need to be repeated.
7777
7778 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007779 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007780
7781 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7782 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7783 Data->Bases.insert(Base);
7784 return true;
7785 }
7786
7787 bool hasDependentBases(const CXXRecordDecl *Class) {
7788 return !Class->forallBases(collect, this);
7789 }
7790
7791 /// Returns true if the base is dependent or is one of the
7792 /// accumulated base classes.
7793 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7794 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7795 return !Data->Bases.count(Base);
7796 }
7797
7798 bool mightShareBases(const CXXRecordDecl *Class) {
7799 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7800 }
7801 };
7802
7803 UserData Data;
7804
7805 // Returns false if we find a dependent base.
7806 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7807 return false;
7808
7809 // Returns false if the class has a dependent base or if it or one
7810 // of its bases is present in the base set of the current context.
7811 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7812 return false;
7813
7814 Diag(SS.getRange().getBegin(),
7815 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007816 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007817 << cast<CXXRecordDecl>(CurContext)
7818 << SS.getRange();
7819
7820 return true;
John McCallb96ec562009-12-04 22:46:56 +00007821}
7822
Richard Smithdda56e42011-04-15 14:24:37 +00007823Decl *Sema::ActOnAliasDeclaration(Scope *S,
7824 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007825 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007826 SourceLocation UsingLoc,
7827 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007828 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007829 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007830 // Skip up to the relevant declaration scope.
7831 while (S->getFlags() & Scope::TemplateParamScope)
7832 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007833 assert((S->getFlags() & Scope::DeclScope) &&
7834 "got alias-declaration outside of declaration scope");
7835
7836 if (Type.isInvalid())
7837 return 0;
7838
7839 bool Invalid = false;
7840 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7841 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007842 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007843
7844 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7845 return 0;
7846
7847 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007848 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007849 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007850 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7851 TInfo->getTypeLoc().getBeginLoc());
7852 }
Richard Smithdda56e42011-04-15 14:24:37 +00007853
7854 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7855 LookupName(Previous, S);
7856
7857 // Warn about shadowing the name of a template parameter.
7858 if (Previous.isSingleResult() &&
7859 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007860 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007861 Previous.clear();
7862 }
7863
7864 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7865 "name in alias declaration must be an identifier");
7866 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7867 Name.StartLocation,
7868 Name.Identifier, TInfo);
7869
7870 NewTD->setAccess(AS);
7871
7872 if (Invalid)
7873 NewTD->setInvalidDecl();
7874
Richard Smith54ecd982013-02-20 19:22:51 +00007875 ProcessDeclAttributeList(S, NewTD, AttrList);
7876
Richard Smith3f1b5d02011-05-05 21:57:07 +00007877 CheckTypedefForVariablyModifiedType(S, NewTD);
7878 Invalid |= NewTD->isInvalidDecl();
7879
Richard Smithdda56e42011-04-15 14:24:37 +00007880 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007881
7882 NamedDecl *NewND;
7883 if (TemplateParamLists.size()) {
7884 TypeAliasTemplateDecl *OldDecl = 0;
7885 TemplateParameterList *OldTemplateParams = 0;
7886
7887 if (TemplateParamLists.size() != 1) {
7888 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007889 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7890 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007891 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007892 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007893
7894 // Only consider previous declarations in the same scope.
7895 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7896 /*ExplicitInstantiationOrSpecialization*/false);
7897 if (!Previous.empty()) {
7898 Redeclaration = true;
7899
7900 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7901 if (!OldDecl && !Invalid) {
7902 Diag(UsingLoc, diag::err_redefinition_different_kind)
7903 << Name.Identifier;
7904
7905 NamedDecl *OldD = Previous.getRepresentativeDecl();
7906 if (OldD->getLocation().isValid())
7907 Diag(OldD->getLocation(), diag::note_previous_definition);
7908
7909 Invalid = true;
7910 }
7911
7912 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7913 if (TemplateParameterListsAreEqual(TemplateParams,
7914 OldDecl->getTemplateParameters(),
7915 /*Complain=*/true,
7916 TPL_TemplateMatch))
7917 OldTemplateParams = OldDecl->getTemplateParameters();
7918 else
7919 Invalid = true;
7920
7921 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7922 if (!Invalid &&
7923 !Context.hasSameType(OldTD->getUnderlyingType(),
7924 NewTD->getUnderlyingType())) {
7925 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7926 // but we can't reasonably accept it.
7927 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7928 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7929 if (OldTD->getLocation().isValid())
7930 Diag(OldTD->getLocation(), diag::note_previous_definition);
7931 Invalid = true;
7932 }
7933 }
7934 }
7935
7936 // Merge any previous default template arguments into our parameters,
7937 // and check the parameter list.
7938 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7939 TPC_TypeAliasTemplate))
7940 return 0;
7941
7942 TypeAliasTemplateDecl *NewDecl =
7943 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7944 Name.Identifier, TemplateParams,
7945 NewTD);
7946
7947 NewDecl->setAccess(AS);
7948
7949 if (Invalid)
7950 NewDecl->setInvalidDecl();
7951 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00007952 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007953
7954 NewND = NewDecl;
7955 } else {
7956 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7957 NewND = NewTD;
7958 }
Richard Smithdda56e42011-04-15 14:24:37 +00007959
7960 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00007961 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00007962
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00007963 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007964 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00007965}
7966
John McCall48871652010-08-21 09:40:31 +00007967Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007968 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00007969 SourceLocation AliasLoc,
7970 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007971 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007972 SourceLocation IdentLoc,
7973 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00007974
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007975 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007976 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7977 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007978
Anders Carlssondca83c42009-03-28 06:23:46 +00007979 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00007980 NamedDecl *PrevDecl
7981 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7982 ForRedeclaration);
7983 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7984 PrevDecl = 0;
7985
7986 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007987 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00007988 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007989 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00007990 // FIXME: At some point, we'll want to create the (redundant)
7991 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00007992 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00007993 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00007994 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007995 }
Mike Stump11289f42009-09-09 15:08:12 +00007996
Anders Carlssondca83c42009-03-28 06:23:46 +00007997 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7998 diag::err_redefinition_different_kind;
7999 Diag(AliasLoc, DiagID) << Alias;
8000 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00008001 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00008002 }
8003
John McCall27b18f82009-11-17 02:14:36 +00008004 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00008005 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00008006
John McCall9f3059a2009-10-09 21:13:30 +00008007 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008008 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008009 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00008010 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008011 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008012 }
Mike Stump11289f42009-09-09 15:08:12 +00008013
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008014 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008015 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008016 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008017 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008018
John McCalld8d0d432010-02-16 06:53:13 +00008019 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008020 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008021}
8022
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008023Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008024Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8025 CXXMethodDecl *MD) {
8026 CXXRecordDecl *ClassDecl = MD->getParent();
8027
Douglas Gregor6d880b12010-07-01 22:31:05 +00008028 // C++ [except.spec]p14:
8029 // An implicitly declared special member function (Clause 12) shall have an
8030 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008031 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008032 if (ClassDecl->isInvalidDecl())
8033 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008034
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008035 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008036 for (const auto &B : ClassDecl->bases()) {
8037 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008038 continue;
8039
Aaron Ballman574705e2014-03-13 15:41:46 +00008040 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008041 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008042 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8043 // If this is a deleted function, add it anyway. This might be conformant
8044 // with the standard. This might not. I'm not sure. It might not matter.
8045 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008046 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008047 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008048 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008049
8050 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008051 for (const auto &B : ClassDecl->vbases()) {
8052 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008053 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008054 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8055 // If this is a deleted function, add it anyway. This might be conformant
8056 // with the standard. This might not. I'm not sure. It might not matter.
8057 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008058 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008059 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008060 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008061
8062 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008063 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008064 if (F->hasInClassInitializer()) {
8065 if (Expr *E = F->getInClassInitializer())
8066 ExceptSpec.CalledExpr(E);
8067 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008068 // DR1351:
8069 // If the brace-or-equal-initializer of a non-static data member
8070 // invokes a defaulted default constructor of its class or of an
8071 // enclosing class in a potentially evaluated subexpression, the
8072 // program is ill-formed.
8073 //
8074 // This resolution is unworkable: the exception specification of the
8075 // default constructor can be needed in an unevaluated context, in
8076 // particular, in the operand of a noexcept-expression, and we can be
8077 // unable to compute an exception specification for an enclosed class.
8078 //
8079 // We do not allow an in-class initializer to require the evaluation
8080 // of the exception specification for any in-class initializer whose
8081 // definition is not lexically complete.
8082 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008083 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008084 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008085 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8086 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8087 // If this is a deleted function, add it anyway. This might be conformant
8088 // with the standard. This might not. I'm not sure. It might not matter.
8089 // In particular, the problem is that this function never gets called. It
8090 // might just be ill-formed because this function attempts to refer to
8091 // a deleted function here.
8092 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008093 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008094 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008095 }
John McCalldb40c7f2010-12-14 08:05:40 +00008096
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008097 return ExceptSpec;
8098}
8099
Richard Smithc2bc61b2013-03-18 21:12:30 +00008100Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008101Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8102 CXXRecordDecl *ClassDecl = CD->getParent();
8103
8104 // C++ [except.spec]p14:
8105 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008106 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008107 if (ClassDecl->isInvalidDecl())
8108 return ExceptSpec;
8109
8110 // Inherited constructor.
8111 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8112 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8113 // FIXME: Copying or moving the parameters could add extra exceptions to the
8114 // set, as could the default arguments for the inherited constructor. This
8115 // will be addressed when we implement the resolution of core issue 1351.
8116 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8117
8118 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008119 for (const auto &B : ClassDecl->bases()) {
8120 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008121 continue;
8122
Aaron Ballman574705e2014-03-13 15:41:46 +00008123 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008124 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8125 if (BaseClassDecl == InheritedDecl)
8126 continue;
8127 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8128 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008129 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008130 }
8131 }
8132
8133 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008134 for (const auto &B : ClassDecl->vbases()) {
8135 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008136 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8137 if (BaseClassDecl == InheritedDecl)
8138 continue;
8139 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8140 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008141 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008142 }
8143 }
8144
8145 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008146 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008147 if (F->hasInClassInitializer()) {
8148 if (Expr *E = F->getInClassInitializer())
8149 ExceptSpec.CalledExpr(E);
8150 else if (!F->isInvalidDecl())
8151 Diag(CD->getLocation(),
8152 diag::err_in_class_initializer_references_def_ctor) << CD;
8153 } else if (const RecordType *RecordTy
8154 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8155 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8156 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8157 if (Constructor)
8158 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8159 }
8160 }
8161
Richard Smithc2bc61b2013-03-18 21:12:30 +00008162 return ExceptSpec;
8163}
8164
Richard Smith8bf22e52012-11-29 01:34:07 +00008165namespace {
8166/// RAII object to register a special member as being currently declared.
8167struct DeclaringSpecialMember {
8168 Sema &S;
8169 Sema::SpecialMemberDecl D;
8170 bool WasAlreadyBeingDeclared;
8171
8172 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8173 : S(S), D(RD, CSM) {
8174 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8175 if (WasAlreadyBeingDeclared)
8176 // This almost never happens, but if it does, ensure that our cache
8177 // doesn't contain a stale result.
8178 S.SpecialMemberCache.clear();
8179
8180 // FIXME: Register a note to be produced if we encounter an error while
8181 // declaring the special member.
8182 }
8183 ~DeclaringSpecialMember() {
8184 if (!WasAlreadyBeingDeclared)
8185 S.SpecialMembersBeingDeclared.erase(D);
8186 }
8187
8188 /// \brief Are we already trying to declare this special member?
8189 bool isAlreadyBeingDeclared() const {
8190 return WasAlreadyBeingDeclared;
8191 }
8192};
8193}
8194
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008195CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8196 CXXRecordDecl *ClassDecl) {
8197 // C++ [class.ctor]p5:
8198 // A default constructor for a class X is a constructor of class X
8199 // that can be called without an argument. If there is no
8200 // user-declared constructor for class X, a default constructor is
8201 // implicitly declared. An implicitly-declared default constructor
8202 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008203 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008204 "Should not build implicit default constructor!");
8205
Richard Smith8bf22e52012-11-29 01:34:07 +00008206 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8207 if (DSM.isAlreadyBeingDeclared())
8208 return 0;
8209
Richard Smithb5800092012-06-10 05:43:50 +00008210 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8211 CXXDefaultConstructor,
8212 false);
8213
Douglas Gregor6d880b12010-07-01 22:31:05 +00008214 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008215 CanQualType ClassType
8216 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008217 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008218 DeclarationName Name
8219 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008220 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008221 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00008222 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00008223 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00008224 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008225 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008226 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008227 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008228
8229 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008230 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008231 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008232
Richard Smith6b02d462012-12-08 08:32:28 +00008233 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8234 // constructors is easy to compute.
8235 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8236
8237 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008238 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008239
Douglas Gregor9672f922010-07-03 00:47:00 +00008240 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008241 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008242
Douglas Gregor0be31a22010-07-02 17:43:08 +00008243 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008244 PushOnScopeChains(DefaultCon, S, false);
8245 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008246
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008247 return DefaultCon;
8248}
8249
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008250void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8251 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008252 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008253 !Constructor->doesThisDeclarationHaveABody() &&
8254 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008255 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008256
Anders Carlsson423f5d82010-04-23 16:04:08 +00008257 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008258 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008259
Eli Friedmaneaf34142012-10-18 20:14:08 +00008260 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008261 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008262 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008263 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008264 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008265 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008266 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008267 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008268 }
Douglas Gregor73193272010-09-20 16:48:21 +00008269
8270 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008271 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008272
Eli Friedman276dd182013-09-05 00:02:25 +00008273 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008274 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008275
8276 if (ASTMutationListener *L = getASTMutationListener()) {
8277 L->CompletedImplicitDefinition(Constructor);
8278 }
Richard Trieuef64e942013-10-25 00:56:00 +00008279
8280 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008281}
8282
Richard Smith938f40b2011-06-11 17:19:42 +00008283void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008284 // Perform any delayed checks on exception specifications.
8285 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008286}
8287
Richard Smith185be182013-04-10 05:48:59 +00008288namespace {
8289/// Information on inheriting constructors to declare.
8290class InheritingConstructorInfo {
8291public:
8292 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8293 : SemaRef(SemaRef), Derived(Derived) {
8294 // Mark the constructors that we already have in the derived class.
8295 //
8296 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8297 // unless there is a user-declared constructor with the same signature in
8298 // the class where the using-declaration appears.
8299 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8300 }
8301
8302 void inheritAll(CXXRecordDecl *RD) {
8303 visitAll(RD, &InheritingConstructorInfo::inherit);
8304 }
8305
8306private:
8307 /// Information about an inheriting constructor.
8308 struct InheritingConstructor {
8309 InheritingConstructor()
8310 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8311
8312 /// If \c true, a constructor with this signature is already declared
8313 /// in the derived class.
8314 bool DeclaredInDerived;
8315
8316 /// The constructor which is inherited.
8317 const CXXConstructorDecl *BaseCtor;
8318
8319 /// The derived constructor we declared.
8320 CXXConstructorDecl *DerivedCtor;
8321 };
8322
8323 /// Inheriting constructors with a given canonical type. There can be at
8324 /// most one such non-template constructor, and any number of templated
8325 /// constructors.
8326 struct InheritingConstructorsForType {
8327 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008328 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8329 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008330
8331 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8332 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8333 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8334 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8335 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8336 false, S.TPL_TemplateMatch))
8337 return Templates[I].second;
8338 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8339 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008340 }
Richard Smith185be182013-04-10 05:48:59 +00008341
8342 return NonTemplate;
8343 }
8344 };
8345
8346 /// Get or create the inheriting constructor record for a constructor.
8347 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8348 QualType CtorType) {
8349 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8350 .getEntry(SemaRef, Ctor);
8351 }
8352
8353 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8354
8355 /// Process all constructors for a class.
8356 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008357 for (const auto *Ctor : RD->ctors())
8358 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008359 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8360 I(RD->decls_begin()), E(RD->decls_end());
8361 I != E; ++I) {
8362 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8363 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8364 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008365 }
8366 }
Richard Smith185be182013-04-10 05:48:59 +00008367
8368 /// Note that a constructor (or constructor template) was declared in Derived.
8369 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8370 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8371 }
8372
8373 /// Inherit a single constructor.
8374 void inherit(const CXXConstructorDecl *Ctor) {
8375 const FunctionProtoType *CtorType =
8376 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008377 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008378 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8379
8380 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8381
8382 // Core issue (no number yet): the ellipsis is always discarded.
8383 if (EPI.Variadic) {
8384 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8385 SemaRef.Diag(Ctor->getLocation(),
8386 diag::note_using_decl_constructor_ellipsis);
8387 EPI.Variadic = false;
8388 }
8389
8390 // Declare a constructor for each number of parameters.
8391 //
8392 // C++11 [class.inhctor]p1:
8393 // The candidate set of inherited constructors from the class X named in
8394 // the using-declaration consists of [... modulo defects ...] for each
8395 // constructor or constructor template of X, the set of constructors or
8396 // constructor templates that results from omitting any ellipsis parameter
8397 // specification and successively omitting parameters with a default
8398 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008399 unsigned MinParams = minParamsToInherit(Ctor);
8400 unsigned Params = Ctor->getNumParams();
8401 if (Params >= MinParams) {
8402 do
8403 declareCtor(UsingLoc, Ctor,
8404 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008405 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008406 while (Params > MinParams &&
8407 Ctor->getParamDecl(--Params)->hasDefaultArg());
8408 }
Richard Smith185be182013-04-10 05:48:59 +00008409 }
8410
8411 /// Find the using-declaration which specified that we should inherit the
8412 /// constructors of \p Base.
8413 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8414 // No fancy lookup required; just look for the base constructor name
8415 // directly within the derived class.
8416 ASTContext &Context = SemaRef.Context;
8417 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8418 Context.getCanonicalType(Context.getRecordType(Base)));
8419 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8420 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8421 }
8422
8423 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8424 // C++11 [class.inhctor]p3:
8425 // [F]or each constructor template in the candidate set of inherited
8426 // constructors, a constructor template is implicitly declared
8427 if (Ctor->getDescribedFunctionTemplate())
8428 return 0;
8429
8430 // For each non-template constructor in the candidate set of inherited
8431 // constructors other than a constructor having no parameters or a
8432 // copy/move constructor having a single parameter, a constructor is
8433 // implicitly declared [...]
8434 if (Ctor->getNumParams() == 0)
8435 return 1;
8436 if (Ctor->isCopyOrMoveConstructor())
8437 return 2;
8438
8439 // Per discussion on core reflector, never inherit a constructor which
8440 // would become a default, copy, or move constructor of Derived either.
8441 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8442 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8443 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8444 }
8445
8446 /// Declare a single inheriting constructor, inheriting the specified
8447 /// constructor, with the given type.
8448 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8449 QualType DerivedType) {
8450 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8451
8452 // C++11 [class.inhctor]p3:
8453 // ... a constructor is implicitly declared with the same constructor
8454 // characteristics unless there is a user-declared constructor with
8455 // the same signature in the class where the using-declaration appears
8456 if (Entry.DeclaredInDerived)
8457 return;
8458
8459 // C++11 [class.inhctor]p7:
8460 // If two using-declarations declare inheriting constructors with the
8461 // same signature, the program is ill-formed
8462 if (Entry.DerivedCtor) {
8463 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8464 // Only diagnose this once per constructor.
8465 if (Entry.DerivedCtor->isInvalidDecl())
8466 return;
8467 Entry.DerivedCtor->setInvalidDecl();
8468
8469 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8470 SemaRef.Diag(BaseCtor->getLocation(),
8471 diag::note_using_decl_constructor_conflict_current_ctor);
8472 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8473 diag::note_using_decl_constructor_conflict_previous_ctor);
8474 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8475 diag::note_using_decl_constructor_conflict_previous_using);
8476 } else {
8477 // Core issue (no number): if the same inheriting constructor is
8478 // produced by multiple base class constructors from the same base
8479 // class, the inheriting constructor is defined as deleted.
8480 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8481 }
8482
8483 return;
8484 }
8485
8486 ASTContext &Context = SemaRef.Context;
8487 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8488 Context.getCanonicalType(Context.getRecordType(Derived)));
8489 DeclarationNameInfo NameInfo(Name, UsingLoc);
8490
8491 TemplateParameterList *TemplateParams = 0;
8492 if (const FunctionTemplateDecl *FTD =
8493 BaseCtor->getDescribedFunctionTemplate()) {
8494 TemplateParams = FTD->getTemplateParameters();
8495 // We're reusing template parameters from a different DeclContext. This
8496 // is questionable at best, but works out because the template depth in
8497 // both places is guaranteed to be 0.
8498 // FIXME: Rebuild the template parameters in the new context, and
8499 // transform the function type to refer to them.
8500 }
8501
8502 // Build type source info pointing at the using-declaration. This is
8503 // required by template instantiation.
8504 TypeSourceInfo *TInfo =
8505 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8506 FunctionProtoTypeLoc ProtoLoc =
8507 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8508
8509 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8510 Context, Derived, UsingLoc, NameInfo, DerivedType,
8511 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8512 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8513
8514 // Build an unevaluated exception specification for this constructor.
8515 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8516 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8517 EPI.ExceptionSpecType = EST_Unevaluated;
8518 EPI.ExceptionSpecDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008519 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008520 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008521
8522 // Build the parameter declarations.
8523 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008524 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008525 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008526 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008527 ParmVarDecl *PD = ParmVarDecl::Create(
8528 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
Alp Toker9cacbab2014-01-20 20:26:09 +00008529 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
Richard Smith185be182013-04-10 05:48:59 +00008530 PD->setScopeInfo(0, I);
8531 PD->setImplicit();
8532 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008533 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008534 }
8535
8536 // Set up the new constructor.
8537 DerivedCtor->setAccess(BaseCtor->getAccess());
8538 DerivedCtor->setParams(ParamDecls);
8539 DerivedCtor->setInheritedConstructor(BaseCtor);
8540 if (BaseCtor->isDeleted())
8541 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8542
8543 // If this is a constructor template, build the template declaration.
8544 if (TemplateParams) {
8545 FunctionTemplateDecl *DerivedTemplate =
8546 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8547 TemplateParams, DerivedCtor);
8548 DerivedTemplate->setAccess(BaseCtor->getAccess());
8549 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8550 Derived->addDecl(DerivedTemplate);
8551 } else {
8552 Derived->addDecl(DerivedCtor);
8553 }
8554
8555 Entry.BaseCtor = BaseCtor;
8556 Entry.DerivedCtor = DerivedCtor;
8557 }
8558
8559 Sema &SemaRef;
8560 CXXRecordDecl *Derived;
8561 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8562 MapType Map;
8563};
8564}
8565
8566void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8567 // Defer declaring the inheriting constructors until the class is
8568 // instantiated.
8569 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008570 return;
8571
Richard Smith185be182013-04-10 05:48:59 +00008572 // Find base classes from which we might inherit constructors.
8573 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008574 for (const auto &BaseIt : ClassDecl->bases())
8575 if (BaseIt.getInheritConstructors())
8576 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008577
Richard Smith185be182013-04-10 05:48:59 +00008578 // Go no further if we're not inheriting any constructors.
8579 if (InheritedBases.empty())
8580 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008581
Richard Smith185be182013-04-10 05:48:59 +00008582 // Declare the inherited constructors.
8583 InheritingConstructorInfo ICI(*this, ClassDecl);
8584 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8585 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008586}
8587
Richard Smithc2bc61b2013-03-18 21:12:30 +00008588void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8589 CXXConstructorDecl *Constructor) {
8590 CXXRecordDecl *ClassDecl = Constructor->getParent();
8591 assert(Constructor->getInheritedConstructor() &&
8592 !Constructor->doesThisDeclarationHaveABody() &&
8593 !Constructor->isDeleted());
8594
8595 SynthesizedFunctionScope Scope(*this, Constructor);
8596 DiagnosticErrorTrap Trap(Diags);
8597 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8598 Trap.hasErrorOccurred()) {
8599 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8600 << Context.getTagDeclType(ClassDecl);
8601 Constructor->setInvalidDecl();
8602 return;
8603 }
8604
8605 SourceLocation Loc = Constructor->getLocation();
8606 Constructor->setBody(new (Context) CompoundStmt(Loc));
8607
Eli Friedman276dd182013-09-05 00:02:25 +00008608 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008609 MarkVTableUsed(CurrentLocation, ClassDecl);
8610
8611 if (ASTMutationListener *L = getASTMutationListener()) {
8612 L->CompletedImplicitDefinition(Constructor);
8613 }
8614}
8615
8616
Alexis Huntf91729462011-05-12 22:46:25 +00008617Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008618Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8619 CXXRecordDecl *ClassDecl = MD->getParent();
8620
Douglas Gregorf1203042010-07-01 19:09:28 +00008621 // C++ [except.spec]p14:
8622 // An implicitly declared special member function (Clause 12) shall have
8623 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008624 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008625 if (ClassDecl->isInvalidDecl())
8626 return ExceptSpec;
8627
Douglas Gregorf1203042010-07-01 19:09:28 +00008628 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008629 for (const auto &B : ClassDecl->bases()) {
8630 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008631 continue;
8632
Aaron Ballman574705e2014-03-13 15:41:46 +00008633 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8634 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008635 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008636 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008637
Douglas Gregorf1203042010-07-01 19:09:28 +00008638 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008639 for (const auto &B : ClassDecl->vbases()) {
8640 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8641 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008642 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008643 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008644
Douglas Gregorf1203042010-07-01 19:09:28 +00008645 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008646 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008647 if (const RecordType *RecordTy
8648 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008649 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008650 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008651 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008652
Alexis Huntf91729462011-05-12 22:46:25 +00008653 return ExceptSpec;
8654}
8655
8656CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8657 // C++ [class.dtor]p2:
8658 // If a class has no user-declared destructor, a destructor is
8659 // declared implicitly. An implicitly-declared destructor is an
8660 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008661 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008662
Richard Smith8bf22e52012-11-29 01:34:07 +00008663 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8664 if (DSM.isAlreadyBeingDeclared())
8665 return 0;
8666
Douglas Gregor7454c562010-07-02 20:37:36 +00008667 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008668 CanQualType ClassType
8669 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008670 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008671 DeclarationName Name
8672 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008673 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008674 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008675 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8676 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008677 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008678 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008679 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008680 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008681
8682 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008683 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008684 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008685
Richard Smith6b02d462012-12-08 08:32:28 +00008686 AddOverriddenMethods(ClassDecl, Destructor);
8687
8688 // We don't need to use SpecialMemberIsTrivial here; triviality for
8689 // destructors is easy to compute.
8690 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8691
8692 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008693 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008694
Douglas Gregor7454c562010-07-02 20:37:36 +00008695 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008696 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008697
Douglas Gregor7454c562010-07-02 20:37:36 +00008698 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008699 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008700 PushOnScopeChains(Destructor, S, false);
8701 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008702
Douglas Gregorf1203042010-07-01 19:09:28 +00008703 return Destructor;
8704}
8705
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008706void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008707 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008708 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008709 !Destructor->doesThisDeclarationHaveABody() &&
8710 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008711 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008712 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008713 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008714
Douglas Gregor54818f02010-05-12 16:39:35 +00008715 if (Destructor->isInvalidDecl())
8716 return;
8717
Eli Friedmaneaf34142012-10-18 20:14:08 +00008718 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008719
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008720 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008721 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8722 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008723
Douglas Gregor54818f02010-05-12 16:39:35 +00008724 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008725 Diag(CurrentLocation, diag::note_member_synthesized_at)
8726 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8727
8728 Destructor->setInvalidDecl();
8729 return;
8730 }
8731
Douglas Gregor73193272010-09-20 16:48:21 +00008732 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008733 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008734 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008735 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008736
8737 if (ASTMutationListener *L = getASTMutationListener()) {
8738 L->CompletedImplicitDefinition(Destructor);
8739 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008740}
8741
Richard Smith84973e52012-04-21 18:42:51 +00008742/// \brief Perform any semantic analysis which needs to be delayed until all
8743/// pending class member declarations have been parsed.
8744void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008745 // If the context is an invalid C++ class, just suppress these checks.
8746 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8747 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008748 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008749 DelayedDestructorExceptionSpecChecks.clear();
8750 return;
8751 }
8752 }
Richard Smith84973e52012-04-21 18:42:51 +00008753}
8754
Richard Smithd3b5c9082012-07-27 04:22:15 +00008755void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8756 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008757 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008758 "adjusting dtor exception specs was introduced in c++11");
8759
Sebastian Redl623ea822011-05-19 05:13:44 +00008760 // C++11 [class.dtor]p3:
8761 // A declaration of a destructor that does not have an exception-
8762 // specification is implicitly considered to have the same exception-
8763 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008764 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008765 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008766 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008767 return;
8768
Chandler Carruth9a797572011-09-20 04:55:26 +00008769 // Replace the destructor's type, building off the existing one. Fortunately,
8770 // the only thing of interest in the destructor type is its extended info.
8771 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008772 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8773 EPI.ExceptionSpecType = EST_Unevaluated;
8774 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008775 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008776
Sebastian Redl623ea822011-05-19 05:13:44 +00008777 // FIXME: If the destructor has a body that could throw, and the newly created
8778 // spec doesn't allow exceptions, we should emit a warning, because this
8779 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008780 // However, we don't have a body or an exception specification yet, so it
8781 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008782}
8783
Pavel Labath58934982013-08-30 08:52:28 +00008784namespace {
8785/// \brief An abstract base class for all helper classes used in building the
8786// copy/move operators. These classes serve as factory functions and help us
8787// avoid using the same Expr* in the AST twice.
8788class ExprBuilder {
8789 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8790 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8791
8792protected:
8793 static Expr *assertNotNull(Expr *E) {
8794 assert(E && "Expression construction must not fail.");
8795 return E;
8796 }
8797
8798public:
8799 ExprBuilder() {}
8800 virtual ~ExprBuilder() {}
8801
8802 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8803};
8804
8805class RefBuilder: public ExprBuilder {
8806 VarDecl *Var;
8807 QualType VarType;
8808
8809public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008810 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008811 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8812 }
8813
8814 RefBuilder(VarDecl *Var, QualType VarType)
8815 : Var(Var), VarType(VarType) {}
8816};
8817
8818class ThisBuilder: public ExprBuilder {
8819public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008820 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008821 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8822 }
8823};
8824
8825class CastBuilder: public ExprBuilder {
8826 const ExprBuilder &Builder;
8827 QualType Type;
8828 ExprValueKind Kind;
8829 const CXXCastPath &Path;
8830
8831public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008832 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008833 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8834 CK_UncheckedDerivedToBase, Kind,
8835 &Path).take());
8836 }
8837
8838 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8839 const CXXCastPath &Path)
8840 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8841};
8842
8843class DerefBuilder: public ExprBuilder {
8844 const ExprBuilder &Builder;
8845
8846public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008847 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008848 return assertNotNull(
8849 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8850 }
8851
8852 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8853};
8854
8855class MemberBuilder: public ExprBuilder {
8856 const ExprBuilder &Builder;
8857 QualType Type;
8858 CXXScopeSpec SS;
8859 bool IsArrow;
8860 LookupResult &MemberLookup;
8861
8862public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008863 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008864 return assertNotNull(S.BuildMemberReferenceExpr(
8865 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8866 MemberLookup, 0).take());
8867 }
8868
8869 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8870 LookupResult &MemberLookup)
8871 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8872 MemberLookup(MemberLookup) {}
8873};
8874
8875class MoveCastBuilder: public ExprBuilder {
8876 const ExprBuilder &Builder;
8877
8878public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008879 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008880 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8881 }
8882
8883 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8884};
8885
8886class LvalueConvBuilder: public ExprBuilder {
8887 const ExprBuilder &Builder;
8888
8889public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008890 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008891 return assertNotNull(
8892 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8893 }
8894
8895 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8896};
8897
8898class SubscriptBuilder: public ExprBuilder {
8899 const ExprBuilder &Base;
8900 const ExprBuilder &Index;
8901
8902public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008903 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008904 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8905 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8906 }
8907
8908 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8909 : Base(Base), Index(Index) {}
8910};
8911
8912} // end anonymous namespace
8913
Richard Smith41ae3282012-11-14 00:50:40 +00008914/// When generating a defaulted copy or move assignment operator, if a field
8915/// should be copied with __builtin_memcpy rather than via explicit assignments,
8916/// do so. This optimization only applies for arrays of scalars, and for arrays
8917/// of class type where the selected copy/move-assignment operator is trivial.
8918static StmtResult
8919buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008920 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00008921 // Compute the size of the memory buffer to be copied.
8922 QualType SizeType = S.Context.getSizeType();
8923 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8924 S.Context.getTypeSizeInChars(T).getQuantity());
8925
8926 // Take the address of the field references for "from" and "to". We
8927 // directly construct UnaryOperators here because semantic analysis
8928 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00008929 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008930 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8931 S.Context.getPointerType(From->getType()),
8932 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00008933 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008934 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8935 S.Context.getPointerType(To->getType()),
8936 VK_RValue, OK_Ordinary, Loc);
8937
8938 const Type *E = T->getBaseElementTypeUnsafe();
8939 bool NeedsCollectableMemCpy =
8940 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8941
8942 // Create a reference to the __builtin_objc_memmove_collectable function
8943 StringRef MemCpyName = NeedsCollectableMemCpy ?
8944 "__builtin_objc_memmove_collectable" :
8945 "__builtin_memcpy";
8946 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8947 Sema::LookupOrdinaryName);
8948 S.LookupName(R, S.TUScope, true);
8949
8950 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8951 if (!MemCpy)
8952 // Something went horribly wrong earlier, and we will have complained
8953 // about it.
8954 return StmtError();
8955
8956 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8957 VK_RValue, Loc, 0);
8958 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8959
8960 Expr *CallArgs[] = {
8961 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8962 };
8963 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8964 Loc, CallArgs, Loc);
8965
8966 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8967 return S.Owned(Call.takeAs<Stmt>());
8968}
8969
Sebastian Redl22653ba2011-08-30 19:58:05 +00008970/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00008971/// \c To.
8972///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008973/// This routine is used to copy/move the members of a class with an
8974/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00008975/// copied are arrays, this routine builds for loops to copy them.
8976///
8977/// \param S The Sema object used for type-checking.
8978///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008979/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008980///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008981/// \param T The type of the expressions being copied/moved. Both expressions
8982/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008983///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008984/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008985///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008986/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008987///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008988/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008989/// Otherwise, it's a non-static member subobject.
8990///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008991/// \param Copying Whether we're copying or moving.
8992///
Douglas Gregorb139cd52010-05-01 20:49:11 +00008993/// \param Depth Internal parameter recording the depth of the recursion.
8994///
Richard Smith41ae3282012-11-14 00:50:40 +00008995/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8996/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00008997static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00008998buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008999 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009000 bool CopyingBaseSubobject, bool Copying,
9001 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009002 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009003 // Each subobject is assigned in the manner appropriate to its type:
9004 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009005 // - if the subobject is of class type, as if by a call to operator= with
9006 // the subobject as the object expression and the corresponding
9007 // subobject of x as a single function argument (as if by explicit
9008 // qualification; that is, ignoring any possible virtual overriding
9009 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009010 //
9011 // C++03 [class.copy]p13:
9012 // - if the subobject is of class type, the copy assignment operator for
9013 // the class is used (as if by explicit qualification; that is,
9014 // ignoring any possible virtual overriding functions in more derived
9015 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009016 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9017 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009018
Douglas Gregorb139cd52010-05-01 20:49:11 +00009019 // Look for operator=.
9020 DeclarationName Name
9021 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9022 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9023 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009024
Richard Smith52c0b582012-11-13 00:54:12 +00009025 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9026 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009027 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009028 LookupResult::Filter F = OpLookup.makeFilter();
9029 while (F.hasNext()) {
9030 NamedDecl *D = F.next();
9031 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9032 if (Method->isCopyAssignmentOperator() ||
9033 (!Copying && Method->isMoveAssignmentOperator()))
9034 continue;
9035
9036 F.erase();
9037 }
9038 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009039 }
Richard Smith52c0b582012-11-13 00:54:12 +00009040
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009041 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009042 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009043 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009044 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009045 // ambiguities), we need to cast "this" to that subobject type; to
9046 // ensure that we don't go through the virtual call mechanism, we need
9047 // to qualify the operator= name with the base class (see below). However,
9048 // this means that if the base class has a protected copy assignment
9049 // operator, the protected member access check will fail. So, we
9050 // rewrite "protected" access to "public" access in this case, since we
9051 // know by construction that we're calling from a derived class.
9052 if (CopyingBaseSubobject) {
9053 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9054 L != LEnd; ++L) {
9055 if (L.getAccess() == AS_protected)
9056 L.setAccess(AS_public);
9057 }
9058 }
Richard Smith52c0b582012-11-13 00:54:12 +00009059
Douglas Gregorb139cd52010-05-01 20:49:11 +00009060 // Create the nested-name-specifier that will be used to qualify the
9061 // reference to operator=; this is required to suppress the virtual
9062 // call mechanism.
9063 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009064 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009065 SS.MakeTrivial(S.Context,
9066 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009067 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009068 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009069
Douglas Gregorb139cd52010-05-01 20:49:11 +00009070 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009071 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009072 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9073 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00009074 /*FirstQualifierInScope=*/0,
9075 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009076 /*TemplateArgs=*/0,
9077 /*SuppressQualifierCheck=*/true);
9078 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009079 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009080
Douglas Gregorb139cd52010-05-01 20:49:11 +00009081 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009082
Pavel Labath58934982013-08-30 08:52:28 +00009083 Expr *FromInst = From.build(S, Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009084 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009085 OpEqualRef.takeAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009086 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009087 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009088 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009089
Richard Smith41ae3282012-11-14 00:50:40 +00009090 // If we built a call to a trivial 'operator=' while copying an array,
9091 // bail out. We'll replace the whole shebang with a memcpy.
9092 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9093 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9094 return StmtResult((Stmt*)0);
9095
Richard Smith52c0b582012-11-13 00:54:12 +00009096 // Convert to an expression-statement, and clean up any produced
9097 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009098 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009099 }
John McCallab8c2732010-03-16 06:11:48 +00009100
Richard Smith52c0b582012-11-13 00:54:12 +00009101 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009102 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009103 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009104 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009105 ExprResult Assignment = S.CreateBuiltinBinOp(
9106 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009107 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009108 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009109 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009110 }
Richard Smith52c0b582012-11-13 00:54:12 +00009111
9112 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009113 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009114
Douglas Gregorb139cd52010-05-01 20:49:11 +00009115 // Construct a loop over the array bounds, e.g.,
9116 //
9117 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9118 //
9119 // that will copy each of the array elements.
9120 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009121
Douglas Gregorb139cd52010-05-01 20:49:11 +00009122 // Create the iteration variable.
9123 IdentifierInfo *IterationVarName = 0;
9124 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009125 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009126 llvm::raw_svector_ostream OS(Str);
9127 OS << "__i" << Depth;
9128 IterationVarName = &S.Context.Idents.get(OS.str());
9129 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009130 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009131 IterationVarName, SizeType,
9132 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009133 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009134
Douglas Gregorb139cd52010-05-01 20:49:11 +00009135 // Initialize the iteration variable to zero.
9136 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009137 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009138
Pavel Labath58934982013-08-30 08:52:28 +00009139 // Creates a reference to the iteration variable.
9140 RefBuilder IterationVarRef(IterationVar, SizeType);
9141 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009142
Douglas Gregorb139cd52010-05-01 20:49:11 +00009143 // Create the DeclStmt that holds the iteration variable.
9144 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009145
Douglas Gregorb139cd52010-05-01 20:49:11 +00009146 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009147 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9148 MoveCastBuilder FromIndexMove(FromIndexCopy);
9149 const ExprBuilder *FromIndex;
9150 if (Copying)
9151 FromIndex = &FromIndexCopy;
9152 else
9153 FromIndex = &FromIndexMove;
9154
9155 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009156
9157 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009158 StmtResult Copy =
9159 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009160 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009161 Copying, Depth + 1);
9162 // Bail out if copying fails or if we determined that we should use memcpy.
9163 if (Copy.isInvalid() || !Copy.get())
9164 return Copy;
9165
9166 // Create the comparison against the array bound.
9167 llvm::APInt Upper
9168 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9169 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009170 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009171 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9172 BO_NE, S.Context.BoolTy,
9173 VK_RValue, OK_Ordinary, Loc, false);
9174
9175 // Create the pre-increment of the iteration variable.
9176 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009177 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9178 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009179
Douglas Gregorb139cd52010-05-01 20:49:11 +00009180 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009181 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009182 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00009183 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00009184 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009185}
9186
Richard Smith41ae3282012-11-14 00:50:40 +00009187static StmtResult
9188buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009189 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009190 bool CopyingBaseSubobject, bool Copying) {
9191 // Maybe we should use a memcpy?
9192 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9193 T.isTriviallyCopyableType(S.Context))
9194 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9195
9196 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9197 CopyingBaseSubobject,
9198 Copying, 0));
9199
9200 // If we ended up picking a trivial assignment operator for an array of a
9201 // non-trivially-copyable class type, just emit a memcpy.
9202 if (!Result.isInvalid() && !Result.get())
9203 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9204
9205 return Result;
9206}
9207
Richard Smithd3b5c9082012-07-27 04:22:15 +00009208Sema::ImplicitExceptionSpecification
9209Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9210 CXXRecordDecl *ClassDecl = MD->getParent();
9211
9212 ImplicitExceptionSpecification ExceptSpec(*this);
9213 if (ClassDecl->isInvalidDecl())
9214 return ExceptSpec;
9215
9216 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009217 assert(T->getNumParams() == 1 && "not a copy assignment op");
9218 unsigned ArgQuals =
9219 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009220
Douglas Gregor68e11362010-07-01 17:48:08 +00009221 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009222 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009223 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009224
9225 // It is unspecified whether or not an implicit copy assignment operator
9226 // attempts to deduplicate calls to assignment operators of virtual bases are
9227 // made. As such, this exception specification is effectively unspecified.
9228 // Based on a similar decision made for constness in C++0x, we're erring on
9229 // the side of assuming such calls to be made regardless of whether they
9230 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009231 for (const auto &Base : ClassDecl->bases()) {
9232 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009233 continue;
9234
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009235 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009236 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009237 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9238 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009239 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009240 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009241
Aaron Ballman445a9392014-03-13 16:15:17 +00009242 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009243 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009244 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009245 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9246 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009247 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009248 }
9249
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009250 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009251 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009252 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9253 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009254 LookupCopyingAssignment(FieldClassDecl,
9255 ArgQuals | FieldType.getCVRQualifiers(),
9256 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009257 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009258 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009259 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009260
Richard Smithd3b5c9082012-07-27 04:22:15 +00009261 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009262}
9263
9264CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9265 // Note: The following rules are largely analoguous to the copy
9266 // constructor rules. Note that virtual bases are not taken into account
9267 // for determining the argument type of the operator. Note also that
9268 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009269 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009270
Richard Smith8bf22e52012-11-29 01:34:07 +00009271 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9272 if (DSM.isAlreadyBeingDeclared())
9273 return 0;
9274
Alexis Hunt119f3652011-05-14 05:23:20 +00009275 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9276 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009277 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9278 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009279 ArgType = ArgType.withConst();
9280 ArgType = Context.getLValueReferenceType(ArgType);
9281
Richard Smith99005e62013-05-07 03:19:20 +00009282 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9283 CXXCopyAssignment,
9284 Const);
9285
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009286 // An implicitly-declared copy assignment operator is an inline public
9287 // member of its class.
9288 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009289 SourceLocation ClassLoc = ClassDecl->getLocation();
9290 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009291 CXXMethodDecl *CopyAssignment =
9292 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9293 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9294 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009295 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009296 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009297 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009298
9299 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009300 FunctionProtoType::ExtProtoInfo EPI =
9301 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009302 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009303
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009304 // Add the parameter to the operator.
9305 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009306 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009307 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009308 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009309 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009310
Richard Smith6b02d462012-12-08 08:32:28 +00009311 AddOverriddenMethods(ClassDecl, CopyAssignment);
9312
9313 CopyAssignment->setTrivial(
9314 ClassDecl->needsOverloadResolutionForCopyAssignment()
9315 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9316 : ClassDecl->hasTrivialCopyAssignment());
9317
Richard Smith852265f2012-03-30 20:53:28 +00009318 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009319 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009320
Richard Smith6b02d462012-12-08 08:32:28 +00009321 // Note that we have added this copy-assignment operator.
9322 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9323
9324 if (Scope *S = getScopeForContext(ClassDecl))
9325 PushOnScopeChains(CopyAssignment, S, false);
9326 ClassDecl->addDecl(CopyAssignment);
9327
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009328 return CopyAssignment;
9329}
9330
Richard Smithd577fbb2013-06-13 03:23:42 +00009331/// Diagnose an implicit copy operation for a class which is odr-used, but
9332/// which is deprecated because the class has a user-declared copy constructor,
9333/// copy assignment operator, or destructor.
9334static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9335 SourceLocation UseLoc) {
9336 assert(CopyOp->isImplicit());
9337
9338 CXXRecordDecl *RD = CopyOp->getParent();
9339 CXXMethodDecl *UserDeclaredOperation = 0;
9340
9341 // In Microsoft mode, assignment operations don't affect constructors and
9342 // vice versa.
9343 if (RD->hasUserDeclaredDestructor()) {
9344 UserDeclaredOperation = RD->getDestructor();
9345 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9346 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009347 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009348 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009349 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009350 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009351 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009352 break;
9353 }
9354 }
9355 assert(UserDeclaredOperation);
9356 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9357 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009358 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009359 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009360 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009361 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009362 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009363 break;
9364 }
9365 }
9366 assert(UserDeclaredOperation);
9367 }
9368
9369 if (UserDeclaredOperation) {
9370 S.Diag(UserDeclaredOperation->getLocation(),
9371 diag::warn_deprecated_copy_operation)
9372 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9373 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9374 S.Diag(UseLoc, diag::note_member_synthesized_at)
9375 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9376 : Sema::CXXCopyAssignment)
9377 << RD;
9378 }
9379}
9380
Douglas Gregorb139cd52010-05-01 20:49:11 +00009381void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9382 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009383 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009384 CopyAssignOperator->isOverloadedOperator() &&
9385 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009386 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9387 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009388 "DefineImplicitCopyAssignment called for wrong function");
9389
9390 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9391
9392 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9393 CopyAssignOperator->setInvalidDecl();
9394 return;
9395 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009396
9397 // C++11 [class.copy]p18:
9398 // The [definition of an implicitly declared copy assignment operator] is
9399 // deprecated if the class has a user-declared copy constructor or a
9400 // user-declared destructor.
9401 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9402 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9403
Eli Friedman276dd182013-09-05 00:02:25 +00009404 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009405
Eli Friedmaneaf34142012-10-18 20:14:08 +00009406 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009407 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009408
9409 // C++0x [class.copy]p30:
9410 // The implicitly-defined or explicitly-defaulted copy assignment operator
9411 // for a non-union class X performs memberwise copy assignment of its
9412 // subobjects. The direct base classes of X are assigned first, in the
9413 // order of their declaration in the base-specifier-list, and then the
9414 // immediate non-static data members of X are assigned, in the order in
9415 // which they were declared in the class definition.
9416
9417 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009418 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009419
9420 // The parameter for the "other" object, which we are copying from.
9421 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9422 Qualifiers OtherQuals = Other->getType().getQualifiers();
9423 QualType OtherRefType = Other->getType();
9424 if (const LValueReferenceType *OtherRef
9425 = OtherRefType->getAs<LValueReferenceType>()) {
9426 OtherRefType = OtherRef->getPointeeType();
9427 OtherQuals = OtherRefType.getQualifiers();
9428 }
9429
9430 // Our location for everything implicitly-generated.
9431 SourceLocation Loc = CopyAssignOperator->getLocation();
9432
Pavel Labath58934982013-08-30 08:52:28 +00009433 // Builds a DeclRefExpr for the "other" object.
9434 RefBuilder OtherRef(Other, OtherRefType);
9435
9436 // Builds the "this" pointer.
9437 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009438
9439 // Assign base classes.
9440 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009441 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009442 // Form the assignment:
9443 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009444 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009445 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009446 Invalid = true;
9447 continue;
9448 }
9449
John McCallcf142162010-08-07 06:22:56 +00009450 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009451 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009452
Douglas Gregorb139cd52010-05-01 20:49:11 +00009453 // Construct the "from" expression, which is an implicit cast to the
9454 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009455 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9456 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009457
9458 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009459 DerefBuilder DerefThis(This);
9460 CastBuilder To(DerefThis,
9461 Context.getCVRQualifiedType(
9462 BaseType, CopyAssignOperator->getTypeQualifiers()),
9463 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009464
9465 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009466 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009467 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009468 /*CopyingBaseSubobject=*/true,
9469 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009470 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009471 Diag(CurrentLocation, diag::note_member_synthesized_at)
9472 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9473 CopyAssignOperator->setInvalidDecl();
9474 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009475 }
9476
9477 // Success! Record the copy.
9478 Statements.push_back(Copy.takeAs<Expr>());
9479 }
9480
Douglas Gregorb139cd52010-05-01 20:49:11 +00009481 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009482 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009483 if (Field->isUnnamedBitfield())
9484 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009485
9486 if (Field->isInvalidDecl()) {
9487 Invalid = true;
9488 continue;
9489 }
9490
Douglas Gregorb139cd52010-05-01 20:49:11 +00009491 // Check for members of reference type; we can't copy those.
9492 if (Field->getType()->isReferenceType()) {
9493 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9494 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9495 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009496 Diag(CurrentLocation, diag::note_member_synthesized_at)
9497 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009498 Invalid = true;
9499 continue;
9500 }
9501
9502 // Check for members of const-qualified, non-class type.
9503 QualType BaseType = Context.getBaseElementType(Field->getType());
9504 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9505 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9506 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9507 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009508 Diag(CurrentLocation, diag::note_member_synthesized_at)
9509 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009510 Invalid = true;
9511 continue;
9512 }
John McCall1b1a1db2011-06-17 00:18:42 +00009513
9514 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009515 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9516 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009517
9518 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009519 if (FieldType->isIncompleteArrayType()) {
9520 assert(ClassDecl->hasFlexibleArrayMember() &&
9521 "Incomplete array type is not valid");
9522 continue;
9523 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009524
9525 // Build references to the field in the object we're copying from and to.
9526 CXXScopeSpec SS; // Intentionally empty
9527 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9528 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009529 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009530 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009531
9532 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9533
9534 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009535
Douglas Gregorb139cd52010-05-01 20:49:11 +00009536 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009537 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009538 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009539 /*CopyingBaseSubobject=*/false,
9540 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009541 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009542 Diag(CurrentLocation, diag::note_member_synthesized_at)
9543 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9544 CopyAssignOperator->setInvalidDecl();
9545 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009546 }
9547
9548 // Success! Record the copy.
9549 Statements.push_back(Copy.takeAs<Stmt>());
9550 }
9551
9552 if (!Invalid) {
9553 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009554 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009555
John McCalldadc5752010-08-24 06:29:42 +00009556 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009557 if (Return.isInvalid())
9558 Invalid = true;
9559 else {
9560 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009561
9562 if (Trap.hasErrorOccurred()) {
9563 Diag(CurrentLocation, diag::note_member_synthesized_at)
9564 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9565 Invalid = true;
9566 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009567 }
9568 }
9569
9570 if (Invalid) {
9571 CopyAssignOperator->setInvalidDecl();
9572 return;
9573 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009574
9575 StmtResult Body;
9576 {
9577 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009578 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009579 /*isStmtExpr=*/false);
9580 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9581 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009582 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009583
9584 if (ASTMutationListener *L = getASTMutationListener()) {
9585 L->CompletedImplicitDefinition(CopyAssignOperator);
9586 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009587}
9588
Sebastian Redl22653ba2011-08-30 19:58:05 +00009589Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009590Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9591 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009592
Richard Smithd3b5c9082012-07-27 04:22:15 +00009593 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009594 if (ClassDecl->isInvalidDecl())
9595 return ExceptSpec;
9596
9597 // C++0x [except.spec]p14:
9598 // An implicitly declared special member function (Clause 12) shall have an
9599 // exception-specification. [...]
9600
9601 // It is unspecified whether or not an implicit move assignment operator
9602 // attempts to deduplicate calls to assignment operators of virtual bases are
9603 // made. As such, this exception specification is effectively unspecified.
9604 // Based on a similar decision made for constness in C++0x, we're erring on
9605 // the side of assuming such calls to be made regardless of whether they
9606 // actually happen.
9607 // Note that a move constructor is not implicitly declared when there are
9608 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009609 for (const auto &Base : ClassDecl->bases()) {
9610 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009611 continue;
9612
9613 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009614 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009615 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009616 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009617 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009618 }
9619
Aaron Ballman445a9392014-03-13 16:15:17 +00009620 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009621 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009622 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009623 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009624 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009625 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009626 }
9627
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009628 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009629 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009630 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009631 if (CXXMethodDecl *MoveAssign =
9632 LookupMovingAssignment(FieldClassDecl,
9633 FieldType.getCVRQualifiers(),
9634 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009635 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009636 }
9637 }
9638
9639 return ExceptSpec;
9640}
9641
9642CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009643 assert(ClassDecl->needsImplicitMoveAssignment());
9644
Richard Smith8bf22e52012-11-29 01:34:07 +00009645 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9646 if (DSM.isAlreadyBeingDeclared())
9647 return 0;
9648
Sebastian Redl22653ba2011-08-30 19:58:05 +00009649 // Note: The following rules are largely analoguous to the move
9650 // constructor rules.
9651
Sebastian Redl22653ba2011-08-30 19:58:05 +00009652 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9653 QualType RetType = Context.getLValueReferenceType(ArgType);
9654 ArgType = Context.getRValueReferenceType(ArgType);
9655
Richard Smith99005e62013-05-07 03:19:20 +00009656 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9657 CXXMoveAssignment,
9658 false);
9659
Sebastian Redl22653ba2011-08-30 19:58:05 +00009660 // An implicitly-declared move assignment operator is an inline public
9661 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009662 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9663 SourceLocation ClassLoc = ClassDecl->getLocation();
9664 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009665 CXXMethodDecl *MoveAssignment =
9666 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9667 /*TInfo=*/0, /*StorageClass=*/SC_None,
9668 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009669 MoveAssignment->setAccess(AS_public);
9670 MoveAssignment->setDefaulted();
9671 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009672
Richard Smithd3b5c9082012-07-27 04:22:15 +00009673 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009674 FunctionProtoType::ExtProtoInfo EPI =
9675 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009676 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009677
Sebastian Redl22653ba2011-08-30 19:58:05 +00009678 // Add the parameter to the operator.
9679 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9680 ClassLoc, ClassLoc, /*Id=*/0,
9681 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009682 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009683 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009684
Richard Smith6b02d462012-12-08 08:32:28 +00009685 AddOverriddenMethods(ClassDecl, MoveAssignment);
9686
9687 MoveAssignment->setTrivial(
9688 ClassDecl->needsOverloadResolutionForMoveAssignment()
9689 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9690 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009691
Richard Smithd951a1d2012-02-18 02:02:13 +00009692 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009693 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9694 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009695 }
9696
Richard Smith6b02d462012-12-08 08:32:28 +00009697 // Note that we have added this copy-assignment operator.
9698 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9699
Sebastian Redl22653ba2011-08-30 19:58:05 +00009700 if (Scope *S = getScopeForContext(ClassDecl))
9701 PushOnScopeChains(MoveAssignment, S, false);
9702 ClassDecl->addDecl(MoveAssignment);
9703
Sebastian Redl22653ba2011-08-30 19:58:05 +00009704 return MoveAssignment;
9705}
9706
Richard Smithb2504bd2013-11-04 04:26:14 +00009707/// Check if we're implicitly defining a move assignment operator for a class
9708/// with virtual bases. Such a move assignment might move-assign the virtual
9709/// base multiple times.
9710static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9711 SourceLocation CurrentLocation) {
9712 assert(!Class->isDependentContext() && "should not define dependent move");
9713
9714 // Only a virtual base could get implicitly move-assigned multiple times.
9715 // Only a non-trivial move assignment can observe this. We only want to
9716 // diagnose if we implicitly define an assignment operator that assigns
9717 // two base classes, both of which move-assign the same virtual base.
9718 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9719 Class->getNumBases() < 2)
9720 return;
9721
9722 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9723 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9724 VBaseMap VBases;
9725
Aaron Ballman574705e2014-03-13 15:41:46 +00009726 for (auto &BI : Class->bases()) {
9727 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009728 while (!Worklist.empty()) {
9729 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9730 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9731
9732 // If the base has no non-trivial move assignment operators,
9733 // we don't care about moves from it.
9734 if (!Base->hasNonTrivialMoveAssignment())
9735 continue;
9736
9737 // If there's nothing virtual here, skip it.
9738 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9739 continue;
9740
9741 // If we're not actually going to call a move assignment for this base,
9742 // or the selected move assignment is trivial, skip it.
9743 Sema::SpecialMemberOverloadResult *SMOR =
9744 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9745 /*ConstArg*/false, /*VolatileArg*/false,
9746 /*RValueThis*/true, /*ConstThis*/false,
9747 /*VolatileThis*/false);
9748 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9749 !SMOR->getMethod()->isMoveAssignmentOperator())
9750 continue;
9751
9752 if (BaseSpec->isVirtual()) {
9753 // We're going to move-assign this virtual base, and its move
9754 // assignment operator is not trivial. If this can happen for
9755 // multiple distinct direct bases of Class, diagnose it. (If it
9756 // only happens in one base, we'll diagnose it when synthesizing
9757 // that base class's move assignment operator.)
9758 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +00009759 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +00009760 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +00009761 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009762 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9763 << Class << Base;
9764 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9765 << (Base->getCanonicalDecl() ==
9766 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9767 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +00009768 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +00009769 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +00009770 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9771 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +00009772
9773 // Only diagnose each vbase once.
9774 Existing = 0;
9775 }
9776 } else {
9777 // Only walk over bases that have defaulted move assignment operators.
9778 // We assume that any user-provided move assignment operator handles
9779 // the multiple-moves-of-vbase case itself somehow.
9780 if (!SMOR->getMethod()->isDefaulted())
9781 continue;
9782
9783 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +00009784 for (auto &BI : Base->bases())
9785 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009786 }
9787 }
9788 }
9789}
9790
Sebastian Redl22653ba2011-08-30 19:58:05 +00009791void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9792 CXXMethodDecl *MoveAssignOperator) {
9793 assert((MoveAssignOperator->isDefaulted() &&
9794 MoveAssignOperator->isOverloadedOperator() &&
9795 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009796 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9797 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009798 "DefineImplicitMoveAssignment called for wrong function");
9799
9800 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9801
9802 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9803 MoveAssignOperator->setInvalidDecl();
9804 return;
9805 }
9806
Eli Friedman276dd182013-09-05 00:02:25 +00009807 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009808
Eli Friedmaneaf34142012-10-18 20:14:08 +00009809 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009810 DiagnosticErrorTrap Trap(Diags);
9811
9812 // C++0x [class.copy]p28:
9813 // The implicitly-defined or move assignment operator for a non-union class
9814 // X performs memberwise move assignment of its subobjects. The direct base
9815 // classes of X are assigned first, in the order of their declaration in the
9816 // base-specifier-list, and then the immediate non-static data members of X
9817 // are assigned, in the order in which they were declared in the class
9818 // definition.
9819
Richard Smithb2504bd2013-11-04 04:26:14 +00009820 // Issue a warning if our implicit move assignment operator will move
9821 // from a virtual base more than once.
9822 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009823
Sebastian Redl22653ba2011-08-30 19:58:05 +00009824 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009825 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009826
9827 // The parameter for the "other" object, which we are move from.
9828 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9829 QualType OtherRefType = Other->getType()->
9830 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009831 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009832 "Bad argument type of defaulted move assignment");
9833
9834 // Our location for everything implicitly-generated.
9835 SourceLocation Loc = MoveAssignOperator->getLocation();
9836
Pavel Labath58934982013-08-30 08:52:28 +00009837 // Builds a reference to the "other" object.
9838 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009839 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009840 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009841
Pavel Labath58934982013-08-30 08:52:28 +00009842 // Builds the "this" pointer.
9843 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009844
Sebastian Redl22653ba2011-08-30 19:58:05 +00009845 // Assign base classes.
9846 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009847 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009848 // C++11 [class.copy]p28:
9849 // It is unspecified whether subobjects representing virtual base classes
9850 // are assigned more than once by the implicitly-defined copy assignment
9851 // operator.
9852 // FIXME: Do not assign to a vbase that will be assigned by some other base
9853 // class. For a move-assignment, this can result in the vbase being moved
9854 // multiple times.
9855
Sebastian Redl22653ba2011-08-30 19:58:05 +00009856 // Form the assignment:
9857 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009858 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009859 if (!BaseType->isRecordType()) {
9860 Invalid = true;
9861 continue;
9862 }
9863
9864 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009865 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009866
9867 // Construct the "from" expression, which is an implicit cast to the
9868 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009869 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009870
9871 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009872 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009873
9874 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009875 CastBuilder To(DerefThis,
9876 Context.getCVRQualifiedType(
9877 BaseType, MoveAssignOperator->getTypeQualifiers()),
9878 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009879
9880 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009881 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009882 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009883 /*CopyingBaseSubobject=*/true,
9884 /*Copying=*/false);
9885 if (Move.isInvalid()) {
9886 Diag(CurrentLocation, diag::note_member_synthesized_at)
9887 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9888 MoveAssignOperator->setInvalidDecl();
9889 return;
9890 }
9891
9892 // Success! Record the move.
9893 Statements.push_back(Move.takeAs<Expr>());
9894 }
9895
Sebastian Redl22653ba2011-08-30 19:58:05 +00009896 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009897 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009898 if (Field->isUnnamedBitfield())
9899 continue;
9900
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009901 if (Field->isInvalidDecl()) {
9902 Invalid = true;
9903 continue;
9904 }
9905
Sebastian Redl22653ba2011-08-30 19:58:05 +00009906 // Check for members of reference type; we can't move those.
9907 if (Field->getType()->isReferenceType()) {
9908 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9909 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9910 Diag(Field->getLocation(), diag::note_declared_at);
9911 Diag(CurrentLocation, diag::note_member_synthesized_at)
9912 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9913 Invalid = true;
9914 continue;
9915 }
9916
9917 // Check for members of const-qualified, non-class type.
9918 QualType BaseType = Context.getBaseElementType(Field->getType());
9919 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9920 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9921 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9922 Diag(Field->getLocation(), diag::note_declared_at);
9923 Diag(CurrentLocation, diag::note_member_synthesized_at)
9924 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9925 Invalid = true;
9926 continue;
9927 }
9928
9929 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009930 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9931 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009932
9933 QualType FieldType = Field->getType().getNonReferenceType();
9934 if (FieldType->isIncompleteArrayType()) {
9935 assert(ClassDecl->hasFlexibleArrayMember() &&
9936 "Incomplete array type is not valid");
9937 continue;
9938 }
9939
9940 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009941 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9942 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009943 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009944 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009945 MemberBuilder From(MoveOther, OtherRefType,
9946 /*IsArrow=*/false, MemberLookup);
9947 MemberBuilder To(This, getCurrentThisType(),
9948 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009949
Pavel Labath58934982013-08-30 08:52:28 +00009950 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +00009951 "Member reference with rvalue base must be rvalue except for reference "
9952 "members, which aren't allowed for move assignment.");
9953
Sebastian Redl22653ba2011-08-30 19:58:05 +00009954 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009955 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009956 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009957 /*CopyingBaseSubobject=*/false,
9958 /*Copying=*/false);
9959 if (Move.isInvalid()) {
9960 Diag(CurrentLocation, diag::note_member_synthesized_at)
9961 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9962 MoveAssignOperator->setInvalidDecl();
9963 return;
9964 }
Richard Smith11d19592012-11-12 23:33:00 +00009965
Sebastian Redl22653ba2011-08-30 19:58:05 +00009966 // Success! Record the copy.
9967 Statements.push_back(Move.takeAs<Stmt>());
9968 }
9969
9970 if (!Invalid) {
9971 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009972 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00009973
9974 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9975 if (Return.isInvalid())
9976 Invalid = true;
9977 else {
9978 Statements.push_back(Return.takeAs<Stmt>());
9979
9980 if (Trap.hasErrorOccurred()) {
9981 Diag(CurrentLocation, diag::note_member_synthesized_at)
9982 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9983 Invalid = true;
9984 }
9985 }
9986 }
9987
9988 if (Invalid) {
9989 MoveAssignOperator->setInvalidDecl();
9990 return;
9991 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009992
9993 StmtResult Body;
9994 {
9995 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009996 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009997 /*isStmtExpr=*/false);
9998 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9999 }
Sebastian Redl22653ba2011-08-30 19:58:05 +000010000 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
10001
10002 if (ASTMutationListener *L = getASTMutationListener()) {
10003 L->CompletedImplicitDefinition(MoveAssignOperator);
10004 }
10005}
10006
Richard Smithd3b5c9082012-07-27 04:22:15 +000010007Sema::ImplicitExceptionSpecification
10008Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10009 CXXRecordDecl *ClassDecl = MD->getParent();
10010
10011 ImplicitExceptionSpecification ExceptSpec(*this);
10012 if (ClassDecl->isInvalidDecl())
10013 return ExceptSpec;
10014
10015 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010016 assert(T->getNumParams() >= 1 && "not a copy ctor");
10017 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010018
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010019 // C++ [except.spec]p14:
10020 // An implicitly declared special member function (Clause 12) shall have an
10021 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010022 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010023 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010024 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010025 continue;
10026
Douglas Gregora6d69502010-07-02 23:41:54 +000010027 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010028 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010029 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010030 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010031 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010032 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010033 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010034 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010035 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010036 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010037 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010038 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010039 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010040 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010041 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010042 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10043 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010044 LookupCopyingConstructor(FieldClassDecl,
10045 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010046 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010047 }
10048 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010049
Richard Smithd3b5c9082012-07-27 04:22:15 +000010050 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010051}
10052
10053CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10054 CXXRecordDecl *ClassDecl) {
10055 // C++ [class.copy]p4:
10056 // If the class definition does not explicitly declare a copy
10057 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010058 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010059
Richard Smith8bf22e52012-11-29 01:34:07 +000010060 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10061 if (DSM.isAlreadyBeingDeclared())
10062 return 0;
10063
Alexis Hunt913820d2011-05-13 06:10:58 +000010064 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10065 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010066 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010067 if (Const)
10068 ArgType = ArgType.withConst();
10069 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010070
Richard Smithb5800092012-06-10 05:43:50 +000010071 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10072 CXXCopyConstructor,
10073 Const);
10074
Douglas Gregor54be3392010-07-01 17:57:27 +000010075 DeclarationName Name
10076 = Context.DeclarationNames.getCXXConstructorName(
10077 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010078 SourceLocation ClassLoc = ClassDecl->getLocation();
10079 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010080
10081 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010082 // member of its class.
10083 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010084 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010085 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010086 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010087 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010088 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010089
Richard Smithd3b5c9082012-07-27 04:22:15 +000010090 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010091 FunctionProtoType::ExtProtoInfo EPI =
10092 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010093 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010094 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010095
Douglas Gregor54be3392010-07-01 17:57:27 +000010096 // Add the parameter to the constructor.
10097 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010098 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +000010099 /*IdentifierInfo=*/0,
10100 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +000010101 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010102 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010103
Richard Smith6b02d462012-12-08 08:32:28 +000010104 CopyConstructor->setTrivial(
10105 ClassDecl->needsOverloadResolutionForCopyConstructor()
10106 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10107 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010108
Richard Smith852265f2012-03-30 20:53:28 +000010109 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010110 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010111
Richard Smith6b02d462012-12-08 08:32:28 +000010112 // Note that we have declared this constructor.
10113 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10114
10115 if (Scope *S = getScopeForContext(ClassDecl))
10116 PushOnScopeChains(CopyConstructor, S, false);
10117 ClassDecl->addDecl(CopyConstructor);
10118
Douglas Gregor54be3392010-07-01 17:57:27 +000010119 return CopyConstructor;
10120}
10121
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010122void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010123 CXXConstructorDecl *CopyConstructor) {
10124 assert((CopyConstructor->isDefaulted() &&
10125 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010126 !CopyConstructor->doesThisDeclarationHaveABody() &&
10127 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010128 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010129
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010130 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010131 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010132
Richard Smithd577fbb2013-06-13 03:23:42 +000010133 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010134 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010135 // deprecated if the class has a user-declared copy assignment operator
10136 // or a user-declared destructor.
10137 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10138 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10139
Eli Friedmaneaf34142012-10-18 20:14:08 +000010140 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010141 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010142
David Blaikie3fc2f912013-01-17 05:26:25 +000010143 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010144 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010145 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010146 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010147 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010148 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010149 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010150 CopyConstructor->setBody(ActOnCompoundStmt(
10151 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10152 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010153 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010154
Eli Friedman276dd182013-09-05 00:02:25 +000010155 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010156 if (ASTMutationListener *L = getASTMutationListener()) {
10157 L->CompletedImplicitDefinition(CopyConstructor);
10158 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010159}
10160
Sebastian Redl22653ba2011-08-30 19:58:05 +000010161Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010162Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10163 CXXRecordDecl *ClassDecl = MD->getParent();
10164
Sebastian Redl22653ba2011-08-30 19:58:05 +000010165 // C++ [except.spec]p14:
10166 // An implicitly declared special member function (Clause 12) shall have an
10167 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010168 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010169 if (ClassDecl->isInvalidDecl())
10170 return ExceptSpec;
10171
10172 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010173 for (const auto &B : ClassDecl->bases()) {
10174 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010175 continue;
10176
Aaron Ballman574705e2014-03-13 15:41:46 +000010177 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010178 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010179 CXXConstructorDecl *Constructor =
10180 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010181 // If this is a deleted function, add it anyway. This might be conformant
10182 // with the standard. This might not. I'm not sure. It might not matter.
10183 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010184 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010185 }
10186 }
10187
10188 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010189 for (const auto &B : ClassDecl->vbases()) {
10190 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010191 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010192 CXXConstructorDecl *Constructor =
10193 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010194 // If this is a deleted function, add it anyway. This might be conformant
10195 // with the standard. This might not. I'm not sure. It might not matter.
10196 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010197 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010198 }
10199 }
10200
10201 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010202 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010203 QualType FieldType = Context.getBaseElementType(F->getType());
10204 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10205 CXXConstructorDecl *Constructor =
10206 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010207 // If this is a deleted function, add it anyway. This might be conformant
10208 // with the standard. This might not. I'm not sure. It might not matter.
10209 // In particular, the problem is that this function never gets called. It
10210 // might just be ill-formed because this function attempts to refer to
10211 // a deleted function here.
10212 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010213 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010214 }
10215 }
10216
10217 return ExceptSpec;
10218}
10219
10220CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10221 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010222 assert(ClassDecl->needsImplicitMoveConstructor());
10223
Richard Smith8bf22e52012-11-29 01:34:07 +000010224 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10225 if (DSM.isAlreadyBeingDeclared())
10226 return 0;
10227
Sebastian Redl22653ba2011-08-30 19:58:05 +000010228 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10229 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010230
Richard Smithb5800092012-06-10 05:43:50 +000010231 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10232 CXXMoveConstructor,
10233 false);
10234
Sebastian Redl22653ba2011-08-30 19:58:05 +000010235 DeclarationName Name
10236 = Context.DeclarationNames.getCXXConstructorName(
10237 Context.getCanonicalType(ClassType));
10238 SourceLocation ClassLoc = ClassDecl->getLocation();
10239 DeclarationNameInfo NameInfo(Name, ClassLoc);
10240
Richard Smith99005e62013-05-07 03:19:20 +000010241 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010242 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010243 // member of its class.
10244 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010245 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010246 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010247 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010248 MoveConstructor->setAccess(AS_public);
10249 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010250
Richard Smithd3b5c9082012-07-27 04:22:15 +000010251 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010252 FunctionProtoType::ExtProtoInfo EPI =
10253 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010254 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010255 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010256
Sebastian Redl22653ba2011-08-30 19:58:05 +000010257 // Add the parameter to the constructor.
10258 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10259 ClassLoc, ClassLoc,
10260 /*IdentifierInfo=*/0,
10261 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010262 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010263 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010264
Richard Smith6b02d462012-12-08 08:32:28 +000010265 MoveConstructor->setTrivial(
10266 ClassDecl->needsOverloadResolutionForMoveConstructor()
10267 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10268 : ClassDecl->hasTrivialMoveConstructor());
10269
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010270 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010271 ClassDecl->setImplicitMoveConstructorIsDeleted();
10272 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010273 }
10274
10275 // Note that we have declared this constructor.
10276 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10277
10278 if (Scope *S = getScopeForContext(ClassDecl))
10279 PushOnScopeChains(MoveConstructor, S, false);
10280 ClassDecl->addDecl(MoveConstructor);
10281
10282 return MoveConstructor;
10283}
10284
10285void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10286 CXXConstructorDecl *MoveConstructor) {
10287 assert((MoveConstructor->isDefaulted() &&
10288 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010289 !MoveConstructor->doesThisDeclarationHaveABody() &&
10290 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010291 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10292
10293 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10294 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10295
Eli Friedmaneaf34142012-10-18 20:14:08 +000010296 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010297 DiagnosticErrorTrap Trap(Diags);
10298
David Blaikie3fc2f912013-01-17 05:26:25 +000010299 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010300 Trap.hasErrorOccurred()) {
10301 Diag(CurrentLocation, diag::note_member_synthesized_at)
10302 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10303 MoveConstructor->setInvalidDecl();
10304 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010305 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010306 MoveConstructor->setBody(ActOnCompoundStmt(
10307 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10308 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010309 }
10310
Eli Friedman276dd182013-09-05 00:02:25 +000010311 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010312
10313 if (ASTMutationListener *L = getASTMutationListener()) {
10314 L->CompletedImplicitDefinition(MoveConstructor);
10315 }
10316}
10317
Douglas Gregor74f7d502012-02-15 19:33:52 +000010318bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010319 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010320}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010321
10322void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010323 SourceLocation CurrentLocation,
10324 CXXConversionDecl *Conv) {
10325 CXXRecordDecl *Lambda = Conv->getParent();
10326 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10327 // If we are defining a specialization of a conversion to function-ptr
10328 // cache the deduced template arguments for this specialization
10329 // so that we can use them to retrieve the corresponding call-operator
10330 // and static-invoker.
10331 const TemplateArgumentList *DeducedTemplateArgs = 0;
10332
Douglas Gregor355efbb2012-02-17 03:02:34 +000010333
Faisal Vali571df122013-09-29 08:45:24 +000010334 // Retrieve the corresponding call-operator specialization.
10335 if (Lambda->isGenericLambda()) {
10336 assert(Conv->isFunctionTemplateSpecialization());
10337 FunctionTemplateDecl *CallOpTemplate =
10338 CallOp->getDescribedFunctionTemplate();
10339 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10340 void *InsertPos = 0;
10341 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10342 DeducedTemplateArgs->data(),
10343 DeducedTemplateArgs->size(),
10344 InsertPos);
10345 assert(CallOpSpec &&
10346 "Conversion operator must have a corresponding call operator");
10347 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10348 }
10349 // Mark the call operator referenced (and add to pending instantiations
10350 // if necessary).
10351 // For both the conversion and static-invoker template specializations
10352 // we construct their body's in this function, so no need to add them
10353 // to the PendingInstantiations.
10354 MarkFunctionReferenced(CurrentLocation, CallOp);
10355
Eli Friedmaneaf34142012-10-18 20:14:08 +000010356 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010357 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010358
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010359 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010360 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10361 // ... and get the corresponding specialization for a generic lambda.
10362 if (Lambda->isGenericLambda()) {
10363 assert(DeducedTemplateArgs &&
10364 "Must have deduced template arguments from Conversion Operator");
10365 FunctionTemplateDecl *InvokeTemplate =
10366 Invoker->getDescribedFunctionTemplate();
10367 void *InsertPos = 0;
10368 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10369 DeducedTemplateArgs->data(),
10370 DeducedTemplateArgs->size(),
10371 InsertPos);
10372 assert(InvokeSpec &&
10373 "Must have a corresponding static invoker specialization");
10374 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10375 }
10376 // Construct the body of the conversion function { return __invoke; }.
10377 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10378 VK_LValue, Conv->getLocation()).take();
10379 assert(FunctionRef && "Can't refer to __invoke function?");
10380 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10381 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10382 Conv->getLocation(),
10383 Conv->getLocation()));
10384
10385 Conv->markUsed(Context);
10386 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010387
Faisal Vali571df122013-09-29 08:45:24 +000010388 // Fill in the __invoke function with a dummy implementation. IR generation
10389 // will fill in the actual details.
10390 Invoker->markUsed(Context);
10391 Invoker->setReferenced();
10392 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10393
Douglas Gregord3b672c2012-02-16 01:06:16 +000010394 if (ASTMutationListener *L = getASTMutationListener()) {
10395 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010396 L->CompletedImplicitDefinition(Invoker);
10397 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010398}
10399
Faisal Vali571df122013-09-29 08:45:24 +000010400
10401
Douglas Gregord3b672c2012-02-16 01:06:16 +000010402void Sema::DefineImplicitLambdaToBlockPointerConversion(
10403 SourceLocation CurrentLocation,
10404 CXXConversionDecl *Conv)
10405{
Faisal Vali850da1a2013-09-29 17:08:32 +000010406 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010407
Eli Friedman276dd182013-09-05 00:02:25 +000010408 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010409
Eli Friedmaneaf34142012-10-18 20:14:08 +000010410 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010411 DiagnosticErrorTrap Trap(Diags);
10412
Douglas Gregored90df32012-02-22 05:02:47 +000010413 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010414 Expr *This = ActOnCXXThis(CurrentLocation).take();
10415 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010416
Eli Friedman98b01ed2012-03-01 04:01:32 +000010417 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10418 Conv->getLocation(),
10419 Conv, DerefThis);
10420
10421 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10422 // behavior. Note that only the general conversion function does this
10423 // (since it's unusable otherwise); in the case where we inline the
10424 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010425 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010426 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10427 CK_CopyAndAutoreleaseBlockObject,
10428 BuildBlock.get(), 0, VK_RValue);
10429
10430 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010431 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010432 Conv->setInvalidDecl();
10433 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010434 }
Douglas Gregored90df32012-02-22 05:02:47 +000010435
Douglas Gregored90df32012-02-22 05:02:47 +000010436 // Create the return statement that returns the block from the conversion
10437 // function.
Eli Friedman98b01ed2012-03-01 04:01:32 +000010438 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010439 if (Return.isInvalid()) {
10440 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10441 Conv->setInvalidDecl();
10442 return;
10443 }
10444
10445 // Set the body of the conversion function.
10446 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010447 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010448 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010449 Conv->getLocation()));
10450
Douglas Gregored90df32012-02-22 05:02:47 +000010451 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010452 if (ASTMutationListener *L = getASTMutationListener()) {
10453 L->CompletedImplicitDefinition(Conv);
10454 }
10455}
10456
Douglas Gregord2f70072012-03-10 06:53:13 +000010457/// \brief Determine whether the given list arguments contains exactly one
10458/// "real" (non-default) argument.
10459static bool hasOneRealArgument(MultiExprArg Args) {
10460 switch (Args.size()) {
10461 case 0:
10462 return false;
10463
10464 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010465 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010466 return false;
10467
10468 // fall through
10469 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010470 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010471 }
10472
10473 return false;
10474}
10475
John McCalldadc5752010-08-24 06:29:42 +000010476ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010477Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010478 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010479 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010480 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010481 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010482 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010483 unsigned ConstructKind,
10484 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010485 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010486
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010487 // C++0x [class.copy]p34:
10488 // When certain criteria are met, an implementation is allowed to
10489 // omit the copy/move construction of a class object, even if the
10490 // copy/move constructor and/or destructor for the object have
10491 // side effects. [...]
10492 // - when a temporary class object that has not been bound to a
10493 // reference (12.2) would be copied/moved to a class object
10494 // with the same cv-unqualified type, the copy/move operation
10495 // can be omitted by constructing the temporary object
10496 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010497 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010498 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010499 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010500 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010501 }
Mike Stump11289f42009-09-09 15:08:12 +000010502
10503 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010504 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010505 IsListInitialization, RequiresZeroInit,
10506 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010507}
10508
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010509/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10510/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010511ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010512Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10513 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010514 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010515 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010516 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010517 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010518 unsigned ConstructKind,
10519 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010520 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010521 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010522 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010523 HadMultipleCandidates,
10524 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010525 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10526 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010527}
10528
John McCall03c48482010-02-02 09:10:11 +000010529void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010530 if (VD->isInvalidDecl()) return;
10531
John McCall03c48482010-02-02 09:10:11 +000010532 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010533 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010534 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010535 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010536
Chandler Carruth86d17d32011-03-27 21:26:48 +000010537 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010538 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010539 CheckDestructorAccess(VD->getLocation(), Destructor,
10540 PDiag(diag::err_access_dtor_var)
10541 << VD->getDeclName()
10542 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010543 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010544
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010545 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010546 if (!VD->hasGlobalStorage()) return;
10547
10548 // Emit warning for non-trivial dtor in global scope (a real global,
10549 // class-static, function-static).
10550 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10551
10552 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010553 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000010554 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010555}
10556
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010557/// \brief Given a constructor and the set of arguments provided for the
10558/// constructor, convert the arguments and add any required default arguments
10559/// to form a proper call to this constructor.
10560///
10561/// \returns true if an error occurred, false otherwise.
10562bool
10563Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10564 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010565 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010566 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010567 bool AllowExplicit,
10568 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010569 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10570 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010571 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010572
10573 const FunctionProtoType *Proto
10574 = Constructor->getType()->getAs<FunctionProtoType>();
10575 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010576 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010577
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010578 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010579 if (NumArgs < NumParams)
10580 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010581 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010582 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010583
10584 VariadicCallType CallType =
10585 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010586 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010587 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010588 Proto, 0,
10589 llvm::makeArrayRef(Args, NumArgs),
10590 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010591 CallType, AllowExplicit,
10592 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010593 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010594
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010595 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010596
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010597 CheckConstructorCall(Constructor,
10598 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10599 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010600 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010601
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010602 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010603}
10604
Anders Carlssone363c8e2009-12-12 00:32:00 +000010605static inline bool
10606CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10607 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010608 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010609 if (isa<NamespaceDecl>(DC)) {
10610 return SemaRef.Diag(FnDecl->getLocation(),
10611 diag::err_operator_new_delete_declared_in_namespace)
10612 << FnDecl->getDeclName();
10613 }
10614
10615 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010616 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010617 return SemaRef.Diag(FnDecl->getLocation(),
10618 diag::err_operator_new_delete_declared_static)
10619 << FnDecl->getDeclName();
10620 }
10621
Anders Carlsson60659a82009-12-12 02:43:16 +000010622 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010623}
10624
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010625static inline bool
10626CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10627 CanQualType ExpectedResultType,
10628 CanQualType ExpectedFirstParamType,
10629 unsigned DependentParamTypeDiag,
10630 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010631 QualType ResultType =
10632 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010633
10634 // Check that the result type is not dependent.
10635 if (ResultType->isDependentType())
10636 return SemaRef.Diag(FnDecl->getLocation(),
10637 diag::err_operator_new_delete_dependent_result_type)
10638 << FnDecl->getDeclName() << ExpectedResultType;
10639
10640 // Check that the result type is what we expect.
10641 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10642 return SemaRef.Diag(FnDecl->getLocation(),
10643 diag::err_operator_new_delete_invalid_result_type)
10644 << FnDecl->getDeclName() << ExpectedResultType;
10645
10646 // A function template must have at least 2 parameters.
10647 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10648 return SemaRef.Diag(FnDecl->getLocation(),
10649 diag::err_operator_new_delete_template_too_few_parameters)
10650 << FnDecl->getDeclName();
10651
10652 // The function decl must have at least 1 parameter.
10653 if (FnDecl->getNumParams() == 0)
10654 return SemaRef.Diag(FnDecl->getLocation(),
10655 diag::err_operator_new_delete_too_few_parameters)
10656 << FnDecl->getDeclName();
10657
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010658 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010659 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10660 if (FirstParamType->isDependentType())
10661 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10662 << FnDecl->getDeclName() << ExpectedFirstParamType;
10663
10664 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010665 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010666 ExpectedFirstParamType)
10667 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10668 << FnDecl->getDeclName() << ExpectedFirstParamType;
10669
10670 return false;
10671}
10672
Anders Carlsson12308f42009-12-11 23:23:22 +000010673static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010674CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010675 // C++ [basic.stc.dynamic.allocation]p1:
10676 // A program is ill-formed if an allocation function is declared in a
10677 // namespace scope other than global scope or declared static in global
10678 // scope.
10679 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10680 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010681
10682 CanQualType SizeTy =
10683 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10684
10685 // C++ [basic.stc.dynamic.allocation]p1:
10686 // The return type shall be void*. The first parameter shall have type
10687 // std::size_t.
10688 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10689 SizeTy,
10690 diag::err_operator_new_dependent_param_type,
10691 diag::err_operator_new_param_type))
10692 return true;
10693
10694 // C++ [basic.stc.dynamic.allocation]p1:
10695 // The first parameter shall not have an associated default argument.
10696 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010697 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010698 diag::err_operator_new_default_arg)
10699 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10700
10701 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010702}
10703
10704static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010705CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010706 // C++ [basic.stc.dynamic.deallocation]p1:
10707 // A program is ill-formed if deallocation functions are declared in a
10708 // namespace scope other than global scope or declared static in global
10709 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010710 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10711 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010712
10713 // C++ [basic.stc.dynamic.deallocation]p2:
10714 // Each deallocation function shall return void and its first parameter
10715 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010716 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10717 SemaRef.Context.VoidPtrTy,
10718 diag::err_operator_delete_dependent_param_type,
10719 diag::err_operator_delete_param_type))
10720 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010721
Anders Carlsson12308f42009-12-11 23:23:22 +000010722 return false;
10723}
10724
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010725/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10726/// of this overloaded operator is well-formed. If so, returns false;
10727/// otherwise, emits appropriate diagnostics and returns true.
10728bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010729 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010730 "Expected an overloaded operator declaration");
10731
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010732 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10733
Mike Stump11289f42009-09-09 15:08:12 +000010734 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010735 // The allocation and deallocation functions, operator new,
10736 // operator new[], operator delete and operator delete[], are
10737 // described completely in 3.7.3. The attributes and restrictions
10738 // found in the rest of this subclause do not apply to them unless
10739 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010740 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010741 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010742
Anders Carlsson22f443f2009-12-12 00:26:23 +000010743 if (Op == OO_New || Op == OO_Array_New)
10744 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010745
10746 // C++ [over.oper]p6:
10747 // An operator function shall either be a non-static member
10748 // function or be a non-member function and have at least one
10749 // parameter whose type is a class, a reference to a class, an
10750 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010751 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10752 if (MethodDecl->isStatic())
10753 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010754 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010755 } else {
10756 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010757 for (auto Param : FnDecl->params()) {
10758 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010759 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10760 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010761 ClassOrEnumParam = true;
10762 break;
10763 }
10764 }
10765
Douglas Gregord69246b2008-11-17 16:14:12 +000010766 if (!ClassOrEnumParam)
10767 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010768 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010769 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010770 }
10771
10772 // C++ [over.oper]p8:
10773 // An operator function cannot have default arguments (8.3.6),
10774 // except where explicitly stated below.
10775 //
Mike Stump11289f42009-09-09 15:08:12 +000010776 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010777 // (C++ [over.call]p1).
10778 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010779 for (auto Param : FnDecl->params()) {
10780 if (Param->hasDefaultArg())
10781 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010782 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010783 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010784 }
10785 }
10786
Douglas Gregor6cf08062008-11-10 13:38:07 +000010787 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10788 { false, false, false }
10789#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10790 , { Unary, Binary, MemberOnly }
10791#include "clang/Basic/OperatorKinds.def"
10792 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010793
Douglas Gregor6cf08062008-11-10 13:38:07 +000010794 bool CanBeUnaryOperator = OperatorUses[Op][0];
10795 bool CanBeBinaryOperator = OperatorUses[Op][1];
10796 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010797
10798 // C++ [over.oper]p8:
10799 // [...] Operator functions cannot have more or fewer parameters
10800 // than the number required for the corresponding operator, as
10801 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010802 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010803 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010804 if (Op != OO_Call &&
10805 ((NumParams == 1 && !CanBeUnaryOperator) ||
10806 (NumParams == 2 && !CanBeBinaryOperator) ||
10807 (NumParams < 1) || (NumParams > 2))) {
10808 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010809 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010810 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010811 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010812 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010813 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010814 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010815 assert(CanBeBinaryOperator &&
10816 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010817 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010818 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010819
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010820 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010821 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010822 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010823
Douglas Gregord69246b2008-11-17 16:14:12 +000010824 // Overloaded operators other than operator() cannot be variadic.
10825 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010826 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010827 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010828 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010829 }
10830
10831 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010832 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10833 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010834 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010835 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010836 }
10837
10838 // C++ [over.inc]p1:
10839 // The user-defined function called operator++ implements the
10840 // prefix and postfix ++ operator. If this function is a member
10841 // function with no parameters, or a non-member function with one
10842 // parameter of class or enumeration type, it defines the prefix
10843 // increment operator ++ for objects of that type. If the function
10844 // is a member function with one parameter (which shall be of type
10845 // int) or a non-member function with two parameters (the second
10846 // of which shall be of type int), it defines the postfix
10847 // increment operator ++ for objects of that type.
10848 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10849 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000010850 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010851
Richard Smith538b52a2014-01-30 22:24:05 +000010852 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10853 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000010854 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010855 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010856 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010857 }
10858
Douglas Gregord69246b2008-11-17 16:14:12 +000010859 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010860}
Chris Lattner3b024a32008-12-17 07:09:26 +000010861
Alexis Huntc88db062010-01-13 09:01:02 +000010862/// CheckLiteralOperatorDeclaration - Check whether the declaration
10863/// of this literal operator function is well-formed. If so, returns
10864/// false; otherwise, emits appropriate diagnostics and returns true.
10865bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010866 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010867 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10868 << FnDecl->getDeclName();
10869 return true;
10870 }
10871
Richard Smith72eebee2012-03-04 09:41:16 +000010872 if (FnDecl->isExternC()) {
10873 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10874 return true;
10875 }
10876
Alexis Huntc88db062010-01-13 09:01:02 +000010877 bool Valid = false;
10878
Richard Smithbcc22fc2012-03-09 08:00:36 +000010879 // This might be the definition of a literal operator template.
10880 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10881 // This might be a specialization of a literal operator template.
10882 if (!TpDecl)
10883 TpDecl = FnDecl->getPrimaryTemplate();
10884
Richard Smithb8b41d32013-10-07 19:57:58 +000010885 // template <char...> type operator "" name() and
10886 // template <class T, T...> type operator "" name() are the only valid
10887 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010888 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010889 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000010890 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000010891 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10892 if (Params->size() == 1) {
10893 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010894 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010895
Alexis Hunt7dd26172010-04-07 23:11:06 +000010896 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010897 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10898 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10899 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000010900 } else if (Params->size() == 2) {
10901 TemplateTypeParmDecl *PmType =
10902 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10903 NonTypeTemplateParmDecl *PmArgs =
10904 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10905
10906 // The second template parameter must be a parameter pack with the
10907 // first template parameter as its type.
10908 if (PmType && PmArgs &&
10909 !PmType->isTemplateParameterPack() &&
10910 PmArgs->isTemplateParameterPack()) {
10911 const TemplateTypeParmType *TArgs =
10912 PmArgs->getType()->getAs<TemplateTypeParmType>();
10913 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10914 TArgs->getIndex() == PmType->getIndex()) {
10915 Valid = true;
10916 if (ActiveTemplateInstantiations.empty())
10917 Diag(FnDecl->getLocation(),
10918 diag::ext_string_literal_operator_template);
10919 }
10920 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000010921 }
10922 }
Richard Smith72eebee2012-03-04 09:41:16 +000010923 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010924 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010925 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10926
Richard Smith72eebee2012-03-04 09:41:16 +000010927 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010928
Alexis Hunt079a6f72010-04-07 22:57:35 +000010929 // unsigned long long int, long double, and any character type are allowed
10930 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010931 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10932 Context.hasSameType(T, Context.LongDoubleTy) ||
10933 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010934 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010935 Context.hasSameType(T, Context.Char16Ty) ||
10936 Context.hasSameType(T, Context.Char32Ty)) {
10937 if (++Param == FnDecl->param_end())
10938 Valid = true;
10939 goto FinishedParams;
10940 }
10941
Alexis Hunt079a6f72010-04-07 22:57:35 +000010942 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000010943 const PointerType *PT = T->getAs<PointerType>();
10944 if (!PT)
10945 goto FinishedParams;
10946 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000010947 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000010948 goto FinishedParams;
10949 T = T.getUnqualifiedType();
10950
10951 // Move on to the second parameter;
10952 ++Param;
10953
10954 // If there is no second parameter, the first must be a const char *
10955 if (Param == FnDecl->param_end()) {
10956 if (Context.hasSameType(T, Context.CharTy))
10957 Valid = true;
10958 goto FinishedParams;
10959 }
10960
10961 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10962 // are allowed as the first parameter to a two-parameter function
10963 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010964 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010965 Context.hasSameType(T, Context.Char16Ty) ||
10966 Context.hasSameType(T, Context.Char32Ty)))
10967 goto FinishedParams;
10968
10969 // The second and final parameter must be an std::size_t
10970 T = (*Param)->getType().getUnqualifiedType();
10971 if (Context.hasSameType(T, Context.getSizeType()) &&
10972 ++Param == FnDecl->param_end())
10973 Valid = true;
10974 }
10975
10976 // FIXME: This diagnostic is absolutely terrible.
10977FinishedParams:
10978 if (!Valid) {
10979 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10980 << FnDecl->getDeclName();
10981 return true;
10982 }
10983
Richard Smith768cecc2012-03-09 08:16:22 +000010984 // A parameter-declaration-clause containing a default argument is not
10985 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010986 for (auto Param : FnDecl->params()) {
10987 if (Param->hasDefaultArg()) {
10988 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000010989 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010990 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000010991 break;
10992 }
10993 }
10994
Richard Smith0df56f42012-03-08 02:39:21 +000010995 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000010996 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10997 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000010998 // C++11 [usrlit.suffix]p1:
10999 // Literal suffix identifiers that do not start with an underscore
11000 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011001 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11002 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011003 }
Richard Smith0df56f42012-03-08 02:39:21 +000011004
Alexis Huntc88db062010-01-13 09:01:02 +000011005 return false;
11006}
11007
Douglas Gregor07665a62009-01-05 19:45:36 +000011008/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11009/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011010/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11011/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011012/// the '{' brace. Otherwise, this linkage specification does not
11013/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011014Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011015 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011016 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011017 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11018 if (!Lit->isAscii()) {
11019 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11020 << LangStr->getSourceRange();
11021 return 0;
11022 }
11023
11024 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011025 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011026 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011027 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011028 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011029 Language = LinkageSpecDecl::lang_cxx;
11030 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011031 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11032 << LangStr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011033 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000011034 }
Mike Stump11289f42009-09-09 15:08:12 +000011035
Chris Lattner438e5012008-12-17 07:13:27 +000011036 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011037
Richard Smith4ee696d2014-02-17 23:25:27 +000011038 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11039 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011040 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011041 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011042 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011043 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011044}
11045
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011046/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011047/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11048/// valid, it's the position of the closing '}' brace in a linkage
11049/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011050Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011051 Decl *LinkageSpec,
11052 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011053 if (RBraceLoc.isValid()) {
11054 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11055 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011056 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011057 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011058 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011059}
11060
Michael Han84324352013-02-22 17:15:32 +000011061Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11062 AttributeList *AttrList,
11063 SourceLocation SemiLoc) {
11064 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11065 // Attribute declarations appertain to empty declaration so we handle
11066 // them here.
11067 if (AttrList)
11068 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011069
Michael Han84324352013-02-22 17:15:32 +000011070 CurContext->addDecl(ED);
11071 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011072}
11073
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011074/// \brief Perform semantic analysis for the variable declaration that
11075/// occurs within a C++ catch clause, returning the newly-created
11076/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011077VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011078 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011079 SourceLocation StartLoc,
11080 SourceLocation Loc,
11081 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011082 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011083 QualType ExDeclType = TInfo->getType();
11084
Sebastian Redl54c04d42008-12-22 19:15:10 +000011085 // Arrays and functions decay.
11086 if (ExDeclType->isArrayType())
11087 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11088 else if (ExDeclType->isFunctionType())
11089 ExDeclType = Context.getPointerType(ExDeclType);
11090
11091 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11092 // The exception-declaration shall not denote a pointer or reference to an
11093 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011094 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011095 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011096 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011097 Invalid = true;
11098 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011099
Sebastian Redl54c04d42008-12-22 19:15:10 +000011100 QualType BaseType = ExDeclType;
11101 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011102 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011103 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011104 BaseType = Ptr->getPointeeType();
11105 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011106 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011107 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011108 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011109 BaseType = Ref->getPointeeType();
11110 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011111 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011112 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011113 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011114 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011115 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011116
Mike Stump11289f42009-09-09 15:08:12 +000011117 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011118 RequireNonAbstractType(Loc, ExDeclType,
11119 diag::err_abstract_type_in_decl,
11120 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011121 Invalid = true;
11122
John McCall2ca705e2010-07-24 00:37:23 +000011123 // Only the non-fragile NeXT runtime currently supports C++ catches
11124 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011125 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011126 QualType T = ExDeclType;
11127 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11128 T = RT->getPointeeType();
11129
11130 if (T->isObjCObjectType()) {
11131 Diag(Loc, diag::err_objc_object_catch);
11132 Invalid = true;
11133 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011134 // FIXME: should this be a test for macosx-fragile specifically?
11135 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011136 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011137 }
11138 }
11139
Abramo Bagnaradff19302011-03-08 08:55:46 +000011140 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011141 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011142 ExDecl->setExceptionVariable(true);
11143
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011144 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011145 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011146 Invalid = true;
11147
Douglas Gregor750734c2011-07-06 18:14:43 +000011148 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011149 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011150 // Insulate this from anything else we might currently be parsing.
11151 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11152
Douglas Gregor6de584c2010-03-05 23:38:39 +000011153 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011154 // The object declared in an exception-declaration or, if the
11155 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011156 // copy-initialized (8.5) from the exception object. [...]
11157 // The object is destroyed when the handler exits, after the destruction
11158 // of any automatic objects initialized within the handler.
11159 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011160 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011161 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011162 QualType initType = ExDeclType;
11163
11164 InitializedEntity entity =
11165 InitializedEntity::InitializeVariable(ExDecl);
11166 InitializationKind initKind =
11167 InitializationKind::CreateCopy(Loc, SourceLocation());
11168
11169 Expr *opaqueValue =
11170 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011171 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11172 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011173 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011174 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011175 else {
11176 // If the constructor used was non-trivial, set this as the
11177 // "initializer".
Nick Lewycky0f292892013-09-22 10:06:57 +000011178 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011179 if (!construct->getConstructor()->isTrivial()) {
11180 Expr *init = MaybeCreateExprWithCleanups(construct);
11181 ExDecl->setInit(init);
11182 }
11183
11184 // And make sure it's destructable.
11185 FinalizeVarWithDestructor(ExDecl, recordType);
11186 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011187 }
11188 }
11189
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011190 if (Invalid)
11191 ExDecl->setInvalidDecl();
11192
11193 return ExDecl;
11194}
11195
11196/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11197/// handler.
John McCall48871652010-08-21 09:40:31 +000011198Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011199 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011200 bool Invalid = D.isInvalidType();
11201
11202 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011203 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11204 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011205 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11206 D.getIdentifierLoc());
11207 Invalid = true;
11208 }
11209
Sebastian Redl54c04d42008-12-22 19:15:10 +000011210 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011211 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011212 LookupOrdinaryName,
11213 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011214 // The scope should be freshly made just for us. There is just no way
11215 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000011216 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000011217 if (PrevDecl->isTemplateParameter()) {
11218 // Maybe we will complain about the shadowed template parameter.
11219 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000011220 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011221 }
11222 }
11223
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011224 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011225 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11226 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011227 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011228 }
11229
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011230 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011231 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011232 D.getIdentifierLoc(),
11233 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011234 if (Invalid)
11235 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011236
Sebastian Redl54c04d42008-12-22 19:15:10 +000011237 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011238 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011239 PushOnScopeChains(ExDecl, S);
11240 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011241 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011242
Douglas Gregor758a8692009-06-17 21:51:59 +000011243 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011244 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011245}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011246
Abramo Bagnaraea947882011-03-08 16:41:52 +000011247Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011248 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011249 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011250 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011251 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011252
Richard Smithded9c2e2012-07-11 22:37:56 +000011253 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11254 return 0;
11255
11256 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11257 AssertMessage, RParenLoc, false);
11258}
11259
11260Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11261 Expr *AssertExpr,
11262 StringLiteral *AssertMessage,
11263 SourceLocation RParenLoc,
11264 bool Failed) {
11265 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11266 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011267 // In a static_assert-declaration, the constant-expression shall be a
11268 // constant expression that can be contextually converted to bool.
11269 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11270 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011271 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011272
Richard Smith902ca212011-12-14 23:32:26 +000011273 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011274 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011275 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011276 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011277 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011278
Richard Smithded9c2e2012-07-11 22:37:56 +000011279 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011280 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011281 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000011282 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011283 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011284 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011285 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011286 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011287 }
Mike Stump11289f42009-09-09 15:08:12 +000011288
Abramo Bagnaraea947882011-03-08 16:41:52 +000011289 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011290 AssertExpr, AssertMessage, RParenLoc,
11291 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011292
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011293 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011294 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011295}
Sebastian Redlf769df52009-03-24 22:27:57 +000011296
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011297/// \brief Perform semantic analysis of the given friend type declaration.
11298///
11299/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011300FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011301 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011302 TypeSourceInfo *TSInfo) {
11303 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11304
11305 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011306 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011307
Richard Smithc8239732011-10-18 21:39:00 +000011308 // C++03 [class.friend]p2:
11309 // An elaborated-type-specifier shall be used in a friend declaration
11310 // for a class.*
11311 //
11312 // * The class-key of the elaborated-type-specifier is required.
11313 if (!ActiveTemplateInstantiations.empty()) {
11314 // Do not complain about the form of friend template types during
11315 // template instantiation; we will already have complained when the
11316 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011317 } else {
11318 if (!T->isElaboratedTypeSpecifier()) {
11319 // If we evaluated the type to a record type, suggest putting
11320 // a tag in front.
11321 if (const RecordType *RT = T->getAs<RecordType>()) {
11322 RecordDecl *RD = RT->getDecl();
Richard Smithc8239732011-10-18 21:39:00 +000011323
Nick Lewycky36722d22013-02-06 05:59:33 +000011324 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smithc8239732011-10-18 21:39:00 +000011325
Nick Lewycky36722d22013-02-06 05:59:33 +000011326 Diag(TypeRange.getBegin(),
11327 getLangOpts().CPlusPlus11 ?
11328 diag::warn_cxx98_compat_unelaborated_friend_type :
11329 diag::ext_unelaborated_friend_type)
11330 << (unsigned) RD->getTagKind()
11331 << T
11332 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11333 InsertionText);
11334 } else {
11335 Diag(FriendLoc,
11336 getLangOpts().CPlusPlus11 ?
11337 diag::warn_cxx98_compat_nonclass_type_friend :
11338 diag::ext_nonclass_type_friend)
11339 << T
11340 << TypeRange;
11341 }
11342 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011343 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011344 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011345 diag::warn_cxx98_compat_enum_friend :
11346 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011347 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011348 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011349 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011350
Nick Lewycky36722d22013-02-06 05:59:33 +000011351 // C++11 [class.friend]p3:
11352 // A friend declaration that does not declare a function shall have one
11353 // of the following forms:
11354 // friend elaborated-type-specifier ;
11355 // friend simple-type-specifier ;
11356 // friend typename-specifier ;
11357 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11358 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11359 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011360
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011361 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011362 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011363 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000011364 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011365}
11366
John McCallace48cd2010-10-19 01:40:49 +000011367/// Handle a friend tag declaration where the scope specifier was
11368/// templated.
11369Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11370 unsigned TagSpec, SourceLocation TagLoc,
11371 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011372 IdentifierInfo *Name,
11373 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011374 AttributeList *Attr,
11375 MultiTemplateParamsArg TempParamLists) {
11376 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11377
11378 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011379 bool Invalid = false;
11380
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011381 if (TemplateParameterList *TemplateParams =
11382 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +000011383 TagLoc, NameLoc, SS, 0, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011384 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011385 if (TemplateParams->size() > 0) {
11386 // This is a declaration of a class template.
11387 if (Invalid)
11388 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011389
Eric Christopher6f228b52011-07-21 05:34:24 +000011390 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11391 SS, Name, NameLoc, Attr,
11392 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011393 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011394 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011395 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000011396 } else {
11397 // The "template<>" header is extraneous.
11398 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11399 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11400 isExplicitSpecialization = true;
11401 }
11402 }
11403
11404 if (Invalid) return 0;
11405
John McCallace48cd2010-10-19 01:40:49 +000011406 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011407 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011408 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011409 isAllExplicitSpecializations = false;
11410 break;
11411 }
11412 }
11413
11414 // FIXME: don't ignore attributes.
11415
11416 // If it's explicit specializations all the way down, just forget
11417 // about the template header and build an appropriate non-templated
11418 // friend. TODO: for source fidelity, remember the headers.
11419 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011420 if (SS.isEmpty()) {
11421 bool Owned = false;
11422 bool IsDependent = false;
11423 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011424 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011425 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011426 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011427 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011428 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011429 /*UnderlyingType=*/TypeResult(),
11430 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011431 }
Richard Smith649c7b062014-01-08 00:56:48 +000011432
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011433 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011434 ElaboratedTypeKeyword Keyword
11435 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011436 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011437 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011438 if (T.isNull())
11439 return 0;
11440
11441 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11442 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011443 DependentNameTypeLoc TL =
11444 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011445 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011446 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011447 TL.setNameLoc(NameLoc);
11448 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011449 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011450 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011451 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011452 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011453 }
11454
11455 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011456 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011457 Friend->setAccess(AS_public);
11458 CurContext->addDecl(Friend);
11459 return Friend;
11460 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011461
11462 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11463
11464
John McCallace48cd2010-10-19 01:40:49 +000011465
11466 // Handle the case of a templated-scope friend class. e.g.
11467 // template <class T> class A<T>::B;
11468 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011469 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11470 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011471 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11472 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11473 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011474 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011475 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011476 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011477 TL.setNameLoc(NameLoc);
11478
11479 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011480 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011481 Friend->setAccess(AS_public);
11482 Friend->setUnsupportedFriend(true);
11483 CurContext->addDecl(Friend);
11484 return Friend;
11485}
11486
11487
John McCall11083da2009-09-16 22:47:08 +000011488/// Handle a friend type declaration. This works in tandem with
11489/// ActOnTag.
11490///
11491/// Notes on friend class templates:
11492///
11493/// We generally treat friend class declarations as if they were
11494/// declaring a class. So, for example, the elaborated type specifier
11495/// in a friend declaration is required to obey the restrictions of a
11496/// class-head (i.e. no typedefs in the scope chain), template
11497/// parameters are required to match up with simple template-ids, &c.
11498/// However, unlike when declaring a template specialization, it's
11499/// okay to refer to a template specialization without an empty
11500/// template parameter declaration, e.g.
11501/// friend class A<T>::B<unsigned>;
11502/// We permit this as a special case; if there are any template
11503/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011504/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011505Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011506 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011507 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011508
11509 assert(DS.isFriendSpecified());
11510 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11511
John McCall11083da2009-09-16 22:47:08 +000011512 // Try to convert the decl specifier to a type. This works for
11513 // friend templates because ActOnTag never produces a ClassTemplateDecl
11514 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011515 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011516 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11517 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011518 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011519 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011520
Douglas Gregor6c110f32010-12-16 01:14:37 +000011521 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11522 return 0;
11523
John McCall11083da2009-09-16 22:47:08 +000011524 // This is definitely an error in C++98. It's probably meant to
11525 // be forbidden in C++0x, too, but the specification is just
11526 // poorly written.
11527 //
11528 // The problem is with declarations like the following:
11529 // template <T> friend A<T>::foo;
11530 // where deciding whether a class C is a friend or not now hinges
11531 // on whether there exists an instantiation of A that causes
11532 // 'foo' to equal C. There are restrictions on class-heads
11533 // (which we declare (by fiat) elaborated friend declarations to
11534 // be) that makes this tractable.
11535 //
11536 // FIXME: handle "template <> friend class A<T>;", which
11537 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011538 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011539 Diag(Loc, diag::err_tagless_friend_type_template)
11540 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011541 return 0;
John McCall11083da2009-09-16 22:47:08 +000011542 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011543
John McCallaa74a0c2009-08-28 07:59:38 +000011544 // C++98 [class.friend]p1: A friend of a class is a function
11545 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011546 // This is fixed in DR77, which just barely didn't make the C++03
11547 // deadline. It's also a very silly restriction that seriously
11548 // affects inner classes and which nobody else seems to implement;
11549 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011550 //
11551 // But note that we could warn about it: it's always useless to
11552 // friend one of your own members (it's not, however, worthless to
11553 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011554
John McCall11083da2009-09-16 22:47:08 +000011555 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011556 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011557 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011558 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011559 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011560 TSI,
John McCall11083da2009-09-16 22:47:08 +000011561 DS.getFriendSpecLoc());
11562 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011563 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011564
11565 if (!D)
John McCall48871652010-08-21 09:40:31 +000011566 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011567
John McCall11083da2009-09-16 22:47:08 +000011568 D->setAccess(AS_public);
11569 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011570
John McCall48871652010-08-21 09:40:31 +000011571 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011572}
11573
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011574NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11575 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011576 const DeclSpec &DS = D.getDeclSpec();
11577
11578 assert(DS.isFriendSpecified());
11579 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11580
11581 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011582 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011583
11584 // C++ [class.friend]p1
11585 // A friend of a class is a function or class....
11586 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011587 // It *doesn't* see through dependent types, which is correct
11588 // according to [temp.arg.type]p3:
11589 // If a declaration acquires a function type through a
11590 // type dependent on a template-parameter and this causes
11591 // a declaration that does not use the syntactic form of a
11592 // function declarator to have a function type, the program
11593 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011594 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011595 Diag(Loc, diag::err_unexpected_friend);
11596
11597 // It might be worthwhile to try to recover by creating an
11598 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011599 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011600 }
11601
11602 // C++ [namespace.memdef]p3
11603 // - If a friend declaration in a non-local class first declares a
11604 // class or function, the friend class or function is a member
11605 // of the innermost enclosing namespace.
11606 // - The name of the friend is not found by simple name lookup
11607 // until a matching declaration is provided in that namespace
11608 // scope (either before or after the class declaration granting
11609 // friendship).
11610 // - If a friend function is called, its name may be found by the
11611 // name lookup that considers functions from namespaces and
11612 // classes associated with the types of the function arguments.
11613 // - When looking for a prior declaration of a class or a function
11614 // declared as a friend, scopes outside the innermost enclosing
11615 // namespace scope are not considered.
11616
John McCallde3fd222010-10-12 23:13:28 +000011617 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011618 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11619 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011620 assert(Name);
11621
Douglas Gregor6c110f32010-12-16 01:14:37 +000011622 // Check for unexpanded parameter packs.
11623 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11624 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11625 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11626 return 0;
11627
John McCall07e91c02009-08-06 02:15:43 +000011628 // The context we found the declaration in, or in which we should
11629 // create the declaration.
11630 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011631 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011632 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011633 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011634
Richard Smith114394f2013-08-09 04:35:01 +000011635 // There are five cases here.
11636 // - There's no scope specifier and we're in a local class. Only look
11637 // for functions declared in the immediately-enclosing block scope.
11638 // We recover from invalid scope qualifiers as if they just weren't there.
11639 FunctionDecl *FunctionContainingLocalClass = 0;
11640 if ((SS.isInvalid() || !SS.isSet()) &&
11641 (FunctionContainingLocalClass =
11642 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11643 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011644 // If a friend declaration appears in a local class and the name
11645 // specified is an unqualified name, a prior declaration is
11646 // looked up without considering scopes that are outside the
11647 // innermost enclosing non-class scope. For a friend function
11648 // declaration, if there is no prior declaration, the program is
11649 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011650
11651 // Find the innermost enclosing non-class scope. This is the block
11652 // scope containing the local class definition (or for a nested class,
11653 // the outer local class).
11654 DCScope = S->getFnParent();
11655
11656 // Look up the function name in the scope.
11657 Previous.clear(LookupLocalFriendName);
11658 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11659
11660 if (!Previous.empty()) {
11661 // All possible previous declarations must have the same context:
11662 // either they were declared at block scope or they are members of
11663 // one of the enclosing local classes.
11664 DC = Previous.getRepresentativeDecl()->getDeclContext();
11665 } else {
11666 // This is ill-formed, but provide the context that we would have
11667 // declared the function in, if we were permitted to, for error recovery.
11668 DC = FunctionContainingLocalClass;
11669 }
Richard Smith541b38b2013-09-20 01:15:31 +000011670 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011671
11672 // C++ [class.friend]p6:
11673 // A function can be defined in a friend declaration of a class if and
11674 // only if the class is a non-local class (9.8), the function name is
11675 // unqualified, and the function has namespace scope.
11676 if (D.isFunctionDefinition()) {
11677 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11678 }
11679
11680 // - There's no scope specifier, in which case we just go to the
11681 // appropriate scope and look for a function or function template
11682 // there as appropriate.
11683 } else if (SS.isInvalid() || !SS.isSet()) {
11684 // C++11 [namespace.memdef]p3:
11685 // If the name in a friend declaration is neither qualified nor
11686 // a template-id and the declaration is a function or an
11687 // elaborated-type-specifier, the lookup to determine whether
11688 // the entity has been previously declared shall not consider
11689 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011690 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011691
John McCallf7cfb222010-10-13 05:45:15 +000011692 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011693 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011694
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011695 // Skip class contexts. If someone can cite chapter and verse
11696 // for this behavior, that would be nice --- it's what GCC and
11697 // EDG do, and it seems like a reasonable intent, but the spec
11698 // really only says that checks for unqualified existing
11699 // declarations should stop at the nearest enclosing namespace,
11700 // not that they should only consider the nearest enclosing
11701 // namespace.
11702 while (DC->isRecord())
11703 DC = DC->getParent();
11704
11705 DeclContext *LookupDC = DC;
11706 while (LookupDC->isTransparentContext())
11707 LookupDC = LookupDC->getParent();
11708
11709 while (true) {
11710 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011711
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011712 if (!Previous.empty()) {
11713 DC = LookupDC;
11714 break;
John McCallf4776592010-10-14 22:22:28 +000011715 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011716
11717 if (isTemplateId) {
11718 if (isa<TranslationUnitDecl>(LookupDC)) break;
11719 } else {
11720 if (LookupDC->isFileContext()) break;
11721 }
11722 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011723 }
11724
John McCallccbc0322010-10-13 06:22:15 +000011725 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011726
John McCallde3fd222010-10-12 23:13:28 +000011727 // - There's a non-dependent scope specifier, in which case we
11728 // compute it and do a previous lookup there for a function
11729 // or function template.
11730 } else if (!SS.getScopeRep()->isDependent()) {
11731 DC = computeDeclContext(SS);
11732 if (!DC) return 0;
11733
11734 if (RequireCompleteDeclContext(SS, DC)) return 0;
11735
11736 LookupQualifiedName(Previous, DC);
11737
11738 // Ignore things found implicitly in the wrong scope.
11739 // TODO: better diagnostics for this case. Suggesting the right
11740 // qualified scope would be nice...
11741 LookupResult::Filter F = Previous.makeFilter();
11742 while (F.hasNext()) {
11743 NamedDecl *D = F.next();
11744 if (!DC->InEnclosingNamespaceSetOf(
11745 D->getDeclContext()->getRedeclContext()))
11746 F.erase();
11747 }
11748 F.done();
11749
11750 if (Previous.empty()) {
11751 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011752 Diag(Loc, diag::err_qualified_friend_not_found)
11753 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011754 return 0;
11755 }
11756
11757 // C++ [class.friend]p1: A friend of a class is a function or
11758 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011759 if (DC->Equals(CurContext))
11760 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011761 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011762 diag::warn_cxx98_compat_friend_is_member :
11763 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011764
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011765 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011766 // C++ [class.friend]p6:
11767 // A function can be defined in a friend declaration of a class if and
11768 // only if the class is a non-local class (9.8), the function name is
11769 // unqualified, and the function has namespace scope.
11770 SemaDiagnosticBuilder DB
11771 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11772
11773 DB << SS.getScopeRep();
11774 if (DC->isFileContext())
11775 DB << FixItHint::CreateRemoval(SS.getRange());
11776 SS.clear();
11777 }
John McCallde3fd222010-10-12 23:13:28 +000011778
11779 // - There's a scope specifier that does not match any template
11780 // parameter lists, in which case we use some arbitrary context,
11781 // create a method or method template, and wait for instantiation.
11782 // - There's a scope specifier that does match some template
11783 // parameter lists, which we don't handle right now.
11784 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011785 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011786 // C++ [class.friend]p6:
11787 // A function can be defined in a friend declaration of a class if and
11788 // only if the class is a non-local class (9.8), the function name is
11789 // unqualified, and the function has namespace scope.
11790 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11791 << SS.getScopeRep();
11792 }
11793
John McCallde3fd222010-10-12 23:13:28 +000011794 DC = CurContext;
11795 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011796 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011797
John McCallf7cfb222010-10-13 05:45:15 +000011798 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011799 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011800 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11801 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11802 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011803 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011804 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11805 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011806 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011807 }
John McCall07e91c02009-08-06 02:15:43 +000011808 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011809
Douglas Gregordd847ba2011-11-03 16:37:14 +000011810 // FIXME: This is an egregious hack to cope with cases where the scope stack
11811 // does not contain the declaration context, i.e., in an out-of-line
11812 // definition of a class.
11813 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11814 if (!DCScope) {
11815 FakeDCScope.setEntity(DC);
11816 DCScope = &FakeDCScope;
11817 }
Richard Smith114394f2013-08-09 04:35:01 +000011818
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011819 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011820 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011821 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011822 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011823
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011824 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011825
Richard Smith114394f2013-08-09 04:35:01 +000011826 // If we performed typo correction, we might have added a scope specifier
11827 // and changed the decl context.
11828 DC = ND->getDeclContext();
11829
John McCall759e32b2009-08-31 22:39:49 +000011830 // Add the function declaration to the appropriate lookup tables,
11831 // adjusting the redeclarations list as necessary. We don't
11832 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011833 //
John McCall759e32b2009-08-31 22:39:49 +000011834 // Also update the scope-based lookup if the target context's
11835 // lookup context is in lexical scope.
11836 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011837 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011838 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011839 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011840 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011841 }
John McCallaa74a0c2009-08-28 07:59:38 +000011842
11843 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011844 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011845 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011846 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011847 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011848
John McCalla0a96892012-08-10 03:15:35 +000011849 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011850 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011851 } else {
11852 if (DC->isRecord()) CheckFriendAccess(ND);
11853
John McCall2c2eb122010-10-16 06:59:13 +000011854 FunctionDecl *FD;
11855 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11856 FD = FTD->getTemplatedDecl();
11857 else
11858 FD = cast<FunctionDecl>(ND);
11859
David Majnemer502b0ed2013-06-25 23:09:30 +000011860 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11861 // default argument expression, that declaration shall be a definition
11862 // and shall be the only declaration of the function or function
11863 // template in the translation unit.
11864 if (functionDeclHasDefaultArgument(FD)) {
11865 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11866 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11867 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11868 } else if (!D.isFunctionDefinition())
11869 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11870 }
11871
John McCall2c2eb122010-10-16 06:59:13 +000011872 // Mark templated-scope function declarations as unsupported.
11873 if (FD->getNumTemplateParameterLists())
11874 FrD->setUnsupportedFriend(true);
11875 }
John McCallde3fd222010-10-12 23:13:28 +000011876
John McCall48871652010-08-21 09:40:31 +000011877 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011878}
11879
John McCall48871652010-08-21 09:40:31 +000011880void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11881 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011882
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011883 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011884 if (!Fn) {
11885 Diag(DelLoc, diag::err_deleted_non_function);
11886 return;
11887 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011888
Douglas Gregorec9fd132012-01-14 16:38:05 +000011889 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011890 // Don't consider the implicit declaration we generate for explicit
11891 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000011892 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11893 Prev->getPreviousDecl()) &&
11894 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011895 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000011896 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11897 Prev->isImplicit() ? diag::note_previous_implicit_declaration
11898 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000011899 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011900 // If the declaration wasn't the first, we delete the function anyway for
11901 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011902 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011903 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011904
11905 if (Fn->isDeleted())
11906 return;
11907
11908 // See if we're deleting a function which is already known to override a
11909 // non-deleted virtual function.
11910 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11911 bool IssuedDiagnostic = false;
11912 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11913 E = MD->end_overridden_methods();
11914 I != E; ++I) {
11915 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11916 if (!IssuedDiagnostic) {
11917 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11918 IssuedDiagnostic = true;
11919 }
11920 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11921 }
11922 }
11923 }
11924
Richard Smithb63b6ee2014-01-22 01:43:19 +000011925 // C++11 [basic.start.main]p3:
11926 // A program that defines main as deleted [...] is ill-formed.
11927 if (Fn->isMain())
11928 Diag(DelLoc, diag::err_deleted_main);
11929
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011930 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011931}
Sebastian Redl4c018662009-04-27 21:33:24 +000011932
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011933void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011934 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011935
11936 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000011937 if (MD->getParent()->isDependentType()) {
11938 MD->setDefaulted();
11939 MD->setExplicitlyDefaulted();
11940 return;
11941 }
11942
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011943 CXXSpecialMember Member = getSpecialMember(MD);
11944 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000011945 if (!MD->isInvalidDecl())
11946 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011947 return;
11948 }
11949
11950 MD->setDefaulted();
11951 MD->setExplicitlyDefaulted();
11952
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011953 // If this definition appears within the record, do the checking when
11954 // the record is complete.
11955 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000011956 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011957 // Find the uninstantiated declaration that actually had the '= default'
11958 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000011959 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011960
Richard Smith3901dfe2013-03-27 00:22:47 +000011961 // If the method was defaulted on its first declaration, we will have
11962 // already performed the checking in CheckCompletedCXXClass. Such a
11963 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011964 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011965 return;
11966
Richard Smithd3b5c9082012-07-27 04:22:15 +000011967 CheckExplicitlyDefaultedSpecialMember(MD);
11968
Richard Smithbd305122012-12-11 01:14:52 +000011969 // The exception specification is needed because we are defining the
11970 // function.
11971 ResolveExceptionSpec(DefaultLoc,
11972 MD->getType()->castAs<FunctionProtoType>());
11973
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011974 if (MD->isInvalidDecl())
11975 return;
11976
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011977 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011978 case CXXDefaultConstructor:
11979 DefineImplicitDefaultConstructor(DefaultLoc,
11980 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000011981 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011982 case CXXCopyConstructor:
11983 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011984 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011985 case CXXCopyAssignment:
11986 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000011987 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011988 case CXXDestructor:
11989 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000011990 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011991 case CXXMoveConstructor:
11992 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000011993 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011994 case CXXMoveAssignment:
11995 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011996 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011997 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000011998 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011999 }
12000 } else {
12001 Diag(DefaultLoc, diag::err_default_special_members);
12002 }
12003}
12004
Sebastian Redl4c018662009-04-27 21:33:24 +000012005static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012006 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012007 Stmt *SubStmt = *CI;
12008 if (!SubStmt)
12009 continue;
12010 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012011 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012012 diag::err_return_in_constructor_handler);
12013 if (!isa<Expr>(SubStmt))
12014 SearchForReturnInStmt(Self, SubStmt);
12015 }
12016}
12017
12018void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12019 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12020 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12021 SearchForReturnInStmt(*this, Handler);
12022 }
12023}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012024
David Blaikie68f71a32013-01-18 23:03:15 +000012025bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012026 const CXXMethodDecl *Old) {
12027 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12028 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12029
12030 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12031
12032 // If the calling conventions match, everything is fine
12033 if (NewCC == OldCC)
12034 return false;
12035
Hans Wennborg2545efe2013-12-11 17:42:11 +000012036 // If the calling conventions mismatch because the new function is static,
12037 // suppress the calling convention mismatch error; the error about static
12038 // function override (err_static_overrides_virtual from
12039 // Sema::CheckFunctionDeclaration) is more clear.
12040 if (New->getStorageClass() == SC_Static)
12041 return false;
12042
Reid Kleckner78af0702013-08-27 23:08:25 +000012043 Diag(New->getLocation(),
12044 diag::err_conflicting_overriding_cc_attributes)
12045 << New->getDeclName() << New->getType() << Old->getType();
12046 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12047 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012048}
12049
Mike Stump11289f42009-09-09 15:08:12 +000012050bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012051 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012052 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12053 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012054
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012055 if (Context.hasSameType(NewTy, OldTy) ||
12056 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012057 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012058
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012059 // Check if the return types are covariant
12060 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012061
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012062 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012063 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12064 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012065 NewClassTy = NewPT->getPointeeType();
12066 OldClassTy = OldPT->getPointeeType();
12067 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012068 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12069 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12070 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12071 NewClassTy = NewRT->getPointeeType();
12072 OldClassTy = OldRT->getPointeeType();
12073 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012074 }
12075 }
Mike Stump11289f42009-09-09 15:08:12 +000012076
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012077 // The return types aren't either both pointers or references to a class type.
12078 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012079 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012080 diag::err_different_return_type_for_overriding_virtual_function)
12081 << New->getDeclName() << NewTy << OldTy;
12082 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012083
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012084 return true;
12085 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012086
Anders Carlssone60365b2009-12-31 18:34:24 +000012087 // C++ [class.virtual]p6:
12088 // If the return type of D::f differs from the return type of B::f, the
12089 // class type in the return type of D::f shall be complete at the point of
12090 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012091 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12092 if (!RT->isBeingDefined() &&
12093 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012094 diag::err_covariant_return_incomplete,
12095 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012096 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012097 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012098
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012099 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012100 // Check if the new class derives from the old class.
12101 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12102 Diag(New->getLocation(),
12103 diag::err_covariant_return_not_derived)
12104 << New->getDeclName() << NewTy << OldTy;
12105 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12106 return true;
12107 }
Mike Stump11289f42009-09-09 15:08:12 +000012108
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012109 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012110 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012111 diag::err_covariant_return_inaccessible_base,
12112 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12113 // FIXME: Should this point to the return type?
12114 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000012115 // FIXME: this note won't trigger for delayed access control
12116 // diagnostics, and it's impossible to get an undelayed error
12117 // here from access control during the original parse because
12118 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012119 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12120 return true;
12121 }
12122 }
Mike Stump11289f42009-09-09 15:08:12 +000012123
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012124 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012125 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012126 Diag(New->getLocation(),
12127 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012128 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012129 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12130 return true;
12131 };
Mike Stump11289f42009-09-09 15:08:12 +000012132
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012133
12134 // The new class type must have the same or less qualifiers as the old type.
12135 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12136 Diag(New->getLocation(),
12137 diag::err_covariant_return_type_class_type_more_qualified)
12138 << New->getDeclName() << NewTy << OldTy;
12139 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12140 return true;
12141 };
Mike Stump11289f42009-09-09 15:08:12 +000012142
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012143 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012144}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012145
Douglas Gregor21920e372009-12-01 17:24:26 +000012146/// \brief Mark the given method pure.
12147///
12148/// \param Method the method to be marked pure.
12149///
12150/// \param InitRange the source range that covers the "0" initializer.
12151bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012152 SourceLocation EndLoc = InitRange.getEnd();
12153 if (EndLoc.isValid())
12154 Method->setRangeEnd(EndLoc);
12155
Douglas Gregor21920e372009-12-01 17:24:26 +000012156 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12157 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012158 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012159 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012160
12161 if (!Method->isInvalidDecl())
12162 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12163 << Method->getDeclName() << InitRange;
12164 return true;
12165}
12166
Douglas Gregor926410d2012-02-21 02:22:07 +000012167/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012168static bool isStaticDataMember(const Decl *D) {
12169 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12170 return Var->isStaticDataMember();
12171
12172 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012173}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012174
John McCall1f4ee7b2009-12-19 09:28:58 +000012175/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12176/// an initializer for the out-of-line declaration 'Dcl'. The scope
12177/// is a fresh scope pushed for just this purpose.
12178///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012179/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12180/// static data member of class X, names should be looked up in the scope of
12181/// class X.
John McCall48871652010-08-21 09:40:31 +000012182void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012183 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012184 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012185
Richard Smitha2302242013-12-05 07:51:02 +000012186 // We will always have a nested name specifier here, but this declaration
12187 // might not be out of line if the specifier names the current namespace:
12188 // extern int n;
12189 // int ::n = 0;
12190 if (D->isOutOfLine())
12191 EnterDeclaratorContext(S, D->getDeclContext());
12192
Douglas Gregor926410d2012-02-21 02:22:07 +000012193 // If we are parsing the initializer for a static data member, push a
12194 // new expression evaluation context that is associated with this static
12195 // data member.
12196 if (isStaticDataMember(D))
12197 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012198}
12199
12200/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012201/// initializer for the out-of-line declaration 'D'.
12202void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012203 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012204 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012205
Douglas Gregor926410d2012-02-21 02:22:07 +000012206 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012207 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012208
Richard Smitha2302242013-12-05 07:51:02 +000012209 if (D->isOutOfLine())
12210 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012211}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012212
12213/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12214/// C++ if/switch/while/for statement.
12215/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012216DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012217 // C++ 6.4p2:
12218 // The declarator shall not specify a function or an array.
12219 // The type-specifier-seq shall not contain typedef and shall not declare a
12220 // new class or enumeration.
12221 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12222 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012223
12224 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012225 if (!Dcl)
12226 return true;
12227
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012228 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12229 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012230 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012231 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012232 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012233
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012234 return Dcl;
12235}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012236
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012237void Sema::LoadExternalVTableUses() {
12238 if (!ExternalSource)
12239 return;
12240
12241 SmallVector<ExternalVTableUse, 4> VTables;
12242 ExternalSource->ReadUsedVTables(VTables);
12243 SmallVector<VTableUse, 4> NewUses;
12244 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12245 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12246 = VTablesUsed.find(VTables[I].Record);
12247 // Even if a definition wasn't required before, it may be required now.
12248 if (Pos != VTablesUsed.end()) {
12249 if (!Pos->second && VTables[I].DefinitionRequired)
12250 Pos->second = true;
12251 continue;
12252 }
12253
12254 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12255 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12256 }
12257
12258 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12259}
12260
Douglas Gregor88d292c2010-05-13 16:44:06 +000012261void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12262 bool DefinitionRequired) {
12263 // Ignore any vtable uses in unevaluated operands or for classes that do
12264 // not have a vtable.
12265 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012266 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012267 return;
12268
Douglas Gregor88d292c2010-05-13 16:44:06 +000012269 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012270 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012271 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12272 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12273 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12274 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012275 // If we already had an entry, check to see if we are promoting this vtable
12276 // to required a definition. If so, we need to reappend to the VTableUses
12277 // list, since we may have already processed the first entry.
12278 if (DefinitionRequired && !Pos.first->second) {
12279 Pos.first->second = true;
12280 } else {
12281 // Otherwise, we can early exit.
12282 return;
12283 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012284 } else {
12285 // The Microsoft ABI requires that we perform the destructor body
12286 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12287 // the deleting destructor is emitted with the vtable, not with the
12288 // destructor definition as in the Itanium ABI.
12289 // If it has a definition, we do the check at that point instead.
12290 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12291 Class->hasUserDeclaredDestructor() &&
12292 !Class->getDestructor()->isDefined() &&
12293 !Class->getDestructor()->isDeleted()) {
12294 CheckDestructor(Class->getDestructor());
12295 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012296 }
12297
12298 // Local classes need to have their virtual members marked
12299 // immediately. For all other classes, we mark their virtual members
12300 // at the end of the translation unit.
12301 if (Class->isLocalClass())
12302 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012303 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012304 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012305}
12306
Douglas Gregor88d292c2010-05-13 16:44:06 +000012307bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012308 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012309 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012310 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012311
Douglas Gregor88d292c2010-05-13 16:44:06 +000012312 // Note: The VTableUses vector could grow as a result of marking
12313 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012314 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012315 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012316 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012317 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012318 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012319 if (!Class)
12320 continue;
12321
12322 SourceLocation Loc = VTableUses[I].second;
12323
Richard Smithd3b5c9082012-07-27 04:22:15 +000012324 bool DefineVTable = true;
12325
Douglas Gregor88d292c2010-05-13 16:44:06 +000012326 // If this class has a key function, but that key function is
12327 // defined in another translation unit, we don't need to emit the
12328 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012329 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012330 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012331 // The key function is in another translation unit.
12332 DefineVTable = false;
12333 TemplateSpecializationKind TSK =
12334 KeyFunction->getTemplateSpecializationKind();
12335 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12336 TSK != TSK_ImplicitInstantiation &&
12337 "Instantiations don't have key functions");
12338 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012339 } else if (!KeyFunction) {
12340 // If we have a class with no key function that is the subject
12341 // of an explicit instantiation declaration, suppress the
12342 // vtable; it will live with the explicit instantiation
12343 // definition.
12344 bool IsExplicitInstantiationDeclaration
12345 = Class->getTemplateSpecializationKind()
12346 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012347 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012348 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012349 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012350 if (TSK == TSK_ExplicitInstantiationDeclaration)
12351 IsExplicitInstantiationDeclaration = true;
12352 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12353 IsExplicitInstantiationDeclaration = false;
12354 break;
12355 }
12356 }
12357
12358 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012359 DefineVTable = false;
12360 }
12361
12362 // The exception specifications for all virtual members may be needed even
12363 // if we are not providing an authoritative form of the vtable in this TU.
12364 // We may choose to emit it available_externally anyway.
12365 if (!DefineVTable) {
12366 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12367 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012368 }
12369
12370 // Mark all of the virtual members of this class as referenced, so
12371 // that we can build a vtable. Then, tell the AST consumer that a
12372 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012373 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012374 MarkVirtualMembersReferenced(Loc, Class);
12375 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12376 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12377
12378 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012379 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012380 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012381 const FunctionDecl *KeyFunctionDef = 0;
12382 if (!KeyFunction ||
12383 (KeyFunction->hasBody(KeyFunctionDef) &&
12384 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012385 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12386 TSK_ExplicitInstantiationDefinition
12387 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12388 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012389 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012390 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012391 VTableUses.clear();
12392
Douglas Gregor97509692011-04-22 22:25:37 +000012393 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012394}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012395
Richard Smithd3b5c9082012-07-27 04:22:15 +000012396void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12397 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012398 for (const auto *I : RD->methods())
12399 if (I->isVirtual() && !I->isPure())
12400 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012401}
12402
Rafael Espindola5b334082010-03-26 00:36:59 +000012403void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12404 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012405 // Mark all functions which will appear in RD's vtable as used.
12406 CXXFinalOverriderMap FinalOverriders;
12407 RD->getFinalOverriders(FinalOverriders);
12408 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12409 E = FinalOverriders.end();
12410 I != E; ++I) {
12411 for (OverridingMethods::const_iterator OI = I->second.begin(),
12412 OE = I->second.end();
12413 OI != OE; ++OI) {
12414 assert(OI->second.size() > 0 && "no final overrider");
12415 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012416
Richard Smith4ff9ff92012-07-07 06:59:51 +000012417 // C++ [basic.def.odr]p2:
12418 // [...] A virtual member function is used if it is not pure. [...]
12419 if (!Overrider->isPure())
12420 MarkFunctionReferenced(Loc, Overrider);
12421 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012422 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012423
12424 // Only classes that have virtual bases need a VTT.
12425 if (RD->getNumVBases() == 0)
12426 return;
12427
Aaron Ballman574705e2014-03-13 15:41:46 +000012428 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012429 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012430 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012431 if (Base->getNumVBases() == 0)
12432 continue;
12433 MarkVirtualMembersReferenced(Loc, Base);
12434 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012435}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012436
12437/// SetIvarInitializers - This routine builds initialization ASTs for the
12438/// Objective-C implementation whose ivars need be initialized.
12439void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012440 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012441 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012442 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012443 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012444 CollectIvarsToConstructOrDestruct(OID, ivars);
12445 if (ivars.empty())
12446 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012447 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012448 for (unsigned i = 0; i < ivars.size(); i++) {
12449 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012450 if (Field->isInvalidDecl())
12451 continue;
12452
Alexis Hunt1d792652011-01-08 20:30:50 +000012453 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012454 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12455 InitializationKind InitKind =
12456 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012457
12458 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12459 ExprResult MemberInit =
12460 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012461 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012462 // Note, MemberInit could actually come back empty if no initialization
12463 // is required (e.g., because it would call a trivial default constructor)
12464 if (!MemberInit.get() || MemberInit.isInvalid())
12465 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012466
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012467 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012468 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12469 SourceLocation(),
12470 MemberInit.takeAs<Expr>(),
12471 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012472 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012473
12474 // Be sure that the destructor is accessible and is marked as referenced.
12475 if (const RecordType *RecordTy
12476 = Context.getBaseElementType(Field->getType())
12477 ->getAs<RecordType>()) {
12478 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012479 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012480 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012481 CheckDestructorAccess(Field->getLocation(), Destructor,
12482 PDiag(diag::err_access_dtor_ivar)
12483 << Context.getBaseElementType(Field->getType()));
12484 }
12485 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012486 }
12487 ObjCImplementation->setIvarInitializers(Context,
12488 AllToInit.data(), AllToInit.size());
12489 }
12490}
Alexis Hunt6118d662011-05-04 05:57:24 +000012491
Alexis Hunt27a761d2011-05-04 23:29:54 +000012492static
12493void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12494 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12495 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12496 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12497 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012498 if (Ctor->isInvalidDecl())
12499 return;
12500
Richard Smith802c4b72012-08-23 06:16:52 +000012501 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12502
12503 // Target may not be determinable yet, for instance if this is a dependent
12504 // call in an uninstantiated template.
12505 if (Target) {
12506 const FunctionDecl *FNTarget = 0;
12507 (void)Target->hasBody(FNTarget);
12508 Target = const_cast<CXXConstructorDecl*>(
12509 cast_or_null<CXXConstructorDecl>(FNTarget));
12510 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012511
12512 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12513 // Avoid dereferencing a null pointer here.
12514 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12515
12516 if (!Current.insert(Canonical))
12517 return;
12518
12519 // We know that beyond here, we aren't chaining into a cycle.
12520 if (!Target || !Target->isDelegatingConstructor() ||
12521 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012522 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012523 Current.clear();
12524 // We've hit a cycle.
12525 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12526 Current.count(TCanonical)) {
12527 // If we haven't diagnosed this cycle yet, do so now.
12528 if (!Invalid.count(TCanonical)) {
12529 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012530 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012531 << Ctor;
12532
Richard Smith802c4b72012-08-23 06:16:52 +000012533 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012534 if (TCanonical != Canonical)
12535 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12536
12537 CXXConstructorDecl *C = Target;
12538 while (C->getCanonicalDecl() != Canonical) {
Richard Smith802c4b72012-08-23 06:16:52 +000012539 const FunctionDecl *FNTarget = 0;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012540 (void)C->getTargetConstructor()->hasBody(FNTarget);
12541 assert(FNTarget && "Ctor cycle through bodiless function");
12542
Richard Smith802c4b72012-08-23 06:16:52 +000012543 C = const_cast<CXXConstructorDecl*>(
12544 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012545 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12546 }
12547 }
12548
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012549 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012550 Current.clear();
12551 } else {
12552 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12553 }
12554}
12555
12556
Alexis Hunt6118d662011-05-04 05:57:24 +000012557void Sema::CheckDelegatingCtorCycles() {
12558 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12559
Douglas Gregorbae31202011-07-27 21:57:17 +000012560 for (DelegatingCtorDeclsType::iterator
12561 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012562 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012563 I != E; ++I)
12564 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012565
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012566 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12567 CE = Invalid.end();
12568 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012569 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012570}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012571
Douglas Gregor3024f072012-04-16 07:05:22 +000012572namespace {
12573 /// \brief AST visitor that finds references to the 'this' expression.
12574 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12575 Sema &S;
12576
12577 public:
12578 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12579
12580 bool VisitCXXThisExpr(CXXThisExpr *E) {
12581 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12582 << E->isImplicit();
12583 return false;
12584 }
12585 };
12586}
12587
12588bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12589 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12590 if (!TSInfo)
12591 return false;
12592
12593 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012594 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012595 if (!ProtoTL)
12596 return false;
12597
12598 // C++11 [expr.prim.general]p3:
12599 // [The expression this] shall not appear before the optional
12600 // cv-qualifier-seq and it shall not appear within the declaration of a
12601 // static member function (although its type and value category are defined
12602 // within a static member function as they are within a non-static member
12603 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012604 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012605 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012606 FindCXXThisExpr Finder(*this);
12607
12608 // If the return type came after the cv-qualifier-seq, check it now.
12609 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012610 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012611 return true;
12612
12613 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012614 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12615 return true;
12616
12617 return checkThisInStaticMemberFunctionAttributes(Method);
12618}
12619
12620bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12621 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12622 if (!TSInfo)
12623 return false;
12624
12625 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012626 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012627 if (!ProtoTL)
12628 return false;
12629
David Blaikie6adc78e2013-02-18 22:06:02 +000012630 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012631 FindCXXThisExpr Finder(*this);
12632
Douglas Gregor3024f072012-04-16 07:05:22 +000012633 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012634 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012635 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012636 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012637 case EST_DynamicNone:
12638 case EST_MSAny:
12639 case EST_None:
12640 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012641
Douglas Gregor3024f072012-04-16 07:05:22 +000012642 case EST_ComputedNoexcept:
12643 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12644 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012645
Douglas Gregor3024f072012-04-16 07:05:22 +000012646 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012647 for (const auto &E : Proto->exceptions()) {
12648 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012649 return true;
12650 }
12651 break;
12652 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012653
12654 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012655}
12656
12657bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12658 FindCXXThisExpr Finder(*this);
12659
12660 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012661 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012662 // FIXME: This should be emitted by tblgen.
12663 Expr *Arg = 0;
12664 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012665 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012666 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012667 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012668 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012669 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012670 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012671 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012672 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012673 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012674 Arg = ETLF->getSuccessValue();
12675 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012676 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012677 Arg = STLF->getSuccessValue();
12678 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000012679 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012680 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012681 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012682 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012683 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012684 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012685 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012686 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012687 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12688 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12689 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012690 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012691
12692 if (Arg && !Finder.TraverseStmt(Arg))
12693 return true;
12694
12695 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12696 if (!Finder.TraverseStmt(Args[I]))
12697 return true;
12698 }
12699 }
12700
12701 return false;
12702}
12703
Douglas Gregor433e0532012-04-16 18:27:27 +000012704void
12705Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12706 ArrayRef<ParsedType> DynamicExceptions,
12707 ArrayRef<SourceRange> DynamicExceptionRanges,
12708 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012709 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012710 FunctionProtoType::ExtProtoInfo &EPI) {
12711 Exceptions.clear();
12712 EPI.ExceptionSpecType = EST;
12713 if (EST == EST_Dynamic) {
12714 Exceptions.reserve(DynamicExceptions.size());
12715 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12716 // FIXME: Preserve type source info.
12717 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12718
12719 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12720 collectUnexpandedParameterPacks(ET, Unexpanded);
12721 if (!Unexpanded.empty()) {
12722 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12723 UPPC_ExceptionType,
12724 Unexpanded);
12725 continue;
12726 }
12727
12728 // Check that the type is valid for an exception spec, and
12729 // drop it if not.
12730 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12731 Exceptions.push_back(ET);
12732 }
12733 EPI.NumExceptions = Exceptions.size();
12734 EPI.Exceptions = Exceptions.data();
12735 return;
12736 }
12737
12738 if (EST == EST_ComputedNoexcept) {
12739 // If an error occurred, there's no expression here.
12740 if (NoexceptExpr) {
12741 assert((NoexceptExpr->isTypeDependent() ||
12742 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12743 Context.BoolTy) &&
12744 "Parser should have made sure that the expression is boolean");
12745 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12746 EPI.ExceptionSpecType = EST_BasicNoexcept;
12747 return;
12748 }
12749
12750 if (!NoexceptExpr->isValueDependent())
12751 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012752 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012753 /*AllowFold*/ false).take();
12754 EPI.NoexceptExpr = NoexceptExpr;
12755 }
12756 return;
12757 }
12758}
12759
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012760/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12761Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12762 // Implicitly declared functions (e.g. copy constructors) are
12763 // __host__ __device__
12764 if (D->isImplicit())
12765 return CFT_HostDevice;
12766
12767 if (D->hasAttr<CUDAGlobalAttr>())
12768 return CFT_Global;
12769
12770 if (D->hasAttr<CUDADeviceAttr>()) {
12771 if (D->hasAttr<CUDAHostAttr>())
12772 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012773 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012774 }
12775
12776 return CFT_Host;
12777}
12778
12779bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12780 CUDAFunctionTarget CalleeTarget) {
12781 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12782 // Callable from the device only."
12783 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12784 return true;
12785
12786 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12787 // Callable from the host only."
12788 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12789 // Callable from the host only."
12790 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12791 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12792 return true;
12793
12794 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12795 return true;
12796
12797 return false;
12798}
John McCall5e77d762013-04-16 07:28:30 +000012799
12800/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12801///
12802MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12803 SourceLocation DeclStart,
12804 Declarator &D, Expr *BitWidth,
12805 InClassInitStyle InitStyle,
12806 AccessSpecifier AS,
12807 AttributeList *MSPropertyAttr) {
12808 IdentifierInfo *II = D.getIdentifier();
12809 if (!II) {
12810 Diag(DeclStart, diag::err_anonymous_property);
12811 return NULL;
12812 }
12813 SourceLocation Loc = D.getIdentifierLoc();
12814
12815 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12816 QualType T = TInfo->getType();
12817 if (getLangOpts().CPlusPlus) {
12818 CheckExtraCXXDefaultArguments(D);
12819
12820 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12821 UPPC_DataMemberType)) {
12822 D.setInvalidType();
12823 T = Context.IntTy;
12824 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12825 }
12826 }
12827
12828 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12829
12830 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12831 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12832 diag::err_invalid_thread)
12833 << DeclSpec::getSpecifierName(TSCS);
12834
12835 // Check to see if this name was declared as a member previously
12836 NamedDecl *PrevDecl = 0;
12837 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12838 LookupName(Previous, S);
12839 switch (Previous.getResultKind()) {
12840 case LookupResult::Found:
12841 case LookupResult::FoundUnresolvedValue:
12842 PrevDecl = Previous.getAsSingle<NamedDecl>();
12843 break;
12844
12845 case LookupResult::FoundOverloaded:
12846 PrevDecl = Previous.getRepresentativeDecl();
12847 break;
12848
12849 case LookupResult::NotFound:
12850 case LookupResult::NotFoundInCurrentInstantiation:
12851 case LookupResult::Ambiguous:
12852 break;
12853 }
12854
12855 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12856 // Maybe we will complain about the shadowed template parameter.
12857 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12858 // Just pretend that we didn't see the previous declaration.
12859 PrevDecl = 0;
12860 }
12861
12862 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12863 PrevDecl = 0;
12864
12865 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000012866 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000012867 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12868 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000012869 ProcessDeclAttributes(TUScope, NewPD, D);
12870 NewPD->setAccess(AS);
12871
12872 if (NewPD->isInvalidDecl())
12873 Record->setInvalidDecl();
12874
12875 if (D.getDeclSpec().isModulePrivateSpecified())
12876 NewPD->setModulePrivate();
12877
12878 if (NewPD->isInvalidDecl() && PrevDecl) {
12879 // Don't introduce NewFD into scope; there's already something
12880 // with the same name in the same scope.
12881 } else if (II) {
12882 PushOnScopeChains(NewPD, S);
12883 } else
12884 Record->addDecl(NewPD);
12885
12886 return NewPD;
12887}