blob: fbc3fd7eb8169c0297a3b657b32adbfaa0c1b911 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000030#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000031#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/CXXFieldCollector.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/ScopeInfo.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000042#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000043#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner58258242008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattnerb0d38442008-04-12 23:52:44 +000051namespace {
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000061
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 public:
Mike Stump11289f42009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000065
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 };
Chris Lattner58258242008-04-10 02:22:51 +000072
Chris Lattnerb0d38442008-04-12 23:52:44 +000073 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000079 }
80
Chris Lattnerb0d38442008-04-12 23:52:44 +000081 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000086 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107
Douglas Gregor8e12c382008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110
Douglas Gregor97a9c812008-11-04 14:32:21 +0000111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000119 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000120
John McCall7353c862013-04-09 01:56:28 +0000121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
Douglas Gregorf0d49512012-02-10 23:30:22 +0000138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
Chris Lattner58258242008-04-10 02:22:51 +0000148}
149
Richard Smithb7151b92013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If this function can throw any exceptions, make a note of that.
Richard Smithd3b5c9082012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith938f40b2011-06-11 17:19:42 +0000172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
174
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
177 return;
178
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
181 return;
182
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
188 return;
189 }
190
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
Richard Smithf623c962012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
200
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
209
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000215 for (const auto &E : Proto->exceptions())
216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
217 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000218}
219
Richard Smith938f40b2011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithf623c962012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssonc80a1272009-08-25 02:29:20 +0000249bool
John McCallb268a282010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssonc80a1272009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000271 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000273
Richard Smithc406cb72013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Anders Carlssonc80a1272009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000279
Douglas Gregor758cb672010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000292 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000293}
294
Chris Lattner58258242008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000298void
John McCall48871652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000302 return;
Mike Stump11289f42009-09-09 15:08:12 +0000303
John McCall48871652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner199abbc2008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlssonf1c26952009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump11289f42009-09-09 15:08:12 +0000327
John McCallb268a282010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000329}
330
Douglas Gregor58354032008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump11289f42009-09-09 15:08:12 +0000340
John McCall48871652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000342 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000343 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000344}
345
Douglas Gregor4d87df52008-12-16 21:30:33 +0000346/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000348void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000349 if (!param)
350 return;
Mike Stump11289f42009-09-09 15:08:12 +0000351
John McCall48871652010-08-21 09:40:31 +0000352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000353 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000354 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000355}
356
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000357/// CheckExtraCXXDefaultArguments - Check for any extra default
358/// arguments in the declarator, which is not a function declaration
359/// or definition and therefore is not permitted to have default
360/// arguments. This routine should be invoked for every declarator
361/// that is not a function declaration or definition.
362void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
363 // C++ [dcl.fct.default]p3
364 // A default argument expression shall be specified only in the
365 // parameter-declaration-clause of a function declaration or in a
366 // template-parameter (14.1). It shall not be specified for a
367 // parameter pack. If it is specified in a
368 // parameter-declaration-clause, it shall not occur within a
369 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000370 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000371 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000372 DeclaratorChunk &chunk = D.getTypeObject(i);
373 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000374 if (MightBeFunction) {
375 // This is a function declaration. It can have default arguments, but
376 // keep looking in case its return type is a function type with default
377 // arguments.
378 MightBeFunction = false;
379 continue;
380 }
Alp Tokerc5350722014-02-26 22:27:52 +0000381 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
382 ++argIdx) {
383 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000384 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000385 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000386 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000387 << SourceRange((*Toks)[1].getLocation(),
388 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000389 delete Toks;
Alp Tokerc5350722014-02-26 22:27:52 +0000390 chunk.Fun.Params[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000391 } else if (Param->getDefaultArg()) {
392 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
393 << Param->getDefaultArg()->getSourceRange();
394 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000395 }
396 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000397 } else if (chunk.Kind != DeclaratorChunk::Paren) {
398 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000399 }
400 }
401}
402
David Majnemer502b0ed2013-06-25 23:09:30 +0000403static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
404 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
405 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
406 if (!PVD->hasDefaultArg())
407 return false;
408 if (!PVD->hasInheritedDefaultArg())
409 return true;
410 }
411 return false;
412}
413
Craig Toppere4794282012-09-21 04:33:26 +0000414/// MergeCXXFunctionDecl - Merge two declarations of the same C++
415/// function, once we already know that they have the same
416/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
417/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000418bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
419 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000420 bool Invalid = false;
421
Chris Lattner199abbc2008-04-08 05:04:30 +0000422 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000423 // For non-template functions, default arguments can be added in
424 // later declarations of a function in the same
425 // scope. Declarations in different scopes have completely
426 // distinct sets of default arguments. That is, declarations in
427 // inner scopes do not acquire default arguments from
428 // declarations in outer scopes, and vice versa. In a given
429 // function declaration, all parameters subsequent to a
430 // parameter with a default argument shall have default
431 // arguments supplied in this or previous declarations. A
432 // default argument shall not be redefined by a later
433 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000434 //
435 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000436 // Except for member functions of class templates, the default arguments
437 // in a member function definition that appears outside of the class
438 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000439 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000440 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
441 ParmVarDecl *OldParam = Old->getParamDecl(p);
442 ParmVarDecl *NewParam = New->getParamDecl(p);
443
James Molloye9430032012-03-13 08:55:35 +0000444 bool OldParamHasDfl = OldParam->hasDefaultArg();
445 bool NewParamHasDfl = NewParam->hasDefaultArg();
446
447 NamedDecl *ND = Old;
Richard Smith541b38b2013-09-20 01:15:31 +0000448
449 // The declaration context corresponding to the scope is the semantic
450 // parent, unless this is a local function declaration, in which case
451 // it is that surrounding function.
452 DeclContext *ScopeDC = New->getLexicalDeclContext();
453 if (!ScopeDC->isFunctionOrMethod())
454 ScopeDC = New->getDeclContext();
455 if (S && !isDeclInScope(ND, ScopeDC, S) &&
456 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000457 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000458 // the same scope and this is not an out-of-line definition of
459 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000460 OldParamHasDfl = false;
461
462 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000463
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000464 unsigned DiagDefaultParamID =
465 diag::err_param_default_argument_redefinition;
466
467 // MSVC accepts that default parameters be redefined for member functions
468 // of template class. The new default parameter's value is ignored.
469 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000470 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000471 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
472 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000473 // Merge the old default argument into the new parameter.
474 NewParam->setHasInheritedDefaultArg();
475 if (OldParam->hasUninstantiatedDefaultArg())
476 NewParam->setUninstantiatedDefaultArg(
477 OldParam->getUninstantiatedDefaultArg());
478 else
479 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000480 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000481 Invalid = false;
482 }
483 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000484
Francois Pichet8cb243a2011-04-10 04:58:30 +0000485 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
486 // hint here. Alternatively, we could walk the type-source information
487 // for NewParam to find the last source location in the type... but it
488 // isn't worth the effort right now. This is the kind of test case that
489 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000490 // int f(int);
491 // void g(int (*fp)(int) = f);
492 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000493 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000494 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000495
496 // Look for the function declaration where the default argument was
497 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000498 for (FunctionDecl *Older = Old->getPreviousDecl();
499 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000500 if (!Older->getParamDecl(p)->hasDefaultArg())
501 break;
502
503 OldParam = Older->getParamDecl(p);
504 }
505
506 Diag(OldParam->getLocation(), diag::note_previous_definition)
507 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000508 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000509 // Merge the old default argument into the new parameter.
510 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000511 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000512 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000513 if (OldParam->hasUninstantiatedDefaultArg())
514 NewParam->setUninstantiatedDefaultArg(
515 OldParam->getUninstantiatedDefaultArg());
516 else
John McCalle61b02b2010-05-04 01:53:42 +0000517 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000518 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000519 if (New->getDescribedFunctionTemplate()) {
520 // Paragraph 4, quoted above, only applies to non-template functions.
521 Diag(NewParam->getLocation(),
522 diag::err_param_default_argument_template_redecl)
523 << NewParam->getDefaultArgRange();
524 Diag(Old->getLocation(), diag::note_template_prev_declaration)
525 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000526 } else if (New->getTemplateSpecializationKind()
527 != TSK_ImplicitInstantiation &&
528 New->getTemplateSpecializationKind() != TSK_Undeclared) {
529 // C++ [temp.expr.spec]p21:
530 // Default function arguments shall not be specified in a declaration
531 // or a definition for one of the following explicit specializations:
532 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000533 // - the explicit specialization of a member function template;
534 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000535 // template where the class template specialization to which the
536 // member function specialization belongs is implicitly
537 // instantiated.
538 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
539 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
540 << New->getDeclName()
541 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000542 } else if (New->getDeclContext()->isDependentContext()) {
543 // C++ [dcl.fct.default]p6 (DR217):
544 // Default arguments for a member function of a class template shall
545 // be specified on the initial declaration of the member function
546 // within the class template.
547 //
548 // Reading the tea leaves a bit in DR217 and its reference to DR205
549 // leads me to the conclusion that one cannot add default function
550 // arguments for an out-of-line definition of a member function of a
551 // dependent type.
552 int WhichKind = 2;
553 if (CXXRecordDecl *Record
554 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
555 if (Record->getDescribedClassTemplate())
556 WhichKind = 0;
557 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
558 WhichKind = 1;
559 else
560 WhichKind = 2;
561 }
562
563 Diag(NewParam->getLocation(),
564 diag::err_param_default_argument_member_template_redecl)
565 << WhichKind
566 << NewParam->getDefaultArgRange();
567 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000568 }
569 }
570
Richard Smith58c3cc12012-11-28 03:45:24 +0000571 // DR1344: If a default argument is added outside a class definition and that
572 // default argument makes the function a special member function, the program
573 // is ill-formed. This can only happen for constructors.
574 if (isa<CXXConstructorDecl>(New) &&
575 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
576 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
577 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
578 if (NewSM != OldSM) {
579 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
580 assert(NewParam->hasDefaultArg());
581 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
582 << NewParam->getDefaultArgRange() << NewSM;
583 Diag(Old->getLocation(), diag::note_previous_declaration);
584 }
585 }
586
David Majnemeree4f4022014-03-30 06:44:54 +0000587 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000588 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000589 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000590 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000591 if (New->isConstexpr() != Old->isConstexpr()) {
592 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
593 << New << New->isConstexpr();
594 Diag(Old->getLocation(), diag::note_previous_declaration);
595 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000596 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
597 // C++11 [dcl.fcn.spec]p4:
598 // If the definition of a function appears in a translation unit before its
599 // first declaration as inline, the program is ill-formed.
600 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
601 Diag(Def->getLocation(), diag::note_previous_definition);
602 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000603 }
604
David Majnemer502b0ed2013-06-25 23:09:30 +0000605 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000606 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000607 // the only declaration of the function or function template in the
608 // translation unit.
609 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
610 functionDeclHasDefaultArgument(Old)) {
611 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
612 Diag(Old->getLocation(), diag::note_previous_declaration);
613 Invalid = true;
614 }
615
Douglas Gregorf40863c2010-02-12 07:32:17 +0000616 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000617 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000618
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000619 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000620}
621
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000622/// \brief Merge the exception specifications of two variable declarations.
623///
624/// This is called when there's a redeclaration of a VarDecl. The function
625/// checks if the redeclaration might have an exception specification and
626/// validates compatibility and merges the specs if necessary.
627void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
628 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000629 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000630 return;
631
632 assert(Context.hasSameType(New->getType(), Old->getType()) &&
633 "Should only be called if types are otherwise the same.");
634
635 QualType NewType = New->getType();
636 QualType OldType = Old->getType();
637
638 // We're only interested in pointers and references to functions, as well
639 // as pointers to member functions.
640 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
641 NewType = R->getPointeeType();
642 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
643 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
644 NewType = P->getPointeeType();
645 OldType = OldType->getAs<PointerType>()->getPointeeType();
646 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
647 NewType = M->getPointeeType();
648 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
649 }
650
651 if (!NewType->isFunctionProtoType())
652 return;
653
654 // There's lots of special cases for functions. For function pointers, system
655 // libraries are hopefully not as broken so that we don't need these
656 // workarounds.
657 if (CheckEquivalentExceptionSpec(
658 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
659 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
660 New->setInvalidDecl();
661 }
662}
663
Chris Lattner199abbc2008-04-08 05:04:30 +0000664/// CheckCXXDefaultArguments - Verify that the default arguments for a
665/// function declaration are well-formed according to C++
666/// [dcl.fct.default].
667void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
668 unsigned NumParams = FD->getNumParams();
669 unsigned p;
670
671 // Find first parameter with a default argument
672 for (p = 0; p < NumParams; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000674 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000675 break;
676 }
677
678 // C++ [dcl.fct.default]p4:
679 // In a given function declaration, all parameters
680 // subsequent to a parameter with a default argument shall
681 // have default arguments supplied in this or previous
682 // declarations. A default argument shall not be redefined
683 // by a later declaration (not even to the same value).
684 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000685 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000686 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000687 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000688 if (Param->isInvalidDecl())
689 /* We already complained about this parameter. */;
690 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000691 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000692 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000693 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000694 else
Mike Stump11289f42009-09-09 15:08:12 +0000695 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000696 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner199abbc2008-04-08 05:04:30 +0000698 LastMissingDefaultArg = p;
699 }
700 }
701
702 if (LastMissingDefaultArg > 0) {
703 // Some default arguments were missing. Clear out all of the
704 // default arguments up to (and including) the last missing
705 // default argument, so that we leave the function parameters
706 // in a semantically valid state.
707 for (p = 0; p <= LastMissingDefaultArg; ++p) {
708 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000709 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000710 Param->setDefaultArg(0);
711 }
712 }
713 }
714}
Douglas Gregor556877c2008-04-13 21:30:24 +0000715
Richard Smitheb3c10c2011-10-01 02:31:28 +0000716// CheckConstexprParameterTypes - Check whether a function's parameter types
717// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000718// diagnostic and return false.
719static bool CheckConstexprParameterTypes(Sema &SemaRef,
720 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000721 unsigned ArgIndex = 0;
722 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000723 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
724 e = FT->param_type_end();
725 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000726 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
727 SourceLocation ParamLoc = PD->getLocation();
728 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000729 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000730 diag::err_constexpr_non_literal_param,
731 ArgIndex+1, PD->getSourceRange(),
732 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000733 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000734 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000735 return true;
736}
737
738/// \brief Get diagnostic %select index for tag kind for
739/// record diagnostic message.
740/// WARNING: Indexes apply to particular diagnostics only!
741///
742/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000743static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000744 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000745 case TTK_Struct: return 0;
746 case TTK_Interface: return 1;
747 case TTK_Class: return 2;
748 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000749 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000750}
751
752// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
753// the requirements of a constexpr function definition or a constexpr
754// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000755// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000756//
Richard Smith3607ffe2012-02-13 03:54:03 +0000757// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
758bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000759 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
760 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000761 // C++11 [dcl.constexpr]p4:
762 // The definition of a constexpr constructor shall satisfy the following
763 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000764 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000765 const CXXRecordDecl *RD = MD->getParent();
766 if (RD->getNumVBases()) {
767 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
768 << isa<CXXConstructorDecl>(NewFD)
769 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000770 for (const auto &I : RD->vbases())
771 Diag(I.getLocStart(),
772 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000773 return false;
774 }
Richard Smith7971b692012-01-13 04:54:00 +0000775 }
776
777 if (!isa<CXXConstructorDecl>(NewFD)) {
778 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000779 // The definition of a constexpr function shall satisfy the following
780 // constraints:
781 // - it shall not be virtual;
782 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
783 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000784 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000785
Richard Smith3607ffe2012-02-13 03:54:03 +0000786 // If it's not obvious why this function is virtual, find an overridden
787 // function which uses the 'virtual' keyword.
788 const CXXMethodDecl *WrittenVirtual = Method;
789 while (!WrittenVirtual->isVirtualAsWritten())
790 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
791 if (WrittenVirtual != Method)
792 Diag(WrittenVirtual->getLocation(),
793 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000794 return false;
795 }
796
797 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000798 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000799 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000800 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000801 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000802 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000803 }
804
Richard Smith7971b692012-01-13 04:54:00 +0000805 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000806 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000807 return false;
808
Richard Smitheb3c10c2011-10-01 02:31:28 +0000809 return true;
810}
811
812/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000813/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000814///
Richard Smithd9f663b2013-04-22 15:31:51 +0000815/// \return true if the body is OK (maybe only as an extension), false if we
816/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000817static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000818 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
819 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000820 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
821 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000822 for (const auto *DclIt : DS->decls()) {
823 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000824 case Decl::StaticAssert:
825 case Decl::Using:
826 case Decl::UsingShadow:
827 case Decl::UsingDirective:
828 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000829 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000830 // - static_assert-declarations
831 // - using-declarations,
832 // - using-directives,
833 continue;
834
835 case Decl::Typedef:
836 case Decl::TypeAlias: {
837 // - typedef declarations and alias-declarations that do not define
838 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000839 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000840 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
841 // Don't allow variably-modified types in constexpr functions.
842 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
843 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
844 << TL.getSourceRange() << TL.getType()
845 << isa<CXXConstructorDecl>(Dcl);
846 return false;
847 }
848 continue;
849 }
850
851 case Decl::Enum:
852 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000853 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000854 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000855 SemaRef.Diag(DS->getLocStart(),
856 SemaRef.getLangOpts().CPlusPlus1y
857 ? diag::warn_cxx11_compat_constexpr_type_definition
858 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000859 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000860 continue;
861
Richard Smithd9f663b2013-04-22 15:31:51 +0000862 case Decl::EnumConstant:
863 case Decl::IndirectField:
864 case Decl::ParmVar:
865 // These can only appear with other declarations which are banned in
866 // C++11 and permitted in C++1y, so ignore them.
867 continue;
868
869 case Decl::Var: {
870 // C++1y [dcl.constexpr]p3 allows anything except:
871 // a definition of a variable of non-literal type or of static or
872 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000873 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000874 if (VD->isThisDeclarationADefinition()) {
875 if (VD->isStaticLocal()) {
876 SemaRef.Diag(VD->getLocation(),
877 diag::err_constexpr_local_var_static)
878 << isa<CXXConstructorDecl>(Dcl)
879 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
880 return false;
881 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000882 if (!VD->getType()->isDependentType() &&
883 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000884 VD->getLocation(), VD->getType(),
885 diag::err_constexpr_local_var_non_literal_type,
886 isa<CXXConstructorDecl>(Dcl)))
887 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000888 if (!VD->getType()->isDependentType() &&
889 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000890 SemaRef.Diag(VD->getLocation(),
891 diag::err_constexpr_local_var_no_init)
892 << isa<CXXConstructorDecl>(Dcl);
893 return false;
894 }
895 }
896 SemaRef.Diag(VD->getLocation(),
897 SemaRef.getLangOpts().CPlusPlus1y
898 ? diag::warn_cxx11_compat_constexpr_local_var
899 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000900 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000901 continue;
902 }
903
904 case Decl::NamespaceAlias:
905 case Decl::Function:
906 // These are disallowed in C++11 and permitted in C++1y. Allow them
907 // everywhere as an extension.
908 if (!Cxx1yLoc.isValid())
909 Cxx1yLoc = DS->getLocStart();
910 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000911
912 default:
913 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
914 << isa<CXXConstructorDecl>(Dcl);
915 return false;
916 }
917 }
918
919 return true;
920}
921
922/// Check that the given field is initialized within a constexpr constructor.
923///
924/// \param Dcl The constexpr constructor being checked.
925/// \param Field The field being checked. This may be a member of an anonymous
926/// struct or union nested within the class being checked.
927/// \param Inits All declarations, including anonymous struct/union members and
928/// indirect members, for which any initialization was provided.
929/// \param Diagnosed Set to true if an error is produced.
930static void CheckConstexprCtorInitializer(Sema &SemaRef,
931 const FunctionDecl *Dcl,
932 FieldDecl *Field,
933 llvm::SmallSet<Decl*, 16> &Inits,
934 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000935 if (Field->isInvalidDecl())
936 return;
937
Douglas Gregor556e5862011-10-10 17:22:13 +0000938 if (Field->isUnnamedBitfield())
939 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000940
Richard Smithab44d5b2013-12-10 08:25:00 +0000941 // Anonymous unions with no variant members and empty anonymous structs do not
942 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
943 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000944 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000945 (Field->getType()->isUnionType()
946 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
947 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000948 return;
949
Richard Smitheb3c10c2011-10-01 02:31:28 +0000950 if (!Inits.count(Field)) {
951 if (!Diagnosed) {
952 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
953 Diagnosed = true;
954 }
955 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
956 } else if (Field->isAnonymousStructOrUnion()) {
957 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000958 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000959 // If an anonymous union contains an anonymous struct of which any member
960 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000961 if (!RD->isUnion() || Inits.count(I))
962 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000963 }
964}
965
Richard Smithd9f663b2013-04-22 15:31:51 +0000966/// Check the provided statement is allowed in a constexpr function
967/// definition.
968static bool
969CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000970 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000971 SourceLocation &Cxx1yLoc) {
972 // - its function-body shall be [...] a compound-statement that contains only
973 switch (S->getStmtClass()) {
974 case Stmt::NullStmtClass:
975 // - null statements,
976 return true;
977
978 case Stmt::DeclStmtClass:
979 // - static_assert-declarations
980 // - using-declarations,
981 // - using-directives,
982 // - typedef declarations and alias-declarations that do not define
983 // classes or enumerations,
984 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
985 return false;
986 return true;
987
988 case Stmt::ReturnStmtClass:
989 // - and exactly one return statement;
990 if (isa<CXXConstructorDecl>(Dcl)) {
991 // C++1y allows return statements in constexpr constructors.
992 if (!Cxx1yLoc.isValid())
993 Cxx1yLoc = S->getLocStart();
994 return true;
995 }
996
997 ReturnStmts.push_back(S->getLocStart());
998 return true;
999
1000 case Stmt::CompoundStmtClass: {
1001 // C++1y allows compound-statements.
1002 if (!Cxx1yLoc.isValid())
1003 Cxx1yLoc = S->getLocStart();
1004
1005 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001006 for (auto *BodyIt : CompStmt->body()) {
1007 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001008 Cxx1yLoc))
1009 return false;
1010 }
1011 return true;
1012 }
1013
1014 case Stmt::AttributedStmtClass:
1015 if (!Cxx1yLoc.isValid())
1016 Cxx1yLoc = S->getLocStart();
1017 return true;
1018
1019 case Stmt::IfStmtClass: {
1020 // C++1y allows if-statements.
1021 if (!Cxx1yLoc.isValid())
1022 Cxx1yLoc = S->getLocStart();
1023
1024 IfStmt *If = cast<IfStmt>(S);
1025 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1026 Cxx1yLoc))
1027 return false;
1028 if (If->getElse() &&
1029 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1030 Cxx1yLoc))
1031 return false;
1032 return true;
1033 }
1034
1035 case Stmt::WhileStmtClass:
1036 case Stmt::DoStmtClass:
1037 case Stmt::ForStmtClass:
1038 case Stmt::CXXForRangeStmtClass:
1039 case Stmt::ContinueStmtClass:
1040 // C++1y allows all of these. We don't allow them as extensions in C++11,
1041 // because they don't make sense without variable mutation.
1042 if (!SemaRef.getLangOpts().CPlusPlus1y)
1043 break;
1044 if (!Cxx1yLoc.isValid())
1045 Cxx1yLoc = S->getLocStart();
1046 for (Stmt::child_range Children = S->children(); Children; ++Children)
1047 if (*Children &&
1048 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1049 Cxx1yLoc))
1050 return false;
1051 return true;
1052
1053 case Stmt::SwitchStmtClass:
1054 case Stmt::CaseStmtClass:
1055 case Stmt::DefaultStmtClass:
1056 case Stmt::BreakStmtClass:
1057 // C++1y allows switch-statements, and since they don't need variable
1058 // mutation, we can reasonably allow them in C++11 as an extension.
1059 if (!Cxx1yLoc.isValid())
1060 Cxx1yLoc = S->getLocStart();
1061 for (Stmt::child_range Children = S->children(); Children; ++Children)
1062 if (*Children &&
1063 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1064 Cxx1yLoc))
1065 return false;
1066 return true;
1067
1068 default:
1069 if (!isa<Expr>(S))
1070 break;
1071
1072 // C++1y allows expression-statements.
1073 if (!Cxx1yLoc.isValid())
1074 Cxx1yLoc = S->getLocStart();
1075 return true;
1076 }
1077
1078 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1079 << isa<CXXConstructorDecl>(Dcl);
1080 return false;
1081}
1082
Richard Smitheb3c10c2011-10-01 02:31:28 +00001083/// Check the body for the given constexpr function declaration only contains
1084/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1085///
1086/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001087bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001088 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001089 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001090 // The definition of a constexpr function shall satisfy the following
1091 // constraints: [...]
1092 // - its function-body shall be = delete, = default, or a
1093 // compound-statement
1094 //
Richard Smith74388b42012-02-04 00:33:54 +00001095 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001096 // In the definition of a constexpr constructor, [...]
1097 // - its function-body shall not be a function-try-block;
1098 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1099 << isa<CXXConstructorDecl>(Dcl);
1100 return false;
1101 }
1102
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001103 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001104
1105 // - its function-body shall be [...] a compound-statement that contains only
1106 // [... list of cases ...]
1107 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1108 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001109 for (auto *BodyIt : CompBody->body()) {
1110 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001111 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001112 }
1113
Richard Smithd9f663b2013-04-22 15:31:51 +00001114 if (Cxx1yLoc.isValid())
1115 Diag(Cxx1yLoc,
1116 getLangOpts().CPlusPlus1y
1117 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1118 : diag::ext_constexpr_body_invalid_stmt)
1119 << isa<CXXConstructorDecl>(Dcl);
1120
Richard Smitheb3c10c2011-10-01 02:31:28 +00001121 if (const CXXConstructorDecl *Constructor
1122 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1123 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001124 // DR1359:
1125 // - every non-variant non-static data member and base class sub-object
1126 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001127 // DR1460:
1128 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001129 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001130 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001131 if (Constructor->getNumCtorInitializers() == 0 &&
1132 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001133 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1134 return false;
1135 }
Richard Smithf368fb42011-10-10 16:38:04 +00001136 } else if (!Constructor->isDependentContext() &&
1137 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001138 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1139
1140 // Skip detailed checking if we have enough initializers, and we would
1141 // allow at most one initializer per member.
1142 bool AnyAnonStructUnionMembers = false;
1143 unsigned Fields = 0;
1144 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1145 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001146 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001147 AnyAnonStructUnionMembers = true;
1148 break;
1149 }
1150 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001151 // DR1460:
1152 // - if the class is a union-like class, but is not a union, for each of
1153 // its anonymous union members having variant members, exactly one of
1154 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001155 if (AnyAnonStructUnionMembers ||
1156 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1157 // Check initialization of non-static data members. Base classes are
1158 // always initialized so do not need to be checked. Dependent bases
1159 // might not have initializers in the member initializer list.
1160 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001161 for (const auto *I: Constructor->inits()) {
1162 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001163 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001164 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001165 Inits.insert(ID->chain_begin(), ID->chain_end());
1166 }
1167
1168 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001169 for (auto *I : RD->fields())
1170 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001171 if (Diagnosed)
1172 return false;
1173 }
1174 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001175 } else {
1176 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001177 // C++1y doesn't require constexpr functions to contain a 'return'
1178 // statement. We still do, unless the return type is void, because
1179 // otherwise if there's no return statement, the function cannot
1180 // be used in a core constant expression.
Alp Toker314cc812014-01-25 16:55:45 +00001181 bool OK = getLangOpts().CPlusPlus1y && Dcl->getReturnType()->isVoidType();
Richard Smithd9f663b2013-04-22 15:31:51 +00001182 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001183 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1184 : diag::err_constexpr_body_no_return);
1185 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001186 }
1187 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001188 Diag(ReturnStmts.back(),
1189 getLangOpts().CPlusPlus1y
1190 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1191 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001192 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1193 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001194 }
1195 }
1196
Richard Smith74388b42012-02-04 00:33:54 +00001197 // C++11 [dcl.constexpr]p5:
1198 // if no function argument values exist such that the function invocation
1199 // substitution would produce a constant expression, the program is
1200 // ill-formed; no diagnostic required.
1201 // C++11 [dcl.constexpr]p3:
1202 // - every constructor call and implicit conversion used in initializing the
1203 // return value shall be one of those allowed in a constant expression.
1204 // C++11 [dcl.constexpr]p4:
1205 // - every constructor involved in initializing non-static data members and
1206 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001207 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001208 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001209 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001210 << isa<CXXConstructorDecl>(Dcl);
1211 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1212 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001213 // Don't return false here: we allow this for compatibility in
1214 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001215 }
1216
Richard Smitheb3c10c2011-10-01 02:31:28 +00001217 return true;
1218}
1219
Douglas Gregor61956c42008-10-31 09:07:45 +00001220/// isCurrentClassName - Determine whether the identifier II is the
1221/// name of the class type currently being defined. In the case of
1222/// nested classes, this will only return true if II is the name of
1223/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001224bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1225 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001226 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001227
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001228 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001229 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001230 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001231 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1232 } else
1233 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1234
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001235 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001236 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001237 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001238}
1239
Richard Smithfb8b7b92013-10-15 00:00:26 +00001240/// \brief Determine whether the identifier II is a typo for the name of
1241/// the class type currently being defined. If so, update it to the identifier
1242/// that should have been used.
1243bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1244 assert(getLangOpts().CPlusPlus && "No class names in C!");
1245
1246 if (!getLangOpts().SpellChecking)
1247 return false;
1248
1249 CXXRecordDecl *CurDecl;
1250 if (SS && SS->isSet() && !SS->isInvalid()) {
1251 DeclContext *DC = computeDeclContext(*SS, true);
1252 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1253 } else
1254 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1255
1256 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1257 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1258 < II->getLength()) {
1259 II = CurDecl->getIdentifier();
1260 return true;
1261 }
1262
1263 return false;
1264}
1265
Douglas Gregordc974572012-11-10 07:24:09 +00001266/// \brief Determine whether the given class is a base class of the given
1267/// class, including looking at dependent bases.
1268static bool findCircularInheritance(const CXXRecordDecl *Class,
1269 const CXXRecordDecl *Current) {
1270 SmallVector<const CXXRecordDecl*, 8> Queue;
1271
1272 Class = Class->getCanonicalDecl();
1273 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001274 for (const auto &I : Current->bases()) {
1275 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001276 if (!Base)
1277 continue;
1278
1279 Base = Base->getDefinition();
1280 if (!Base)
1281 continue;
1282
1283 if (Base->getCanonicalDecl() == Class)
1284 return true;
1285
1286 Queue.push_back(Base);
1287 }
1288
1289 if (Queue.empty())
1290 return false;
1291
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001292 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001293 }
1294
1295 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001296}
1297
Mike Stump11289f42009-09-09 15:08:12 +00001298/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001299///
1300/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1301/// and returns NULL otherwise.
1302CXXBaseSpecifier *
1303Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1304 SourceRange SpecifierRange,
1305 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001306 TypeSourceInfo *TInfo,
1307 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001308 QualType BaseType = TInfo->getType();
1309
Douglas Gregor463421d2009-03-03 04:44:36 +00001310 // C++ [class.union]p1:
1311 // A union shall not have base classes.
1312 if (Class->isUnion()) {
1313 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1314 << SpecifierRange;
1315 return 0;
1316 }
1317
Douglas Gregor752a5952011-01-03 22:36:02 +00001318 if (EllipsisLoc.isValid() &&
1319 !TInfo->getType()->containsUnexpandedParameterPack()) {
1320 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1321 << TInfo->getTypeLoc().getSourceRange();
1322 EllipsisLoc = SourceLocation();
1323 }
Douglas Gregor62004702012-11-10 01:18:17 +00001324
1325 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1326
1327 if (BaseType->isDependentType()) {
1328 // Make sure that we don't have circular inheritance among our dependent
1329 // bases. For non-dependent bases, the check for completeness below handles
1330 // this.
1331 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1332 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1333 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001334 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001335 Diag(BaseLoc, diag::err_circular_inheritance)
1336 << BaseType << Context.getTypeDeclType(Class);
1337
1338 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1339 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1340 << BaseType;
1341
1342 return 0;
1343 }
1344 }
1345
Mike Stump11289f42009-09-09 15:08:12 +00001346 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001347 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001348 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001349 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001350
1351 // Base specifiers must be record types.
1352 if (!BaseType->isRecordType()) {
1353 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1354 return 0;
1355 }
1356
1357 // C++ [class.union]p1:
1358 // A union shall not be used as a base class.
1359 if (BaseType->isUnionType()) {
1360 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1361 return 0;
1362 }
1363
1364 // C++ [class.derived]p2:
1365 // The class-name in a base-specifier shall not be an incompletely
1366 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001367 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001368 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001369 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001370 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001371 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001372
Eli Friedmanc96d4962009-08-15 21:55:26 +00001373 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001374 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001375 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001376 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001377 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001378 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001379 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001380
David Majnemer9b1754d2013-11-02 12:00:36 +00001381 // A class which contains a flexible array member is not suitable for use as a
1382 // base class:
1383 // - If the layout determines that a base comes before another base,
1384 // the flexible array member would index into the subsequent base.
1385 // - If the layout determines that base comes before the derived class,
1386 // the flexible array member would index into the derived class.
1387 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1388 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1389 << CXXBaseDecl->getDeclName();
1390 return 0;
1391 }
1392
Anders Carlsson65c76d32011-03-25 14:55:14 +00001393 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001394 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001395 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001396 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001397 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001398 << CXXBaseDecl->getDeclName()
1399 << FA->isSpelledAsSealed();
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001400 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1401 << CXXBaseDecl->getDeclName();
1402 return 0;
1403 }
1404
John McCall3696dcb2010-08-17 07:23:57 +00001405 if (BaseDecl->isInvalidDecl())
1406 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001407
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001408 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001409 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001410 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001411 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001412}
1413
Douglas Gregor556877c2008-04-13 21:30:24 +00001414/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1415/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001416/// example:
1417/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001418/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001419BaseResult
John McCall48871652010-08-21 09:40:31 +00001420Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001421 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001422 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001423 ParsedType basetype, SourceLocation BaseLoc,
1424 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001425 if (!classdecl)
1426 return true;
1427
Douglas Gregorc40290e2009-03-09 23:48:35 +00001428 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001429 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001430 if (!Class)
1431 return true;
1432
Richard Smith4c96e992013-02-19 23:47:15 +00001433 // We do not support any C++11 attributes on base-specifiers yet.
1434 // Diagnose any attributes we see.
1435 if (!Attributes.empty()) {
1436 for (AttributeList *Attr = Attributes.getList(); Attr;
1437 Attr = Attr->getNext()) {
1438 if (Attr->isInvalid() ||
1439 Attr->getKind() == AttributeList::IgnoredAttribute)
1440 continue;
1441 Diag(Attr->getLoc(),
1442 Attr->getKind() == AttributeList::UnknownAttribute
1443 ? diag::warn_unknown_attribute_ignored
1444 : diag::err_base_specifier_attribute)
1445 << Attr->getName();
1446 }
1447 }
1448
Nick Lewycky19b9f952010-07-26 16:56:01 +00001449 TypeSourceInfo *TInfo = 0;
1450 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001451
Douglas Gregor752a5952011-01-03 22:36:02 +00001452 if (EllipsisLoc.isInvalid() &&
1453 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001454 UPPC_BaseType))
1455 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001456
Douglas Gregor463421d2009-03-03 04:44:36 +00001457 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001458 Virtual, Access, TInfo,
1459 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001460 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001461 else
1462 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001463
Douglas Gregor463421d2009-03-03 04:44:36 +00001464 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001465}
Douglas Gregor556877c2008-04-13 21:30:24 +00001466
Douglas Gregor463421d2009-03-03 04:44:36 +00001467/// \brief Performs the actual work of attaching the given base class
1468/// specifiers to a C++ class.
1469bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1470 unsigned NumBases) {
1471 if (NumBases == 0)
1472 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001473
1474 // Used to keep track of which base types we have already seen, so
1475 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001476 // that the key is always the unqualified canonical type of the base
1477 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001478 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1479
1480 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001481 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001482 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001483 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001484 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001485 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001486 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001487
1488 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1489 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001490 // C++ [class.mi]p3:
1491 // A class shall not be specified as a direct base class of a
1492 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001493 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001494 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001495 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001496 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001497
1498 // Delete the duplicate base class specifier; we're going to
1499 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001500 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001501
1502 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001503 } else {
1504 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001505 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001506 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001507 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1508 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1509 if (Class->isInterface() &&
1510 (!RD->isInterface() ||
1511 KnownBase->getAccessSpecifier() != AS_public)) {
1512 // The Microsoft extension __interface does not permit bases that
1513 // are not themselves public interfaces.
1514 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1515 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1516 << RD->getSourceRange();
1517 Invalid = true;
1518 }
1519 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001520 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001521 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001522 }
1523 }
1524
1525 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001526 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001527
1528 // Delete the remaining (good) base class specifiers, since their
1529 // data has been copied into the CXXRecordDecl.
1530 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001531 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001532
1533 return Invalid;
1534}
1535
1536/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1537/// class, after checking whether there are any duplicate base
1538/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001539void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001540 unsigned NumBases) {
1541 if (!ClassDecl || !Bases || !NumBases)
1542 return;
1543
1544 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001545 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001546}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001547
Douglas Gregor36d1b142009-10-06 17:59:45 +00001548/// \brief Determine whether the type \p Derived is a C++ class that is
1549/// derived from the type \p Base.
1550bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001551 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001552 return false;
John McCalle78aac42010-03-10 03:28:59 +00001553
Douglas Gregor45bb4832013-03-26 23:36:30 +00001554 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001555 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001556 return false;
1557
Douglas Gregor45bb4832013-03-26 23:36:30 +00001558 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001559 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001560 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001561
1562 // If either the base or the derived type is invalid, don't try to
1563 // check whether one is derived from the other.
1564 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1565 return false;
1566
John McCall67da35c2010-02-04 22:26:26 +00001567 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1568 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001569}
1570
1571/// \brief Determine whether the type \p Derived is a C++ class that is
1572/// derived from the type \p Base.
1573bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001574 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001575 return false;
1576
Douglas Gregor45bb4832013-03-26 23:36:30 +00001577 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001578 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001579 return false;
1580
Douglas Gregor45bb4832013-03-26 23:36:30 +00001581 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001582 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001583 return false;
1584
Douglas Gregor36d1b142009-10-06 17:59:45 +00001585 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1586}
1587
Anders Carlssona70cff62010-04-24 19:06:50 +00001588void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001589 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001590 assert(BasePathArray.empty() && "Base path array must be empty!");
1591 assert(Paths.isRecordingPaths() && "Must record paths!");
1592
1593 const CXXBasePath &Path = Paths.front();
1594
1595 // We first go backward and check if we have a virtual base.
1596 // FIXME: It would be better if CXXBasePath had the base specifier for
1597 // the nearest virtual base.
1598 unsigned Start = 0;
1599 for (unsigned I = Path.size(); I != 0; --I) {
1600 if (Path[I - 1].Base->isVirtual()) {
1601 Start = I - 1;
1602 break;
1603 }
1604 }
1605
1606 // Now add all bases.
1607 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001608 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001609}
1610
Douglas Gregor88d292c2010-05-13 16:44:06 +00001611/// \brief Determine whether the given base path includes a virtual
1612/// base class.
John McCallcf142162010-08-07 06:22:56 +00001613bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1614 for (CXXCastPath::const_iterator B = BasePath.begin(),
1615 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001616 B != BEnd; ++B)
1617 if ((*B)->isVirtual())
1618 return true;
1619
1620 return false;
1621}
1622
Douglas Gregor36d1b142009-10-06 17:59:45 +00001623/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1624/// conversion (where Derived and Base are class types) is
1625/// well-formed, meaning that the conversion is unambiguous (and
1626/// that all of the base classes are accessible). Returns true
1627/// and emits a diagnostic if the code is ill-formed, returns false
1628/// otherwise. Loc is the location where this routine should point to
1629/// if there is an error, and Range is the source range to highlight
1630/// if there is an error.
1631bool
1632Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001633 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001634 unsigned AmbigiousBaseConvID,
1635 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001636 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001637 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001638 // First, determine whether the path from Derived to Base is
1639 // ambiguous. This is slightly more expensive than checking whether
1640 // the Derived to Base conversion exists, because here we need to
1641 // explore multiple paths to determine if there is an ambiguity.
1642 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1643 /*DetectVirtual=*/false);
1644 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1645 assert(DerivationOkay &&
1646 "Can only be used with a derived-to-base conversion");
1647 (void)DerivationOkay;
1648
1649 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001650 if (InaccessibleBaseID) {
1651 // Check that the base class can be accessed.
1652 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1653 InaccessibleBaseID)) {
1654 case AR_inaccessible:
1655 return true;
1656 case AR_accessible:
1657 case AR_dependent:
1658 case AR_delayed:
1659 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001660 }
John McCall5b0829a2010-02-10 09:31:12 +00001661 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001662
1663 // Build a base path if necessary.
1664 if (BasePath)
1665 BuildBasePathArray(Paths, *BasePath);
1666 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001667 }
1668
David Majnemer626032f2013-06-22 06:43:58 +00001669 if (AmbigiousBaseConvID) {
1670 // We know that the derived-to-base conversion is ambiguous, and
1671 // we're going to produce a diagnostic. Perform the derived-to-base
1672 // search just one more time to compute all of the possible paths so
1673 // that we can print them out. This is more expensive than any of
1674 // the previous derived-to-base checks we've done, but at this point
1675 // performance isn't as much of an issue.
1676 Paths.clear();
1677 Paths.setRecordingPaths(true);
1678 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1679 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1680 (void)StillOkay;
1681
1682 // Build up a textual representation of the ambiguous paths, e.g.,
1683 // D -> B -> A, that will be used to illustrate the ambiguous
1684 // conversions in the diagnostic. We only print one of the paths
1685 // to each base class subobject.
1686 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1687
1688 Diag(Loc, AmbigiousBaseConvID)
1689 << Derived << Base << PathDisplayStr << Range << Name;
1690 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001691 return true;
1692}
1693
1694bool
1695Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001696 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001697 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001698 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001699 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001700 IgnoreAccess ? 0
1701 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001702 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001703 Loc, Range, DeclarationName(),
1704 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001705}
1706
1707
1708/// @brief Builds a string representing ambiguous paths from a
1709/// specific derived class to different subobjects of the same base
1710/// class.
1711///
1712/// This function builds a string that can be used in error messages
1713/// to show the different paths that one can take through the
1714/// inheritance hierarchy to go from the derived class to different
1715/// subobjects of a base class. The result looks something like this:
1716/// @code
1717/// struct D -> struct B -> struct A
1718/// struct D -> struct C -> struct A
1719/// @endcode
1720std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1721 std::string PathDisplayStr;
1722 std::set<unsigned> DisplayedPaths;
1723 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1724 Path != Paths.end(); ++Path) {
1725 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1726 // We haven't displayed a path to this particular base
1727 // class subobject yet.
1728 PathDisplayStr += "\n ";
1729 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1730 for (CXXBasePath::const_iterator Element = Path->begin();
1731 Element != Path->end(); ++Element)
1732 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1733 }
1734 }
1735
1736 return PathDisplayStr;
1737}
1738
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001739//===----------------------------------------------------------------------===//
1740// C++ class member Handling
1741//===----------------------------------------------------------------------===//
1742
Abramo Bagnarad7340582010-06-05 05:09:32 +00001743/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001744bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1745 SourceLocation ASLoc,
1746 SourceLocation ColonLoc,
1747 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001748 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001749 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001750 ASLoc, ColonLoc);
1751 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001752 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001753}
1754
Richard Smith18f07db2012-08-06 03:25:17 +00001755/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001756void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001757 if (D->isInvalidDecl())
1758 return;
1759
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001760 // We only care about "override" and "final" declarations.
1761 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1762 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001763
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001764 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001765
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001766 // We can't check dependent instance methods.
1767 if (MD && MD->isInstance() &&
1768 (MD->getParent()->hasAnyDependentBases() ||
1769 MD->getType()->isDependentType()))
1770 return;
1771
1772 if (MD && !MD->isVirtual()) {
1773 // If we have a non-virtual method, check if if hides a virtual method.
1774 // (In that case, it's most likely the method has the wrong type.)
1775 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1776 FindHiddenVirtualMethods(MD, OverloadedMethods);
1777
1778 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001779 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1780 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001781 diag::override_keyword_hides_virtual_member_function)
1782 << "override" << (OverloadedMethods.size() > 1);
1783 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001784 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001785 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001786 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1787 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001788 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001789 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1790 MD->setInvalidDecl();
1791 return;
1792 }
1793 // Fall through into the general case diagnostic.
1794 // FIXME: We might want to attempt typo correction here.
1795 }
1796
1797 if (!MD || !MD->isVirtual()) {
1798 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1799 Diag(OA->getLocation(),
1800 diag::override_keyword_only_allowed_on_virtual_member_functions)
1801 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1802 D->dropAttr<OverrideAttr>();
1803 }
1804 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1805 Diag(FA->getLocation(),
1806 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001807 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1808 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001809 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001810 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001811 return;
1812 }
Richard Smith18f07db2012-08-06 03:25:17 +00001813
Richard Smith18f07db2012-08-06 03:25:17 +00001814 // C++11 [class.virtual]p5:
1815 // If a virtual function is marked with the virt-specifier override and
1816 // does not override a member function of a base class, the program is
1817 // ill-formed.
1818 bool HasOverriddenMethods =
1819 MD->begin_overridden_methods() != MD->end_overridden_methods();
1820 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1821 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1822 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001823}
1824
Richard Smith18f07db2012-08-06 03:25:17 +00001825/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001826/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001827/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001828bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1829 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001830 FinalAttr *FA = Old->getAttr<FinalAttr>();
1831 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001832 return false;
1833
1834 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001835 << New->getDeclName()
1836 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001837 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1838 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001839}
1840
Daniel Jasper0baec5492012-06-06 08:32:04 +00001841static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001842 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1843 // FIXME: Destruction of ObjC lifetime types has side-effects.
1844 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1845 return !RD->isCompleteDefinition() ||
1846 !RD->hasTrivialDefaultConstructor() ||
1847 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001848 return false;
1849}
1850
John McCall5e77d762013-04-16 07:28:30 +00001851static AttributeList *getMSPropertyAttr(AttributeList *list) {
1852 for (AttributeList* it = list; it != 0; it = it->getNext())
1853 if (it->isDeclspecPropertyAttribute())
1854 return it;
1855 return 0;
1856}
1857
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001858/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1859/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001860/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001861/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1862/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001863NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001864Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001865 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001866 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001867 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001868 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001869 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1870 DeclarationName Name = NameInfo.getName();
1871 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001872
1873 // For anonymous bitfields, the location should point to the type.
1874 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001875 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001876
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001877 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001878
John McCallb1cd7da2010-06-04 08:34:12 +00001879 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001880 assert(!DS.isFriendSpecified());
1881
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001882 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001883
John McCalldb632ac2012-09-25 07:32:39 +00001884 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1885 // The Microsoft extension __interface only permits public member functions
1886 // and prohibits constructors, destructors, operators, non-public member
1887 // functions, static methods and data members.
1888 unsigned InvalidDecl;
1889 bool ShowDeclName = true;
1890 if (!isFunc)
1891 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1892 else if (AS != AS_public)
1893 InvalidDecl = 2;
1894 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1895 InvalidDecl = 3;
1896 else switch (Name.getNameKind()) {
1897 case DeclarationName::CXXConstructorName:
1898 InvalidDecl = 4;
1899 ShowDeclName = false;
1900 break;
1901
1902 case DeclarationName::CXXDestructorName:
1903 InvalidDecl = 5;
1904 ShowDeclName = false;
1905 break;
1906
1907 case DeclarationName::CXXOperatorName:
1908 case DeclarationName::CXXConversionFunctionName:
1909 InvalidDecl = 6;
1910 break;
1911
1912 default:
1913 InvalidDecl = 0;
1914 break;
1915 }
1916
1917 if (InvalidDecl) {
1918 if (ShowDeclName)
1919 Diag(Loc, diag::err_invalid_member_in_interface)
1920 << (InvalidDecl-1) << Name;
1921 else
1922 Diag(Loc, diag::err_invalid_member_in_interface)
1923 << (InvalidDecl-1) << "";
1924 return 0;
1925 }
1926 }
1927
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001928 // C++ 9.2p6: A member shall not be declared to have automatic storage
1929 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001930 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1931 // data members and cannot be applied to names declared const or static,
1932 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001933 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001934 case DeclSpec::SCS_unspecified:
1935 case DeclSpec::SCS_typedef:
1936 case DeclSpec::SCS_static:
1937 break;
1938 case DeclSpec::SCS_mutable:
1939 if (isFunc) {
1940 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001941
Richard Smithb4a9e862013-04-12 22:46:28 +00001942 // FIXME: It would be nicer if the keyword was ignored only for this
1943 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001944 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001945 }
1946 break;
1947 default:
1948 Diag(DS.getStorageClassSpecLoc(),
1949 diag::err_storageclass_invalid_for_member);
1950 D.getMutableDeclSpec().ClearStorageClassSpecs();
1951 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001952 }
1953
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001954 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1955 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001956 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001957
David Blaikie35506f82013-01-30 01:22:18 +00001958 if (DS.isConstexprSpecified() && isInstField) {
1959 SemaDiagnosticBuilder B =
1960 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1961 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1962 if (InitStyle == ICIS_NoInit) {
1963 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1964 D.getMutableDeclSpec().ClearConstexprSpec();
1965 const char *PrevSpec;
1966 unsigned DiagID;
1967 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1968 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001969 (void)Failed;
David Blaikie35506f82013-01-30 01:22:18 +00001970 assert(!Failed && "Making a constexpr member const shouldn't fail");
1971 } else {
1972 B << 1;
1973 const char *PrevSpec;
1974 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001975 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001976 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1977 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001978 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001979 "This is the only DeclSpec that should fail to be applied");
1980 B << 1;
1981 } else {
1982 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1983 isInstField = false;
1984 }
1985 }
1986 }
1987
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001988 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001989 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001990 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001991
1992 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00001993 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001994 Diag(Loc, diag::err_bad_variable_name)
1995 << Name;
1996 return 0;
1997 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001998
Benjamin Kramer365082d2012-05-19 16:34:46 +00001999 IdentifierInfo *II = Name.getAsIdentifierInfo();
2000
Douglas Gregor7c26c042011-09-21 14:40:46 +00002001 // Member field could not be with "template" keyword.
2002 // So TemplateParameterLists should be empty in this case.
2003 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002004 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002005 if (TemplateParams->size()) {
2006 // There is no such thing as a member field template.
2007 Diag(D.getIdentifierLoc(), diag::err_template_member)
2008 << II
2009 << SourceRange(TemplateParams->getTemplateLoc(),
2010 TemplateParams->getRAngleLoc());
2011 } else {
2012 // There is an extraneous 'template<>' for this member.
2013 Diag(TemplateParams->getTemplateLoc(),
2014 diag::err_template_member_noparams)
2015 << II
2016 << SourceRange(TemplateParams->getTemplateLoc(),
2017 TemplateParams->getRAngleLoc());
2018 }
2019 return 0;
2020 }
2021
Douglas Gregora007d362010-10-13 22:19:53 +00002022 if (SS.isSet() && !SS.isInvalid()) {
2023 // The user provided a superfluous scope specifier inside a class
2024 // definition:
2025 //
2026 // class X {
2027 // int X::member;
2028 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002029 if (DeclContext *DC = computeDeclContext(SS, false))
2030 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002031 else
2032 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2033 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002034
Douglas Gregora007d362010-10-13 22:19:53 +00002035 SS.clear();
2036 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002037
John McCall5e77d762013-04-16 07:28:30 +00002038 AttributeList *MSPropertyAttr =
2039 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002040 if (MSPropertyAttr) {
2041 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2042 BitWidth, InitStyle, AS, MSPropertyAttr);
2043 if (!Member)
2044 return 0;
2045 isInstField = false;
2046 } else {
2047 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2048 BitWidth, InitStyle, AS);
2049 assert(Member && "HandleField never returns null");
2050 }
2051 } else {
2052 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2053
2054 Member = HandleDeclarator(S, D, TemplateParameterLists);
2055 if (!Member)
2056 return 0;
2057
2058 // Non-instance-fields can't have a bitfield.
2059 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002060 if (Member->isInvalidDecl()) {
2061 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002062 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002063 // C++ 9.6p3: A bit-field shall not be a static member.
2064 // "static member 'A' cannot be a bit-field"
2065 Diag(Loc, diag::err_static_not_bitfield)
2066 << Name << BitWidth->getSourceRange();
2067 } else if (isa<TypedefDecl>(Member)) {
2068 // "typedef member 'x' cannot be a bit-field"
2069 Diag(Loc, diag::err_typedef_not_bitfield)
2070 << Name << BitWidth->getSourceRange();
2071 } else {
2072 // A function typedef ("typedef int f(); f a;").
2073 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2074 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002075 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002076 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002077 }
Mike Stump11289f42009-09-09 15:08:12 +00002078
Chris Lattnerd26760a2009-03-05 23:01:03 +00002079 BitWidth = 0;
2080 Member->setInvalidDecl();
2081 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002082
2083 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002084
Larisse Voufo39a1e502013-08-06 01:03:05 +00002085 // If we have declared a member function template or static data member
2086 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002087 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2088 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002089 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2090 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002091 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002092
Richard Smith18f07db2012-08-06 03:25:17 +00002093 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002094 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002095 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002096 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2097 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002098
Douglas Gregorf2f08062011-03-08 17:10:18 +00002099 if (VS.getLastLocation().isValid()) {
2100 // Update the end location of a method that has a virt-specifiers.
2101 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2102 MD->setRangeEnd(VS.getLastLocation());
2103 }
Richard Smith18f07db2012-08-06 03:25:17 +00002104
Anders Carlssonc87f8612011-01-20 06:29:02 +00002105 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002106
Douglas Gregor92751d42008-11-17 22:58:34 +00002107 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002108
Daniel Jasper0baec5492012-06-06 08:32:04 +00002109 if (isInstField) {
2110 FieldDecl *FD = cast<FieldDecl>(Member);
2111 FieldCollector->Add(FD);
2112
2113 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2114 FD->getLocation())
2115 != DiagnosticsEngine::Ignored) {
2116 // Remember all explicit private FieldDecls that have a name, no side
2117 // effects and are not part of a dependent type declaration.
2118 if (!FD->isImplicit() && FD->getDeclName() &&
2119 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002120 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002121 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002122 !InitializationHasSideEffects(*FD))
2123 UnusedPrivateFields.insert(FD);
2124 }
2125 }
2126
John McCall48871652010-08-21 09:40:31 +00002127 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002128}
2129
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002130namespace {
2131 class UninitializedFieldVisitor
2132 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2133 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002134 // List of Decls to generate a warning on. Also remove Decls that become
2135 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002136 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002137 // If non-null, add a note to the warning pointing back to the constructor.
2138 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002139 public:
2140 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002141 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002142 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002143 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002144 : Inherited(S.Context), S(S), Decls(Decls),
2145 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002146
Richard Trieufd687772013-09-16 20:46:50 +00002147 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002148 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2149 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002150
Richard Trieu1bc22c12013-09-13 03:20:53 +00002151 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2152 // or union.
2153 MemberExpr *FieldME = ME;
2154
2155 Expr *Base = ME;
2156 while (isa<MemberExpr>(Base)) {
2157 ME = cast<MemberExpr>(Base);
2158
2159 if (isa<VarDecl>(ME->getMemberDecl()))
2160 return;
2161
2162 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2163 if (!FD->isAnonymousStructOrUnion())
2164 FieldME = ME;
2165
2166 Base = ME->getBase();
2167 }
2168
Richard Trieufd687772013-09-16 20:46:50 +00002169 if (!isa<CXXThisExpr>(Base))
2170 return;
2171
Richard Trieu406e65c2013-09-20 03:03:06 +00002172 ValueDecl* FoundVD = FieldME->getMemberDecl();
2173
Richard Trieuef64e942013-10-25 00:56:00 +00002174 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002175 return;
2176
Richard Trieuef64e942013-10-25 00:56:00 +00002177 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002178
Richard Trieuef64e942013-10-25 00:56:00 +00002179 // Prevent double warnings on use of unbounded references.
2180 if (IsReference != CheckReferenceOnly)
2181 return;
2182
2183 unsigned diag = IsReference
2184 ? diag::warn_reference_field_is_uninit
2185 : diag::warn_field_is_uninit;
2186 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2187 if (Constructor)
2188 S.Diag(Constructor->getLocation(),
2189 diag::note_uninit_in_this_constructor)
2190 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2191
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002192 }
2193
2194 void HandleValue(Expr *E) {
2195 E = E->IgnoreParens();
2196
2197 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002198 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002199 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002200 }
2201
2202 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2203 HandleValue(CO->getTrueExpr());
2204 HandleValue(CO->getFalseExpr());
2205 return;
2206 }
2207
2208 if (BinaryConditionalOperator *BCO =
2209 dyn_cast<BinaryConditionalOperator>(E)) {
2210 HandleValue(BCO->getCommon());
2211 HandleValue(BCO->getFalseExpr());
2212 return;
2213 }
2214
2215 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2216 switch (BO->getOpcode()) {
2217 default:
2218 return;
2219 case(BO_PtrMemD):
2220 case(BO_PtrMemI):
2221 HandleValue(BO->getLHS());
2222 return;
2223 case(BO_Comma):
2224 HandleValue(BO->getRHS());
2225 return;
2226 }
2227 }
2228 }
2229
Richard Trieu1bc22c12013-09-13 03:20:53 +00002230 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002231 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002232 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002233
2234 Inherited::VisitMemberExpr(ME);
2235 }
2236
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002237 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2238 if (E->getCastKind() == CK_LValueToRValue)
2239 HandleValue(E->getSubExpr());
2240
2241 Inherited::VisitImplicitCastExpr(E);
2242 }
2243
Richard Trieu1bc22c12013-09-13 03:20:53 +00002244 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002245 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002246 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2247 if (ICE->getCastKind() == CK_NoOp)
2248 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002249 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002250
2251 Inherited::VisitCXXConstructExpr(E);
2252 }
2253
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002254 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2255 Expr *Callee = E->getCallee();
2256 if (isa<MemberExpr>(Callee))
2257 HandleValue(Callee);
2258
2259 Inherited::VisitCXXMemberCallExpr(E);
2260 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002261
2262 void VisitBinaryOperator(BinaryOperator *E) {
2263 // If a field assignment is detected, remove the field from the
2264 // uninitiailized field set.
2265 if (E->getOpcode() == BO_Assign)
2266 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2267 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002268 if (!FD->getType()->isReferenceType())
2269 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002270
2271 Inherited::VisitBinaryOperator(E);
2272 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002273 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002274 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002275 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2276 const CXXConstructorDecl *Constructor) {
2277 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002278 return;
2279
Richard Trieuef64e942013-10-25 00:56:00 +00002280 if (!E)
2281 return;
2282
2283 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2284 E = Default->getExpr();
2285 if (!E)
2286 return;
2287 // In class initializers will point to the constructor.
2288 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2289 } else {
2290 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2291 }
2292 }
2293
2294 // Diagnose value-uses of fields to initialize themselves, e.g.
2295 // foo(foo)
2296 // where foo is not also a parameter to the constructor.
2297 // Also diagnose across field uninitialized use such as
2298 // x(y), y(x)
2299 // TODO: implement -Wuninitialized and fold this into that framework.
2300 static void DiagnoseUninitializedFields(
2301 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2302
2303 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2304 Constructor->getLocation())
2305 == DiagnosticsEngine::Ignored) {
2306 return;
2307 }
2308
2309 if (Constructor->isInvalidDecl())
2310 return;
2311
2312 const CXXRecordDecl *RD = Constructor->getParent();
2313
2314 // Holds fields that are uninitialized.
2315 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2316
2317 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002318 for (auto *I : RD->decls()) {
2319 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002320 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002321 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002322 UninitializedFields.insert(IFD->getAnonField());
2323 }
2324 }
2325
Aaron Ballman0ad78302014-03-13 17:34:31 +00002326 for (const auto *FieldInit : Constructor->inits()) {
2327 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002328
2329 CheckInitExprContainsUninitializedFields(
2330 SemaRef, InitExpr, UninitializedFields, Constructor);
2331
Aaron Ballman0ad78302014-03-13 17:34:31 +00002332 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002333 UninitializedFields.erase(Field);
2334 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002335 }
2336} // namespace
2337
Richard Smith74108172014-01-17 03:11:34 +00002338/// \brief Enter a new C++ default initializer scope. After calling this, the
2339/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2340/// parsing or instantiating the initializer failed.
2341void Sema::ActOnStartCXXInClassMemberInitializer() {
2342 // Create a synthetic function scope to represent the call to the constructor
2343 // that notionally surrounds a use of this initializer.
2344 PushFunctionScope();
2345}
2346
2347/// \brief This is invoked after parsing an in-class initializer for a
2348/// non-static C++ class member, and after instantiating an in-class initializer
2349/// in a class template. Such actions are deferred until the class is complete.
2350void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2351 SourceLocation InitLoc,
2352 Expr *InitExpr) {
2353 // Pop the notional constructor scope we created earlier.
2354 PopFunctionScopeInfo(0, D);
2355
Richard Smith938f40b2011-06-11 17:19:42 +00002356 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002357 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2358 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002359
2360 if (!InitExpr) {
2361 FD->setInvalidDecl();
2362 FD->removeInClassInitializer();
2363 return;
2364 }
2365
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002366 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2367 FD->setInvalidDecl();
2368 FD->removeInClassInitializer();
2369 return;
2370 }
2371
Richard Smith938f40b2011-06-11 17:19:42 +00002372 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002373 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002374 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002375 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002376 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002377 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002378 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2379 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002380 if (Init.isInvalid()) {
2381 FD->setInvalidDecl();
2382 return;
2383 }
Richard Smith938f40b2011-06-11 17:19:42 +00002384 }
2385
Richard Smith945f8d32013-01-14 22:39:08 +00002386 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002387 // The initialization of each base and member constitutes a
2388 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002389 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002390 if (Init.isInvalid()) {
2391 FD->setInvalidDecl();
2392 return;
2393 }
2394
2395 InitExpr = Init.release();
2396
2397 FD->setInClassInitializer(InitExpr);
2398}
2399
Douglas Gregor15e77a22009-12-31 09:10:24 +00002400/// \brief Find the direct and/or virtual base specifiers that
2401/// correspond to the given base type, for use in base initialization
2402/// within a constructor.
2403static bool FindBaseInitializer(Sema &SemaRef,
2404 CXXRecordDecl *ClassDecl,
2405 QualType BaseType,
2406 const CXXBaseSpecifier *&DirectBaseSpec,
2407 const CXXBaseSpecifier *&VirtualBaseSpec) {
2408 // First, check for a direct base class.
2409 DirectBaseSpec = 0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002410 for (const auto &Base : ClassDecl->bases()) {
2411 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002412 // We found a direct base of this type. That's what we're
2413 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002414 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002415 break;
2416 }
2417 }
2418
2419 // Check for a virtual base class.
2420 // FIXME: We might be able to short-circuit this if we know in advance that
2421 // there are no virtual bases.
2422 VirtualBaseSpec = 0;
2423 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2424 // We haven't found a base yet; search the class hierarchy for a
2425 // virtual base class.
2426 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2427 /*DetectVirtual=*/false);
2428 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2429 BaseType, Paths)) {
2430 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2431 Path != Paths.end(); ++Path) {
2432 if (Path->back().Base->isVirtual()) {
2433 VirtualBaseSpec = Path->back().Base;
2434 break;
2435 }
2436 }
2437 }
2438 }
2439
2440 return DirectBaseSpec || VirtualBaseSpec;
2441}
2442
Sebastian Redla74948d2011-09-24 17:48:25 +00002443/// \brief Handle a C++ member initializer using braced-init-list syntax.
2444MemInitResult
2445Sema::ActOnMemInitializer(Decl *ConstructorD,
2446 Scope *S,
2447 CXXScopeSpec &SS,
2448 IdentifierInfo *MemberOrBase,
2449 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002450 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002451 SourceLocation IdLoc,
2452 Expr *InitList,
2453 SourceLocation EllipsisLoc) {
2454 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002455 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002456 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002457}
2458
2459/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002460MemInitResult
John McCall48871652010-08-21 09:40:31 +00002461Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002462 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002463 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002464 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002465 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002466 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002467 SourceLocation IdLoc,
2468 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002469 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002470 SourceLocation RParenLoc,
2471 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002472 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002473 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002474 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002475 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002476}
2477
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002478namespace {
2479
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002480// Callback to only accept typo corrections that can be a valid C++ member
2481// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002482class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002483public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002484 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2485 : ClassDecl(ClassDecl) {}
2486
Craig Toppera798a9d2014-03-02 09:32:10 +00002487 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002488 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2489 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2490 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002491 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002492 }
2493 return false;
2494 }
2495
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002496private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002497 CXXRecordDecl *ClassDecl;
2498};
2499
2500}
2501
Sebastian Redla74948d2011-09-24 17:48:25 +00002502/// \brief Handle a C++ member initializer.
2503MemInitResult
2504Sema::BuildMemInitializer(Decl *ConstructorD,
2505 Scope *S,
2506 CXXScopeSpec &SS,
2507 IdentifierInfo *MemberOrBase,
2508 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002509 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002510 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002511 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002512 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002513 if (!ConstructorD)
2514 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002515
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002516 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002517
2518 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002519 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002520 if (!Constructor) {
2521 // The user wrote a constructor initializer on a function that is
2522 // not a C++ constructor. Ignore the error for now, because we may
2523 // have more member initializers coming; we'll diagnose it just
2524 // once in ActOnMemInitializers.
2525 return true;
2526 }
2527
2528 CXXRecordDecl *ClassDecl = Constructor->getParent();
2529
2530 // C++ [class.base.init]p2:
2531 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002532 // constructor's class and, if not found in that scope, are looked
2533 // up in the scope containing the constructor's definition.
2534 // [Note: if the constructor's class contains a member with the
2535 // same name as a direct or virtual base class of the class, a
2536 // mem-initializer-id naming the member or base class and composed
2537 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002538 // mem-initializer-id for the hidden base class may be specified
2539 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002540 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002541 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002542 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002543 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002544 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002545 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002546 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2547 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002548 if (EllipsisLoc.isValid())
2549 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002550 << MemberOrBase
2551 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002552
Sebastian Redla9351792012-02-11 23:51:47 +00002553 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002554 }
Francois Pichetd583da02010-12-04 09:14:42 +00002555 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002556 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002557 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002558 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002559 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002560
2561 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002562 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002563 } else if (DS.getTypeSpecType() == TST_decltype) {
2564 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002565 } else {
2566 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2567 LookupParsedName(R, S, &SS);
2568
2569 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2570 if (!TyD) {
2571 if (R.isAmbiguous()) return true;
2572
John McCallda6841b2010-04-09 19:01:14 +00002573 // We don't want access-control diagnostics here.
2574 R.suppressDiagnostics();
2575
Douglas Gregora3b624a2010-01-19 06:46:48 +00002576 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2577 bool NotUnknownSpecialization = false;
2578 DeclContext *DC = computeDeclContext(SS, false);
2579 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2580 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2581
2582 if (!NotUnknownSpecialization) {
2583 // When the scope specifier can refer to a member of an unknown
2584 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002585 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2586 SS.getWithLocInContext(Context),
2587 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002588 if (BaseType.isNull())
2589 return true;
2590
Douglas Gregora3b624a2010-01-19 06:46:48 +00002591 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002592 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002593 }
2594 }
2595
Douglas Gregor15e77a22009-12-31 09:10:24 +00002596 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002597 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002598 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002599 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002600 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00002601 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002602 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002603 // We have found a non-static data member with a similar
2604 // name to what was typed; complain and initialize that
2605 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002606 diagnoseTypo(Corr,
2607 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2608 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002609 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002610 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002611 const CXXBaseSpecifier *DirectBaseSpec;
2612 const CXXBaseSpecifier *VirtualBaseSpec;
2613 if (FindBaseInitializer(*this, ClassDecl,
2614 Context.getTypeDeclType(Type),
2615 DirectBaseSpec, VirtualBaseSpec)) {
2616 // We have found a direct or virtual base class with a
2617 // similar name to what was typed; complain and initialize
2618 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002619 diagnoseTypo(Corr,
2620 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2621 << MemberOrBase << false,
2622 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002623
Richard Smithf9b15102013-08-17 00:46:16 +00002624 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2625 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002626 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002627 diag::note_base_class_specified_here)
2628 << BaseSpec->getType()
2629 << BaseSpec->getSourceRange();
2630
Douglas Gregor15e77a22009-12-31 09:10:24 +00002631 TyD = Type;
2632 }
2633 }
2634 }
2635
Douglas Gregora3b624a2010-01-19 06:46:48 +00002636 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002637 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002638 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002639 return true;
2640 }
John McCallb5a0d312009-12-21 10:41:20 +00002641 }
2642
Douglas Gregora3b624a2010-01-19 06:46:48 +00002643 if (BaseType.isNull()) {
2644 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002645 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002646 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002647 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2648 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002649 }
2650 }
Mike Stump11289f42009-09-09 15:08:12 +00002651
John McCallbcd03502009-12-07 02:54:59 +00002652 if (!TInfo)
2653 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002654
Sebastian Redla9351792012-02-11 23:51:47 +00002655 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002656}
2657
Chandler Carruth599deef2011-09-03 01:14:15 +00002658/// Checks a member initializer expression for cases where reference (or
2659/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002660static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2661 Expr *Init,
2662 SourceLocation IdLoc) {
2663 QualType MemberTy = Member->getType();
2664
2665 // We only handle pointers and references currently.
2666 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2667 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2668 return;
2669
2670 const bool IsPointer = MemberTy->isPointerType();
2671 if (IsPointer) {
2672 if (const UnaryOperator *Op
2673 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2674 // The only case we're worried about with pointers requires taking the
2675 // address.
2676 if (Op->getOpcode() != UO_AddrOf)
2677 return;
2678
2679 Init = Op->getSubExpr();
2680 } else {
2681 // We only handle address-of expression initializers for pointers.
2682 return;
2683 }
2684 }
2685
Richard Smithe3b28bc2013-06-12 21:51:50 +00002686 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002687 // We only warn when referring to a non-reference parameter declaration.
2688 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2689 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002690 return;
2691
2692 S.Diag(Init->getExprLoc(),
2693 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2694 : diag::warn_bind_ref_member_to_parameter)
2695 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002696 } else {
2697 // Other initializers are fine.
2698 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002699 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002700
2701 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2702 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002703}
2704
John McCallfaf5fb42010-08-26 23:41:50 +00002705MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002706Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002707 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002708 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2709 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2710 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002711 "Member must be a FieldDecl or IndirectFieldDecl");
2712
Sebastian Redla9351792012-02-11 23:51:47 +00002713 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002714 return true;
2715
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002716 if (Member->isInvalidDecl())
2717 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002718
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002719 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002720 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002721 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002722 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002723 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002724 } else {
2725 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002726 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002727 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002728
Sebastian Redla9351792012-02-11 23:51:47 +00002729 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002730
Sebastian Redla9351792012-02-11 23:51:47 +00002731 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002732 // Can't check initialization for a member of dependent type or when
2733 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002734 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002735 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002736 bool InitList = false;
2737 if (isa<InitListExpr>(Init)) {
2738 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002739 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002740 }
2741
Chandler Carruthd44c3102010-12-06 09:23:57 +00002742 // Initialize the member.
2743 InitializedEntity MemberEntity =
2744 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2745 : InitializedEntity::InitializeMember(IndirectMember, 0);
2746 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002747 InitList ? InitializationKind::CreateDirectList(IdLoc)
2748 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2749 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002750
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002751 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2752 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002753 if (MemberInit.isInvalid())
2754 return true;
2755
Richard Smith736a9472013-06-12 20:42:33 +00002756 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2757
Richard Smith945f8d32013-01-14 22:39:08 +00002758 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002759 // The initialization of each base and member constitutes a
2760 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002761 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002762 if (MemberInit.isInvalid())
2763 return true;
2764
Richard Smithd59b8322012-12-19 01:39:02 +00002765 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002766 }
2767
Chandler Carruthd44c3102010-12-06 09:23:57 +00002768 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002769 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2770 InitRange.getBegin(), Init,
2771 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002772 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002773 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2774 InitRange.getBegin(), Init,
2775 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002776 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002777}
2778
John McCallfaf5fb42010-08-26 23:41:50 +00002779MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002780Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002781 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002782 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002783 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002784 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002785 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002786 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002787
Sebastian Redl0501c632012-02-12 16:37:36 +00002788 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002789 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002790 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2791 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002792 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002793 }
2794
Sebastian Redla9351792012-02-11 23:51:47 +00002795 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002796 // Initialize the object.
2797 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2798 QualType(ClassDecl->getTypeForDecl(), 0));
2799 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002800 InitList ? InitializationKind::CreateDirectList(NameLoc)
2801 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2802 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002803 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002804 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002805 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002806 if (DelegationInit.isInvalid())
2807 return true;
2808
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002809 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2810 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002811
Richard Smith945f8d32013-01-14 22:39:08 +00002812 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002813 // The initialization of each base and member constitutes a
2814 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002815 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2816 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002817 if (DelegationInit.isInvalid())
2818 return true;
2819
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002820 // If we are in a dependent context, template instantiation will
2821 // perform this type-checking again. Just save the arguments that we
2822 // received in a ParenListExpr.
2823 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2824 // of the information that we have about the base
2825 // initializer. However, deconstructing the ASTs is a dicey process,
2826 // and this approach is far more likely to get the corner cases right.
2827 if (CurContext->isDependentContext())
2828 DelegationInit = Owned(Init);
2829
Sebastian Redla9351792012-02-11 23:51:47 +00002830 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002831 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002832 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002833}
2834
2835MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002836Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002837 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002838 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002839 SourceLocation BaseLoc
2840 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002841
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002842 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2843 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2844 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2845
2846 // C++ [class.base.init]p2:
2847 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002848 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002849 // of that class, the mem-initializer is ill-formed. A
2850 // mem-initializer-list can initialize a base class using any
2851 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002852 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002853
Sebastian Redla9351792012-02-11 23:51:47 +00002854 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002855 if (EllipsisLoc.isValid()) {
2856 // This is a pack expansion.
2857 if (!BaseType->containsUnexpandedParameterPack()) {
2858 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002859 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002860
Douglas Gregor44e7df62011-01-04 00:32:56 +00002861 EllipsisLoc = SourceLocation();
2862 }
2863 } else {
2864 // Check for any unexpanded parameter packs.
2865 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2866 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002867
Sebastian Redla9351792012-02-11 23:51:47 +00002868 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002869 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002870 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002871
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002872 // Check for direct and virtual base classes.
2873 const CXXBaseSpecifier *DirectBaseSpec = 0;
2874 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2875 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002876 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2877 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002878 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002879
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002880 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2881 VirtualBaseSpec);
2882
2883 // C++ [base.class.init]p2:
2884 // Unless the mem-initializer-id names a nonstatic data member of the
2885 // constructor's class or a direct or virtual base of that class, the
2886 // mem-initializer is ill-formed.
2887 if (!DirectBaseSpec && !VirtualBaseSpec) {
2888 // If the class has any dependent bases, then it's possible that
2889 // one of those types will resolve to the same type as
2890 // BaseType. Therefore, just treat this as a dependent base
2891 // class initialization. FIXME: Should we try to check the
2892 // initialization anyway? It seems odd.
2893 if (ClassDecl->hasAnyDependentBases())
2894 Dependent = true;
2895 else
2896 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2897 << BaseType << Context.getTypeDeclType(ClassDecl)
2898 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2899 }
2900 }
2901
2902 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002903 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002904
Sebastian Redla74948d2011-09-24 17:48:25 +00002905 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2906 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002907 InitRange.getBegin(), Init,
2908 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002909 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002910
2911 // C++ [base.class.init]p2:
2912 // If a mem-initializer-id is ambiguous because it designates both
2913 // a direct non-virtual base class and an inherited virtual base
2914 // class, the mem-initializer is ill-formed.
2915 if (DirectBaseSpec && VirtualBaseSpec)
2916 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002917 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002918
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002919 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002920 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002921 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002922
2923 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002924 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002925 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002926 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002927 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002928 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002929 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002930
2931 InitializedEntity BaseEntity =
2932 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2933 InitializationKind Kind =
2934 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2935 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2936 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002937 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2938 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002939 if (BaseInit.isInvalid())
2940 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002941
Richard Smith945f8d32013-01-14 22:39:08 +00002942 // C++11 [class.base.init]p7:
2943 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002944 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002945 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002946 if (BaseInit.isInvalid())
2947 return true;
2948
2949 // If we are in a dependent context, template instantiation will
2950 // perform this type-checking again. Just save the arguments that we
2951 // received in a ParenListExpr.
2952 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2953 // of the information that we have about the base
2954 // initializer. However, deconstructing the ASTs is a dicey process,
2955 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002956 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002957 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002958
Alexis Hunt1d792652011-01-08 20:30:50 +00002959 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002960 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002961 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002962 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002963 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002964}
2965
Sebastian Redl22653ba2011-08-30 19:58:05 +00002966// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002967static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2968 if (T.isNull()) T = E->getType();
2969 QualType TargetType = SemaRef.BuildReferenceType(
2970 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002971 SourceLocation ExprLoc = E->getLocStart();
2972 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2973 TargetType, ExprLoc);
2974
2975 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2976 SourceRange(ExprLoc, ExprLoc),
2977 E->getSourceRange()).take();
2978}
2979
Anders Carlsson1b00e242010-04-23 03:10:23 +00002980/// ImplicitInitializerKind - How an implicit base or member initializer should
2981/// initialize its base or member.
2982enum ImplicitInitializerKind {
2983 IIK_Default,
2984 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002985 IIK_Move,
2986 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002987};
2988
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002989static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002990BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002991 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002992 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002993 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002994 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002995 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002996 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2997 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002998
John McCalldadc5752010-08-24 06:29:42 +00002999 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003000
3001 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003002 case IIK_Inherit: {
3003 const CXXRecordDecl *Inherited =
3004 Constructor->getInheritedConstructor()->getParent();
3005 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3006 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3007 // C++11 [class.inhctor]p8:
3008 // Each expression in the expression-list is of the form
3009 // static_cast<T&&>(p), where p is the name of the corresponding
3010 // constructor parameter and T is the declared type of p.
3011 SmallVector<Expr*, 16> Args;
3012 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3013 ParmVarDecl *PD = Constructor->getParamDecl(I);
3014 ExprResult ArgExpr =
3015 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3016 VK_LValue, SourceLocation());
3017 if (ArgExpr.isInvalid())
3018 return true;
3019 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3020 }
3021
3022 InitializationKind InitKind = InitializationKind::CreateDirect(
3023 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003024 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003025 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3026 break;
3027 }
3028 }
3029 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003030 case IIK_Default: {
3031 InitializationKind InitKind
3032 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003033 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3034 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003035 break;
3036 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003037
Sebastian Redl22653ba2011-08-30 19:58:05 +00003038 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003039 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003040 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003041 ParmVarDecl *Param = Constructor->getParamDecl(0);
3042 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003043
Anders Carlsson1b00e242010-04-23 03:10:23 +00003044 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003045 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003046 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003047 Constructor->getLocation(), ParamType,
3048 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003049
Eli Friedmanfa0df832012-02-02 03:46:19 +00003050 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3051
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003052 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003053 QualType ArgTy =
3054 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3055 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003056
Sebastian Redl22653ba2011-08-30 19:58:05 +00003057 if (Moving) {
3058 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3059 }
3060
John McCallcf142162010-08-07 06:22:56 +00003061 CXXCastPath BasePath;
3062 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003063 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3064 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003065 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003066 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003067
Anders Carlsson1b00e242010-04-23 03:10:23 +00003068 InitializationKind InitKind
3069 = InitializationKind::CreateDirect(Constructor->getLocation(),
3070 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003071 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3072 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003073 break;
3074 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003075 }
John McCallb268a282010-08-23 23:25:46 +00003076
Douglas Gregora40433a2010-12-07 00:41:46 +00003077 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003078 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003079 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003080
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003081 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003082 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003083 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3084 SourceLocation()),
3085 BaseSpec->isVirtual(),
3086 SourceLocation(),
3087 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003088 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003089 SourceLocation());
3090
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003091 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003092}
3093
Sebastian Redl22653ba2011-08-30 19:58:05 +00003094static bool RefersToRValueRef(Expr *MemRef) {
3095 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3096 return Referenced->getType()->isRValueReferenceType();
3097}
3098
Anders Carlsson3c1db572010-04-23 02:15:47 +00003099static bool
3100BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003101 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003102 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003103 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003104 if (Field->isInvalidDecl())
3105 return true;
3106
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003107 SourceLocation Loc = Constructor->getLocation();
3108
Sebastian Redl22653ba2011-08-30 19:58:05 +00003109 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3110 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003111 ParmVarDecl *Param = Constructor->getParamDecl(0);
3112 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003113
3114 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003115 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3116 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003117
Anders Carlsson423f5d82010-04-23 16:04:08 +00003118 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003119 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003120 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003121 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003122
Eli Friedmanfa0df832012-02-02 03:46:19 +00003123 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3124
Sebastian Redl22653ba2011-08-30 19:58:05 +00003125 if (Moving) {
3126 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3127 }
3128
Douglas Gregor94f9a482010-05-05 05:51:00 +00003129 // Build a reference to this field within the parameter.
3130 CXXScopeSpec SS;
3131 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3132 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003133 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3134 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003135 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003136 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003137 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003138 ParamType, Loc,
3139 /*IsArrow=*/false,
3140 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003141 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00003142 /*FirstQualifierInScope=*/0,
3143 MemberLookup,
3144 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003145 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003146 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003147
3148 // C++11 [class.copy]p15:
3149 // - if a member m has rvalue reference type T&&, it is direct-initialized
3150 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003151 if (RefersToRValueRef(CtorArg.get())) {
3152 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003153 }
3154
Douglas Gregor94f9a482010-05-05 05:51:00 +00003155 // When the field we are copying is an array, create index variables for
3156 // each dimension of the array. We use these index variables to subscript
3157 // the source array, and other clients (e.g., CodeGen) will perform the
3158 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003159 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003160 QualType BaseType = Field->getType();
3161 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003162 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003163 while (const ConstantArrayType *Array
3164 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003165 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003166 // Create the iteration variable for this array index.
3167 IdentifierInfo *IterationVarName = 0;
3168 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003169 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003170 llvm::raw_svector_ostream OS(Str);
3171 OS << "__i" << IndexVariables.size();
3172 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3173 }
3174 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003175 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003176 IterationVarName, SizeType,
3177 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003178 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003179 IndexVariables.push_back(IterationVar);
3180
3181 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003182 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003183 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003184 assert(!IterationVarRef.isInvalid() &&
3185 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003186 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3187 assert(!IterationVarRef.isInvalid() &&
3188 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003189
Douglas Gregor94f9a482010-05-05 05:51:00 +00003190 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003191 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003192 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003193 Loc);
3194 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003195 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003196
Douglas Gregor94f9a482010-05-05 05:51:00 +00003197 BaseType = Array->getElementType();
3198 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003199
3200 // The array subscript expression is an lvalue, which is wrong for moving.
3201 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003202 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003203
Douglas Gregor94f9a482010-05-05 05:51:00 +00003204 // Construct the entity that we will be initializing. For an array, this
3205 // will be first element in the array, which may require several levels
3206 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003207 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003208 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003209 if (Indirect)
3210 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3211 else
3212 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003213 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3214 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3215 0,
3216 Entities.back()));
3217
3218 // Direct-initialize to use the copy constructor.
3219 InitializationKind InitKind =
3220 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3221
Sebastian Redle9c4e842011-09-04 18:14:28 +00003222 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003223 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003224
John McCalldadc5752010-08-24 06:29:42 +00003225 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003226 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003227 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003228 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003229 if (MemberInit.isInvalid())
3230 return true;
3231
Douglas Gregor493627b2011-08-10 15:22:55 +00003232 if (Indirect) {
3233 assert(IndexVariables.size() == 0 &&
3234 "Indirect field improperly initialized");
3235 CXXMemberInit
3236 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3237 Loc, Loc,
3238 MemberInit.takeAs<Expr>(),
3239 Loc);
3240 } else
3241 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3242 Loc, MemberInit.takeAs<Expr>(),
3243 Loc,
3244 IndexVariables.data(),
3245 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003246 return false;
3247 }
3248
Richard Smithc2bc61b2013-03-18 21:12:30 +00003249 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3250 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003251
Anders Carlsson3c1db572010-04-23 02:15:47 +00003252 QualType FieldBaseElementType =
3253 SemaRef.Context.getBaseElementType(Field->getType());
3254
Anders Carlsson3c1db572010-04-23 02:15:47 +00003255 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003256 InitializedEntity InitEntity
3257 = Indirect? InitializedEntity::InitializeMember(Indirect)
3258 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003259 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003260 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003261
3262 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3263 ExprResult MemberInit =
3264 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003265
Douglas Gregora40433a2010-12-07 00:41:46 +00003266 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003267 if (MemberInit.isInvalid())
3268 return true;
3269
Douglas Gregor493627b2011-08-10 15:22:55 +00003270 if (Indirect)
3271 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3272 Indirect, Loc,
3273 Loc,
3274 MemberInit.get(),
3275 Loc);
3276 else
3277 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3278 Field, Loc, Loc,
3279 MemberInit.get(),
3280 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003281 return false;
3282 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003283
Alexis Hunt8b455182011-05-17 00:19:05 +00003284 if (!Field->getParent()->isUnion()) {
3285 if (FieldBaseElementType->isReferenceType()) {
3286 SemaRef.Diag(Constructor->getLocation(),
3287 diag::err_uninitialized_member_in_ctor)
3288 << (int)Constructor->isImplicit()
3289 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3290 << 0 << Field->getDeclName();
3291 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3292 return true;
3293 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003294
Alexis Hunt8b455182011-05-17 00:19:05 +00003295 if (FieldBaseElementType.isConstQualified()) {
3296 SemaRef.Diag(Constructor->getLocation(),
3297 diag::err_uninitialized_member_in_ctor)
3298 << (int)Constructor->isImplicit()
3299 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3300 << 1 << Field->getDeclName();
3301 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3302 return true;
3303 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003304 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003305
David Blaikiebbafb8a2012-03-11 07:00:24 +00003306 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003307 FieldBaseElementType->isObjCRetainableType() &&
3308 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3309 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003310 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003311 // Default-initialize Objective-C pointers to NULL.
3312 CXXMemberInit
3313 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3314 Loc, Loc,
3315 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3316 Loc);
3317 return false;
3318 }
3319
Anders Carlsson3c1db572010-04-23 02:15:47 +00003320 // Nothing to initialize.
3321 CXXMemberInit = 0;
3322 return false;
3323}
John McCallbc83b3f2010-05-20 23:23:51 +00003324
3325namespace {
3326struct BaseAndFieldInfo {
3327 Sema &S;
3328 CXXConstructorDecl *Ctor;
3329 bool AnyErrorsInInits;
3330 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003331 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003332 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003333 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003334
3335 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3336 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003337 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3338 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003339 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003340 else if (Generated && Ctor->isMoveConstructor())
3341 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003342 else if (Ctor->getInheritedConstructor())
3343 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003344 else
3345 IIK = IIK_Default;
3346 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003347
3348 bool isImplicitCopyOrMove() const {
3349 switch (IIK) {
3350 case IIK_Copy:
3351 case IIK_Move:
3352 return true;
3353
3354 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003355 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003356 return false;
3357 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003358
3359 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003360 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003361
3362 bool addFieldInitializer(CXXCtorInitializer *Init) {
3363 AllToInit.push_back(Init);
3364
3365 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003366 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003367 S.UnusedPrivateFields.remove(Init->getAnyMember());
3368
3369 return false;
3370 }
John McCallbc83b3f2010-05-20 23:23:51 +00003371
Richard Smithab44d5b2013-12-10 08:25:00 +00003372 bool isInactiveUnionMember(FieldDecl *Field) {
3373 RecordDecl *Record = Field->getParent();
3374 if (!Record->isUnion())
3375 return false;
3376
Richard Smith8d183852013-12-10 20:56:03 +00003377 if (FieldDecl *Active =
3378 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003379 return Active != Field->getCanonicalDecl();
3380
3381 // In an implicit copy or move constructor, ignore any in-class initializer.
3382 if (isImplicitCopyOrMove())
3383 return true;
3384
3385 // If there's no explicit initialization, the field is active only if it
3386 // has an in-class initializer...
3387 if (Field->hasInClassInitializer())
3388 return false;
3389 // ... or it's an anonymous struct or union whose class has an in-class
3390 // initializer.
3391 if (!Field->isAnonymousStructOrUnion())
3392 return true;
3393 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3394 return !FieldRD->hasInClassInitializer();
3395 }
3396
3397 /// \brief Determine whether the given field is, or is within, a union member
3398 /// that is inactive (because there was an initializer given for a different
3399 /// member of the union, or because the union was not initialized at all).
3400 bool isWithinInactiveUnionMember(FieldDecl *Field,
3401 IndirectFieldDecl *Indirect) {
3402 if (!Indirect)
3403 return isInactiveUnionMember(Field);
3404
Aaron Ballman29c94602014-03-07 18:36:15 +00003405 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003406 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003407 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003408 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003409 }
3410 return false;
3411 }
3412};
Richard Smithc94ec842011-09-19 13:34:43 +00003413}
3414
Douglas Gregor10f939c2011-11-02 23:04:16 +00003415/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3416/// array type.
3417static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3418 if (T->isIncompleteArrayType())
3419 return true;
3420
3421 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3422 if (!ArrayT->getSize())
3423 return true;
3424
3425 T = ArrayT->getElementType();
3426 }
3427
3428 return false;
3429}
3430
Richard Smith938f40b2011-06-11 17:19:42 +00003431static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003432 FieldDecl *Field,
3433 IndirectFieldDecl *Indirect = 0) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003434 if (Field->isInvalidDecl())
3435 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003436
Chandler Carruth139e9622010-06-30 02:59:29 +00003437 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0a8cfc72012-08-07 21:30:42 +00003438 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3439 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003440
Richard Smithab44d5b2013-12-10 08:25:00 +00003441 // C++11 [class.base.init]p8:
3442 // if the entity is a non-static data member that has a
3443 // brace-or-equal-initializer and either
3444 // -- the constructor's class is a union and no other variant member of that
3445 // union is designated by a mem-initializer-id or
3446 // -- the constructor's class is not a union, and, if the entity is a member
3447 // of an anonymous union, no other member of that union is designated by
3448 // a mem-initializer-id,
3449 // the entity is initialized as specified in [dcl.init].
3450 //
3451 // We also apply the same rules to handle anonymous structs within anonymous
3452 // unions.
3453 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3454 return false;
3455
Douglas Gregor7db3e952011-11-28 20:03:15 +00003456 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003457 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3458 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003459 CXXCtorInitializer *Init;
3460 if (Indirect)
3461 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3462 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003463 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003464 SourceLocation());
3465 else
3466 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3467 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003468 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003469 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003470 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003471 }
3472
Douglas Gregor10f939c2011-11-02 23:04:16 +00003473 // Don't initialize incomplete or zero-length arrays.
3474 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3475 return false;
3476
John McCallbc83b3f2010-05-20 23:23:51 +00003477 // Don't try to build an implicit initializer if there were semantic
3478 // errors in any of the initializers (and therefore we might be
3479 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003480 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003481 return false;
3482
Alexis Hunt1d792652011-01-08 20:30:50 +00003483 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003484 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3485 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003486 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003487
Richard Smith0a8cfc72012-08-07 21:30:42 +00003488 if (!Init)
3489 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003490
Richard Smith0a8cfc72012-08-07 21:30:42 +00003491 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003492}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003493
3494bool
3495Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3496 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003497 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003498 Constructor->setNumCtorInitializers(1);
3499 CXXCtorInitializer **initializer =
3500 new (Context) CXXCtorInitializer*[1];
3501 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3502 Constructor->setCtorInitializers(initializer);
3503
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003504 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003505 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003506 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3507 }
3508
Alexis Hunte2622992011-05-05 00:05:47 +00003509 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003510
Alexis Hunt61bc1732011-05-01 07:04:31 +00003511 return false;
3512}
Douglas Gregor493627b2011-08-10 15:22:55 +00003513
David Blaikie3fc2f912013-01-17 05:26:25 +00003514bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3515 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003516 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003517 // Just store the initializers as written, they will be checked during
3518 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003519 if (!Initializers.empty()) {
3520 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003521 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003522 new (Context) CXXCtorInitializer*[Initializers.size()];
3523 memcpy(baseOrMemberInitializers, Initializers.data(),
3524 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003525 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003526 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003527
3528 // Let template instantiation know whether we had errors.
3529 if (AnyErrors)
3530 Constructor->setInvalidDecl();
3531
Anders Carlssondb0a9652010-04-02 06:26:44 +00003532 return false;
3533 }
3534
John McCallbc83b3f2010-05-20 23:23:51 +00003535 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003536
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003537 // We need to build the initializer AST according to order of construction
3538 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003539 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003540 if (!ClassDecl)
3541 return true;
3542
Eli Friedman9cf6b592009-11-09 19:20:36 +00003543 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003544
David Blaikie3fc2f912013-01-17 05:26:25 +00003545 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003546 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003547
Anders Carlssondb0a9652010-04-02 06:26:44 +00003548 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003549 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003550 else {
Francois Pichetd583da02010-12-04 09:14:42 +00003551 Info.AllBaseFields[Member->getAnyMember()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003552
3553 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003554 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003555 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003556 if (FD && FD->getParent()->isUnion())
3557 Info.ActiveUnionMember.insert(std::make_pair(
3558 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3559 }
3560 } else if (FieldDecl *FD = Member->getMember()) {
3561 if (FD->getParent()->isUnion())
3562 Info.ActiveUnionMember.insert(std::make_pair(
3563 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3564 }
3565 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003566 }
3567
Anders Carlsson43c64af2010-04-21 19:52:01 +00003568 // Keep track of the direct virtual bases.
3569 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003570 for (auto &I : ClassDecl->bases()) {
3571 if (I.isVirtual())
3572 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003573 }
3574
Anders Carlssondb0a9652010-04-02 06:26:44 +00003575 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003576 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003577 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003578 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003579 // [class.base.init]p7, per DR257:
3580 // A mem-initializer where the mem-initializer-id names a virtual base
3581 // class is ignored during execution of a constructor of any class that
3582 // is not the most derived class.
3583 if (ClassDecl->isAbstract()) {
3584 // FIXME: Provide a fixit to remove the base specifier. This requires
3585 // tracking the location of the associated comma for a base specifier.
3586 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003587 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003588 DiagnoseAbstractType(ClassDecl);
3589 }
3590
John McCallbc83b3f2010-05-20 23:23:51 +00003591 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003592 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3593 // [class.base.init]p8, per DR257:
3594 // If a given [...] base class is not named by a mem-initializer-id
3595 // [...] and the entity is not a virtual base class of an abstract
3596 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003597 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003598 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003599 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003600 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003601 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003602 HadError = true;
3603 continue;
3604 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003605
John McCallbc83b3f2010-05-20 23:23:51 +00003606 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003607 }
3608 }
Mike Stump11289f42009-09-09 15:08:12 +00003609
John McCallbc83b3f2010-05-20 23:23:51 +00003610 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003611 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003612 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003613 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003614 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003615
Alexis Hunt1d792652011-01-08 20:30:50 +00003616 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003617 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003618 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003619 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003620 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003621 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003622 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003623 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003624 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003625 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003626 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003627
John McCallbc83b3f2010-05-20 23:23:51 +00003628 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003629 }
3630 }
Mike Stump11289f42009-09-09 15:08:12 +00003631
John McCallbc83b3f2010-05-20 23:23:51 +00003632 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003633 for (auto *Mem : ClassDecl->decls()) {
3634 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003635 // C++ [class.bit]p2:
3636 // A declaration for a bit-field that omits the identifier declares an
3637 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3638 // initialized.
3639 if (F->isUnnamedBitfield())
3640 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003641
Sebastian Redl22653ba2011-08-30 19:58:05 +00003642 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003643 // handle anonymous struct/union fields based on their individual
3644 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003645 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003646 continue;
3647
3648 if (CollectFieldInitializer(*this, Info, F))
3649 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003650 continue;
3651 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003652
3653 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003654 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003655 continue;
3656
Aaron Ballman629afae2014-03-07 19:56:05 +00003657 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003658 if (F->getType()->isIncompleteArrayType()) {
3659 assert(ClassDecl->hasFlexibleArrayMember() &&
3660 "Incomplete array type is not valid");
3661 continue;
3662 }
3663
Douglas Gregor493627b2011-08-10 15:22:55 +00003664 // Initialize each field of an anonymous struct individually.
3665 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3666 HadError = true;
3667
3668 continue;
3669 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003670 }
Mike Stump11289f42009-09-09 15:08:12 +00003671
David Blaikie3fc2f912013-01-17 05:26:25 +00003672 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003673 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003674 Constructor->setNumCtorInitializers(NumInitializers);
3675 CXXCtorInitializer **baseOrMemberInitializers =
3676 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003677 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003678 NumInitializers * sizeof(CXXCtorInitializer*));
3679 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003680
John McCalla6309952010-03-16 21:39:52 +00003681 // Constructors implicitly reference the base and member
3682 // destructors.
3683 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3684 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003685 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003686
3687 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003688}
3689
David Blaikieb61b8152013-01-17 08:49:22 +00003690static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003691 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003692 const RecordDecl *RD = RT->getDecl();
3693 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003694 for (auto *Field : RD->fields())
3695 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003696 return;
3697 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003698 }
David Blaikieb61b8152013-01-17 08:49:22 +00003699 IdealInits.push_back(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003700}
3701
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003702static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3703 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003704}
3705
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003706static const void *GetKeyForMember(ASTContext &Context,
3707 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003708 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003709 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003710
David Blaikieb61b8152013-01-17 08:49:22 +00003711 return Member->getAnyMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00003712}
3713
David Blaikie3fc2f912013-01-17 05:26:25 +00003714static void DiagnoseBaseOrMemInitializerOrder(
3715 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3716 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003717 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003718 return;
Mike Stump11289f42009-09-09 15:08:12 +00003719
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003720 // Don't check initializers order unless the warning is enabled at the
3721 // location of at least one initializer.
3722 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003723 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003724 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003725 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3726 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003727 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003728 ShouldCheckOrder = true;
3729 break;
3730 }
3731 }
3732 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003733 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003734
John McCallbb7b6582010-04-10 07:37:23 +00003735 // Build the list of bases and members in the order that they'll
3736 // actually be initialized. The explicit initializers should be in
3737 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003738 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003739
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003740 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3741
John McCallbb7b6582010-04-10 07:37:23 +00003742 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003743 for (const auto &VBase : ClassDecl->vbases())
3744 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003745
John McCallbb7b6582010-04-10 07:37:23 +00003746 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003747 for (const auto &Base : ClassDecl->bases()) {
3748 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003749 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003750 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003751 }
Mike Stump11289f42009-09-09 15:08:12 +00003752
John McCallbb7b6582010-04-10 07:37:23 +00003753 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003754 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003755 if (Field->isUnnamedBitfield())
3756 continue;
3757
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003758 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003759 }
3760
John McCallbb7b6582010-04-10 07:37:23 +00003761 unsigned NumIdealInits = IdealInitKeys.size();
3762 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003763
Alexis Hunt1d792652011-01-08 20:30:50 +00003764 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003765 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003766 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003767 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003768
3769 // Scan forward to try to find this initializer in the idealized
3770 // initializers list.
3771 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3772 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003773 break;
John McCallbb7b6582010-04-10 07:37:23 +00003774
3775 // If we didn't find this initializer, it must be because we
3776 // scanned past it on a previous iteration. That can only
3777 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003778 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003779 Sema::SemaDiagnosticBuilder D =
3780 SemaRef.Diag(PrevInit->getSourceLocation(),
3781 diag::warn_initializer_out_of_order);
3782
Francois Pichetd583da02010-12-04 09:14:42 +00003783 if (PrevInit->isAnyMemberInitializer())
3784 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003785 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003786 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003787
Francois Pichetd583da02010-12-04 09:14:42 +00003788 if (Init->isAnyMemberInitializer())
3789 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003790 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003791 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003792
3793 // Move back to the initializer's location in the ideal list.
3794 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3795 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003796 break;
John McCallbb7b6582010-04-10 07:37:23 +00003797
3798 assert(IdealIndex != NumIdealInits &&
3799 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003800 }
John McCallbb7b6582010-04-10 07:37:23 +00003801
3802 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003803 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003804}
3805
John McCall23eebd92010-04-10 09:28:51 +00003806namespace {
3807bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003808 CXXCtorInitializer *Init,
3809 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003810 if (!PrevInit) {
3811 PrevInit = Init;
3812 return false;
3813 }
3814
Douglas Gregorea306a12013-03-25 23:28:23 +00003815 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003816 S.Diag(Init->getSourceLocation(),
3817 diag::err_multiple_mem_initialization)
3818 << Field->getDeclName()
3819 << Init->getSourceRange();
3820 else {
John McCall424cec92011-01-19 06:33:43 +00003821 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003822 assert(BaseClass && "neither field nor base");
3823 S.Diag(Init->getSourceLocation(),
3824 diag::err_multiple_base_initialization)
3825 << QualType(BaseClass, 0)
3826 << Init->getSourceRange();
3827 }
3828 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3829 << 0 << PrevInit->getSourceRange();
3830
3831 return true;
3832}
3833
Alexis Hunt1d792652011-01-08 20:30:50 +00003834typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003835typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3836
3837bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003838 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003839 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003840 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003841 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003842 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003843
3844 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003845 if (Parent->isUnion()) {
3846 UnionEntry &En = Unions[Parent];
3847 if (En.first && En.first != Child) {
3848 S.Diag(Init->getSourceLocation(),
3849 diag::err_multiple_mem_union_initialization)
3850 << Field->getDeclName()
3851 << Init->getSourceRange();
3852 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3853 << 0 << En.second->getSourceRange();
3854 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003855 }
3856 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003857 En.first = Child;
3858 En.second = Init;
3859 }
David Blaikie0f65d592011-11-17 06:01:57 +00003860 if (!Parent->isAnonymousStructOrUnion())
3861 return false;
John McCall23eebd92010-04-10 09:28:51 +00003862 }
3863
3864 Child = Parent;
3865 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003866 }
John McCall23eebd92010-04-10 09:28:51 +00003867
3868 return false;
3869}
3870}
3871
Anders Carlssone857b292010-04-02 03:37:03 +00003872/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003873void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003874 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003875 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003876 bool AnyErrors) {
3877 if (!ConstructorDecl)
3878 return;
3879
3880 AdjustDeclIfTemplate(ConstructorDecl);
3881
3882 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003883 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003884
3885 if (!Constructor) {
3886 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3887 return;
3888 }
3889
John McCall23eebd92010-04-10 09:28:51 +00003890 // Mapping for the duplicate initializers check.
3891 // For member initializers, this is keyed with a FieldDecl*.
3892 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003893 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003894
3895 // Mapping for the inconsistent anonymous-union initializers check.
3896 RedundantUnionMap MemberUnions;
3897
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003898 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003899 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003900 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003901
Abramo Bagnara341d7832010-05-26 18:09:23 +00003902 // Set the source order index.
3903 Init->setSourceOrder(i);
3904
Francois Pichetd583da02010-12-04 09:14:42 +00003905 if (Init->isAnyMemberInitializer()) {
3906 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003907 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3908 CheckRedundantUnionInit(*this, Init, MemberUnions))
3909 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003910 } else if (Init->isBaseInitializer()) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003911 const void *Key =
3912 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall23eebd92010-04-10 09:28:51 +00003913 if (CheckRedundantInit(*this, Init, Members[Key]))
3914 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003915 } else {
3916 assert(Init->isDelegatingInitializer());
3917 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003918 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003919 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003920 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003921 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003922 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003923 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003924 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003925 // Return immediately as the initializer is set.
3926 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003927 }
Anders Carlssone857b292010-04-02 03:37:03 +00003928 }
3929
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003930 if (HadError)
3931 return;
3932
David Blaikie3fc2f912013-01-17 05:26:25 +00003933 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003934
David Blaikie3fc2f912013-01-17 05:26:25 +00003935 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003936
Richard Trieuef64e942013-10-25 00:56:00 +00003937 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003938}
3939
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003940void
John McCalla6309952010-03-16 21:39:52 +00003941Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3942 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003943 // Ignore dependent contexts. Also ignore unions, since their members never
3944 // have destructors implicitly called.
3945 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003946 return;
John McCall1064d7e2010-03-16 05:22:47 +00003947
3948 // FIXME: all the access-control diagnostics are positioned on the
3949 // field/base declaration. That's probably good; that said, the
3950 // user might reasonably want to know why the destructor is being
3951 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003952
Anders Carlssondee9a302009-11-17 04:44:12 +00003953 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003954 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003955 if (Field->isInvalidDecl())
3956 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003957
3958 // Don't destroy incomplete or zero-length arrays.
3959 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3960 continue;
3961
Anders Carlssondee9a302009-11-17 04:44:12 +00003962 QualType FieldType = Context.getBaseElementType(Field->getType());
3963
3964 const RecordType* RT = FieldType->getAs<RecordType>();
3965 if (!RT)
3966 continue;
3967
3968 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003969 if (FieldClassDecl->isInvalidDecl())
3970 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003971 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003972 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003973 // The destructor for an implicit anonymous union member is never invoked.
3974 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3975 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003976
Douglas Gregore71edda2010-07-01 22:47:18 +00003977 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003978 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003979 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003980 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003981 << Field->getDeclName()
3982 << FieldType);
3983
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003984 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003985 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003986 }
3987
John McCall1064d7e2010-03-16 05:22:47 +00003988 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3989
Anders Carlssondee9a302009-11-17 04:44:12 +00003990 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003991 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00003992 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00003993 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00003994
3995 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003996 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003997 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003998
John McCall1064d7e2010-03-16 05:22:47 +00003999 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004000 // If our base class is invalid, we probably can't get its dtor anyway.
4001 if (BaseClassDecl->isInvalidDecl())
4002 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004003 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004004 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004005
Douglas Gregore71edda2010-07-01 22:47:18 +00004006 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004007 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004008
4009 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004010 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004011 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004012 << Base.getType()
4013 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004014 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004015
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004016 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004017 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004018 }
4019
4020 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004021 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004022 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004023 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004024
4025 // Ignore direct virtual bases.
4026 if (DirectVirtualBases.count(RT))
4027 continue;
4028
John McCall1064d7e2010-03-16 05:22:47 +00004029 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004030 // If our base class is invalid, we probably can't get its dtor anyway.
4031 if (BaseClassDecl->isInvalidDecl())
4032 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004033 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004034 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004035
Douglas Gregore71edda2010-07-01 22:47:18 +00004036 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004037 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004038 if (CheckDestructorAccess(
4039 ClassDecl->getLocation(), Dtor,
4040 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004041 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004042 Context.getTypeDeclType(ClassDecl)) ==
4043 AR_accessible) {
4044 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004045 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004046 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4047 SourceRange(), DeclarationName(), 0);
4048 }
John McCall1064d7e2010-03-16 05:22:47 +00004049
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004050 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004051 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004052 }
4053}
4054
John McCall48871652010-08-21 09:40:31 +00004055void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004056 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004057 return;
Mike Stump11289f42009-09-09 15:08:12 +00004058
Mike Stump11289f42009-09-09 15:08:12 +00004059 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004060 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004061 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004062 DiagnoseUninitializedFields(*this, Constructor);
4063 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004064}
4065
Mike Stump11289f42009-09-09 15:08:12 +00004066bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004067 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004068 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4069 unsigned DiagID;
4070 AbstractDiagSelID SelID;
4071
4072 public:
4073 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4074 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004075
Craig Toppera798a9d2014-03-02 09:32:10 +00004076 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004077 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004078 if (SelID == -1)
4079 S.Diag(Loc, DiagID) << T;
4080 else
4081 S.Diag(Loc, DiagID) << SelID << T;
4082 }
4083 } Diagnoser(DiagID, SelID);
4084
4085 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004086}
4087
Anders Carlssoneabf7702009-08-27 00:13:57 +00004088bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004089 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004090 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004091 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004092
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004093 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004094 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004095
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004096 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004097 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004098 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004099 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004100
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004101 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004102 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004103 }
Mike Stump11289f42009-09-09 15:08:12 +00004104
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004105 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004106 if (!RT)
4107 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004108
John McCall67da35c2010-02-04 22:26:26 +00004109 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004110
John McCall02db245d2010-08-18 09:41:07 +00004111 // We can't answer whether something is abstract until it has a
4112 // definition. If it's currently being defined, we'll walk back
4113 // over all the declarations when we have a full definition.
4114 const CXXRecordDecl *Def = RD->getDefinition();
4115 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004116 return false;
4117
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004118 if (!RD->isAbstract())
4119 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004120
Douglas Gregorae298422012-05-04 17:09:59 +00004121 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004122 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004123
John McCall02db245d2010-08-18 09:41:07 +00004124 return true;
4125}
4126
4127void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4128 // Check if we've already emitted the list of pure virtual functions
4129 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004130 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004131 return;
Mike Stump11289f42009-09-09 15:08:12 +00004132
Richard Smithbc46e432013-07-22 02:56:56 +00004133 // If the diagnostic is suppressed, don't emit the notes. We're only
4134 // going to emit them once, so try to attach them to a diagnostic we're
4135 // actually going to show.
4136 if (Diags.isLastDiagnosticIgnored())
4137 return;
4138
Douglas Gregor4165bd62010-03-23 23:47:56 +00004139 CXXFinalOverriderMap FinalOverriders;
4140 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004141
Anders Carlssona2f74f32010-06-03 01:00:02 +00004142 // Keep a set of seen pure methods so we won't diagnose the same method
4143 // more than once.
4144 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4145
Douglas Gregor4165bd62010-03-23 23:47:56 +00004146 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4147 MEnd = FinalOverriders.end();
4148 M != MEnd;
4149 ++M) {
4150 for (OverridingMethods::iterator SO = M->second.begin(),
4151 SOEnd = M->second.end();
4152 SO != SOEnd; ++SO) {
4153 // C++ [class.abstract]p4:
4154 // A class is abstract if it contains or inherits at least one
4155 // pure virtual function for which the final overrider is pure
4156 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004157
Douglas Gregor4165bd62010-03-23 23:47:56 +00004158 //
4159 if (SO->second.size() != 1)
4160 continue;
4161
4162 if (!SO->second.front().Method->isPure())
4163 continue;
4164
Anders Carlssona2f74f32010-06-03 01:00:02 +00004165 if (!SeenPureMethods.insert(SO->second.front().Method))
4166 continue;
4167
Douglas Gregor4165bd62010-03-23 23:47:56 +00004168 Diag(SO->second.front().Method->getLocation(),
4169 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004170 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004171 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004172 }
4173
4174 if (!PureVirtualClassDiagSet)
4175 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4176 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004177}
4178
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004179namespace {
John McCall02db245d2010-08-18 09:41:07 +00004180struct AbstractUsageInfo {
4181 Sema &S;
4182 CXXRecordDecl *Record;
4183 CanQualType AbstractType;
4184 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004185
John McCall02db245d2010-08-18 09:41:07 +00004186 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4187 : S(S), Record(Record),
4188 AbstractType(S.Context.getCanonicalType(
4189 S.Context.getTypeDeclType(Record))),
4190 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004191
John McCall02db245d2010-08-18 09:41:07 +00004192 void DiagnoseAbstractType() {
4193 if (Invalid) return;
4194 S.DiagnoseAbstractType(Record);
4195 Invalid = true;
4196 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004197
John McCall02db245d2010-08-18 09:41:07 +00004198 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4199};
4200
4201struct CheckAbstractUsage {
4202 AbstractUsageInfo &Info;
4203 const NamedDecl *Ctx;
4204
4205 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4206 : Info(Info), Ctx(Ctx) {}
4207
4208 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4209 switch (TL.getTypeLocClass()) {
4210#define ABSTRACT_TYPELOC(CLASS, PARENT)
4211#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004212 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004213#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004214 }
John McCall02db245d2010-08-18 09:41:07 +00004215 }
Mike Stump11289f42009-09-09 15:08:12 +00004216
John McCall02db245d2010-08-18 09:41:07 +00004217 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004218 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004219 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4220 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004221 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004222
4223 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004224 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004225 }
John McCall02db245d2010-08-18 09:41:07 +00004226 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004227
John McCall02db245d2010-08-18 09:41:07 +00004228 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4229 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4230 }
Mike Stump11289f42009-09-09 15:08:12 +00004231
John McCall02db245d2010-08-18 09:41:07 +00004232 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4233 // Visit the type parameters from a permissive context.
4234 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4235 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4236 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4237 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4238 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4239 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004240 }
John McCall02db245d2010-08-18 09:41:07 +00004241 }
Mike Stump11289f42009-09-09 15:08:12 +00004242
John McCall02db245d2010-08-18 09:41:07 +00004243 // Visit pointee types from a permissive context.
4244#define CheckPolymorphic(Type) \
4245 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4246 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4247 }
4248 CheckPolymorphic(PointerTypeLoc)
4249 CheckPolymorphic(ReferenceTypeLoc)
4250 CheckPolymorphic(MemberPointerTypeLoc)
4251 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004252 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004253
John McCall02db245d2010-08-18 09:41:07 +00004254 /// Handle all the types we haven't given a more specific
4255 /// implementation for above.
4256 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4257 // Every other kind of type that we haven't called out already
4258 // that has an inner type is either (1) sugar or (2) contains that
4259 // inner type in some way as a subobject.
4260 if (TypeLoc Next = TL.getNextTypeLoc())
4261 return Visit(Next, Sel);
4262
4263 // If there's no inner type and we're in a permissive context,
4264 // don't diagnose.
4265 if (Sel == Sema::AbstractNone) return;
4266
4267 // Check whether the type matches the abstract type.
4268 QualType T = TL.getType();
4269 if (T->isArrayType()) {
4270 Sel = Sema::AbstractArrayType;
4271 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004272 }
John McCall02db245d2010-08-18 09:41:07 +00004273 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4274 if (CT != Info.AbstractType) return;
4275
4276 // It matched; do some magic.
4277 if (Sel == Sema::AbstractArrayType) {
4278 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4279 << T << TL.getSourceRange();
4280 } else {
4281 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4282 << Sel << T << TL.getSourceRange();
4283 }
4284 Info.DiagnoseAbstractType();
4285 }
4286};
4287
4288void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4289 Sema::AbstractDiagSelID Sel) {
4290 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4291}
4292
4293}
4294
4295/// Check for invalid uses of an abstract type in a method declaration.
4296static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4297 CXXMethodDecl *MD) {
4298 // No need to do the check on definitions, which require that
4299 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004300 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004301 return;
4302
4303 // For safety's sake, just ignore it if we don't have type source
4304 // information. This should never happen for non-implicit methods,
4305 // but...
4306 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4307 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4308}
4309
4310/// Check for invalid uses of an abstract type within a class definition.
4311static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4312 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004313 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004314 if (D->isImplicit()) continue;
4315
4316 // Methods and method templates.
4317 if (isa<CXXMethodDecl>(D)) {
4318 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4319 } else if (isa<FunctionTemplateDecl>(D)) {
4320 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4321 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4322
4323 // Fields and static variables.
4324 } else if (isa<FieldDecl>(D)) {
4325 FieldDecl *FD = cast<FieldDecl>(D);
4326 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4327 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4328 } else if (isa<VarDecl>(D)) {
4329 VarDecl *VD = cast<VarDecl>(D);
4330 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4331 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4332
4333 // Nested classes and class templates.
4334 } else if (isa<CXXRecordDecl>(D)) {
4335 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4336 } else if (isa<ClassTemplateDecl>(D)) {
4337 CheckAbstractClassUsage(Info,
4338 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4339 }
4340 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004341}
4342
Douglas Gregorc99f1552009-12-03 18:33:45 +00004343/// \brief Perform semantic checks on a class definition that has been
4344/// completing, introducing implicitly-declared members, checking for
4345/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004346void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004347 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004348 return;
4349
John McCall02db245d2010-08-18 09:41:07 +00004350 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4351 AbstractUsageInfo Info(*this, Record);
4352 CheckAbstractClassUsage(Info, Record);
4353 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004354
4355 // If this is not an aggregate type and has no user-declared constructor,
4356 // complain about any non-static data members of reference or const scalar
4357 // type, since they will never get initializers.
4358 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004359 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4360 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004361 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004362 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004363 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004364 continue;
4365
Douglas Gregor454a5b62010-04-15 00:00:53 +00004366 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004367 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004368 if (!Complained) {
4369 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4370 << Record->getTagKind() << Record;
4371 Complained = true;
4372 }
4373
4374 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4375 << F->getType()->isReferenceType()
4376 << F->getDeclName();
4377 }
4378 }
4379 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004380
Anders Carlssone771e762011-01-25 18:08:22 +00004381 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004382 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004383
4384 if (Record->getIdentifier()) {
4385 // C++ [class.mem]p13:
4386 // If T is the name of a class, then each of the following shall have a
4387 // name different from T:
4388 // - every member of every anonymous union that is a member of class T.
4389 //
4390 // C++ [class.mem]p14:
4391 // In addition, if class T has a user-declared constructor (12.1), every
4392 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004393 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4394 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4395 ++I) {
4396 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004397 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4398 isa<IndirectFieldDecl>(D)) {
4399 Diag(D->getLocation(), diag::err_member_name_of_class)
4400 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004401 break;
4402 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004403 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004404 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004405
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004406 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004407 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004408 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004409 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004410 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4411 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4412 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004413
David Majnemera5433082013-10-18 00:33:31 +00004414 if (Record->isAbstract()) {
4415 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4416 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4417 << FA->isSpelledAsSealed();
4418 DiagnoseAbstractType(Record);
4419 }
David Blaikie348df502012-09-21 03:21:07 +00004420 }
4421
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004422 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004423 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004424 // See if a method overloads virtual methods in a base
4425 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004426 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004427 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004428
4429 // Check whether the explicitly-defaulted special members are valid.
4430 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004431 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004432
4433 // For an explicitly defaulted or deleted special member, we defer
4434 // determining triviality until the class is complete. That time is now!
4435 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004436 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004437 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004438 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004439
4440 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004441 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004442 }
4443 }
4444 }
4445 }
4446
4447 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4448 // function that is not a constructor declares that member function to be
4449 // const. [...] The class of which that function is a member shall be
4450 // a literal type.
4451 //
4452 // If the class has virtual bases, any constexpr members will already have
4453 // been diagnosed by the checks performed on the member declaration, so
4454 // suppress this (less useful) diagnostic.
4455 //
4456 // We delay this until we know whether an explicitly-defaulted (or deleted)
4457 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004458 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004459 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004460 for (const auto *M : Record->methods()) {
4461 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004462 switch (Record->getTemplateSpecializationKind()) {
4463 case TSK_ImplicitInstantiation:
4464 case TSK_ExplicitInstantiationDeclaration:
4465 case TSK_ExplicitInstantiationDefinition:
4466 // If a template instantiates to a non-literal type, but its members
4467 // instantiate to constexpr functions, the template is technically
4468 // ill-formed, but we allow it for sanity.
4469 continue;
4470
4471 case TSK_Undeclared:
4472 case TSK_ExplicitSpecialization:
4473 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4474 diag::err_constexpr_method_non_literal);
4475 break;
4476 }
4477
4478 // Only produce one error per class.
4479 break;
4480 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004481 }
4482 }
Sebastian Redl08905022011-02-05 19:23:19 +00004483
John McCall95833f32014-02-27 20:30:49 +00004484 // ms_struct is a request to use the same ABI rules as MSVC. Check
4485 // whether this class uses any C++ features that are implemented
4486 // completely differently in MSVC, and if so, emit a diagnostic.
4487 // That diagnostic defaults to an error, but we allow projects to
4488 // map it down to a warning (or ignore it). It's a fairly common
4489 // practice among users of the ms_struct pragma to mass-annotate
4490 // headers, sweeping up a bunch of types that the project doesn't
4491 // really rely on MSVC-compatible layout for. We must therefore
4492 // support "ms_struct except for C++ stuff" as a secondary ABI.
4493 if (Record->isMsStruct(Context) &&
4494 (Record->isPolymorphic() || Record->getNumBases())) {
4495 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004496 }
4497
Richard Smithc2bc61b2013-03-18 21:12:30 +00004498 // Declare inheriting constructors. We do this eagerly here because:
4499 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004500 // constructors from different classes.
4501 // - The lazy declaration of the other implicit constructors is so as to not
4502 // waste space and performance on classes that are not meant to be
4503 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004504 // have inheriting constructors.
4505 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004506}
4507
Richard Smith41c35d62013-11-27 03:39:20 +00004508/// Look up the special member function that would be called by a special
4509/// member function for a subobject of class type.
4510///
4511/// \param Class The class type of the subobject.
4512/// \param CSM The kind of special member function.
4513/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4514/// \param ConstRHS True if this is a copy operation with a const object
4515/// on its RHS, that is, if the argument to the outer special member
4516/// function is 'const' and this is not a field marked 'mutable'.
4517static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4518 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4519 unsigned FieldQuals, bool ConstRHS) {
4520 unsigned LHSQuals = 0;
4521 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4522 LHSQuals = FieldQuals;
4523
4524 unsigned RHSQuals = FieldQuals;
4525 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4526 RHSQuals = 0;
4527 else if (ConstRHS)
4528 RHSQuals |= Qualifiers::Const;
4529
4530 return S.LookupSpecialMember(Class, CSM,
4531 RHSQuals & Qualifiers::Const,
4532 RHSQuals & Qualifiers::Volatile,
4533 false,
4534 LHSQuals & Qualifiers::Const,
4535 LHSQuals & Qualifiers::Volatile);
4536}
4537
Richard Smithb5800092012-06-10 05:43:50 +00004538/// Is the special member function which would be selected to perform the
4539/// specified operation on the specified class type a constexpr constructor?
4540static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4541 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004542 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004543 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004544 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004545 if (!SMOR || !SMOR->getMethod())
4546 // A constructor we wouldn't select can't be "involved in initializing"
4547 // anything.
4548 return true;
4549 return SMOR->getMethod()->isConstexpr();
4550}
4551
4552/// Determine whether the specified special member function would be constexpr
4553/// if it were implicitly defined.
4554static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4555 Sema::CXXSpecialMember CSM,
4556 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004557 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004558 return false;
4559
4560 // C++11 [dcl.constexpr]p4:
4561 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004562 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004563 switch (CSM) {
4564 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004565 // Since default constructor lookup is essentially trivial (and cannot
4566 // involve, for instance, template instantiation), we compute whether a
4567 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4568 //
4569 // This is important for performance; we need to know whether the default
4570 // constructor is constexpr to determine whether the type is a literal type.
4571 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4572
Richard Smithb5800092012-06-10 05:43:50 +00004573 case Sema::CXXCopyConstructor:
4574 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004575 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004576 break;
4577
4578 case Sema::CXXCopyAssignment:
4579 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004580 if (!S.getLangOpts().CPlusPlus1y)
4581 return false;
4582 // In C++1y, we need to perform overload resolution.
4583 Ctor = false;
4584 break;
4585
Richard Smithb5800092012-06-10 05:43:50 +00004586 case Sema::CXXDestructor:
4587 case Sema::CXXInvalid:
4588 return false;
4589 }
4590
4591 // -- if the class is a non-empty union, or for each non-empty anonymous
4592 // union member of a non-union class, exactly one non-static data member
4593 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004594 //
4595 // If we squint, this is guaranteed, since exactly one non-static data member
4596 // will be initialized (if the constructor isn't deleted), we just don't know
4597 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004598 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004599 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004600
4601 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004602 if (Ctor && ClassDecl->getNumVBases())
4603 return false;
4604
4605 // C++1y [class.copy]p26:
4606 // -- [the class] is a literal type, and
4607 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004608 return false;
4609
4610 // -- every constructor involved in initializing [...] base class
4611 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004612 // -- the assignment operator selected to copy/move each direct base
4613 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004614 for (const auto &B : ClassDecl->bases()) {
4615 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004616 if (!BaseType) continue;
4617
4618 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004619 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004620 return false;
4621 }
4622
4623 // -- every constructor involved in initializing non-static data members
4624 // [...] shall be a constexpr constructor;
4625 // -- every non-static data member and base class sub-object shall be
4626 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004627 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004628 // thereof), the assignment operator selected to copy/move that member is
4629 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004630 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004631 if (F->isInvalidDecl())
4632 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004633 QualType BaseType = S.Context.getBaseElementType(F->getType());
4634 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004635 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004636 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4637 BaseType.getCVRQualifiers(),
4638 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004639 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004640 }
4641 }
4642
4643 // All OK, it's constexpr!
4644 return true;
4645}
4646
Richard Smithd3b5c9082012-07-27 04:22:15 +00004647static Sema::ImplicitExceptionSpecification
4648computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4649 switch (S.getSpecialMember(MD)) {
4650 case Sema::CXXDefaultConstructor:
4651 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4652 case Sema::CXXCopyConstructor:
4653 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4654 case Sema::CXXCopyAssignment:
4655 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4656 case Sema::CXXMoveConstructor:
4657 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4658 case Sema::CXXMoveAssignment:
4659 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4660 case Sema::CXXDestructor:
4661 return S.ComputeDefaultedDtorExceptionSpec(MD);
4662 case Sema::CXXInvalid:
4663 break;
4664 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004665 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4666 "only special members have implicit exception specs");
4667 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004668}
4669
Reid Kleckner78af0702013-08-27 23:08:25 +00004670static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4671 CXXMethodDecl *MD) {
4672 FunctionProtoType::ExtProtoInfo EPI;
4673
4674 // Build an exception specification pointing back at this member.
4675 EPI.ExceptionSpecType = EST_Unevaluated;
4676 EPI.ExceptionSpecDecl = MD;
4677
4678 // Set the calling convention to the default for C++ instance methods.
4679 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4680 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4681 /*IsCXXMethod=*/true));
4682 return EPI;
4683}
4684
Richard Smithd3b5c9082012-07-27 04:22:15 +00004685void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4686 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4687 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4688 return;
4689
Richard Smith7f782272012-07-30 23:48:14 +00004690 // Evaluate the exception specification.
4691 ImplicitExceptionSpecification ExceptSpec =
4692 computeImplicitExceptionSpec(*this, Loc, MD);
4693
Richard Smith564417a2014-03-20 21:47:22 +00004694 FunctionProtoType::ExtProtoInfo EPI;
4695 ExceptSpec.getEPI(EPI);
4696
Richard Smith7f782272012-07-30 23:48:14 +00004697 // Update the type of the special member to use it.
Richard Smith564417a2014-03-20 21:47:22 +00004698 UpdateExceptionSpec(MD, EPI);
Richard Smith7f782272012-07-30 23:48:14 +00004699
4700 // A user-provided destructor can be defined outside the class. When that
4701 // happens, be sure to update the exception specification on both
4702 // declarations.
4703 const FunctionProtoType *CanonicalFPT =
4704 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4705 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith564417a2014-03-20 21:47:22 +00004706 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004707}
4708
Richard Smithb9e90b12012-05-15 04:39:51 +00004709void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4710 CXXRecordDecl *RD = MD->getParent();
4711 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004712
Richard Smithb9e90b12012-05-15 04:39:51 +00004713 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4714 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004715
4716 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004717 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004718 bool First = MD == MD->getCanonicalDecl();
4719
4720 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004721
4722 // C++11 [dcl.fct.def.default]p1:
4723 // A function that is explicitly defaulted shall
4724 // -- be a special member function (checked elsewhere),
4725 // -- have the same type (except for ref-qualifiers, and except that a
4726 // copy operation can take a non-const reference) as an implicit
4727 // declaration, and
4728 // -- not have default arguments.
4729 unsigned ExpectedParams = 1;
4730 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4731 ExpectedParams = 0;
4732 if (MD->getNumParams() != ExpectedParams) {
4733 // This also checks for default arguments: a copy or move constructor with a
4734 // default argument is classified as a default constructor, and assignment
4735 // operations and destructors can't have default arguments.
4736 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4737 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004738 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004739 } else if (MD->isVariadic()) {
4740 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4741 << CSM << MD->getSourceRange();
4742 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004743 }
4744
Richard Smithb9e90b12012-05-15 04:39:51 +00004745 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004746
Richard Smithb5800092012-06-10 05:43:50 +00004747 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004748 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004749 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004750 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004751 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004752
Richard Smithb9e90b12012-05-15 04:39:51 +00004753 QualType ReturnType = Context.VoidTy;
4754 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4755 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004756 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004757 QualType ExpectedReturnType =
4758 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4759 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4760 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4761 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4762 HadError = true;
4763 }
4764
4765 // A defaulted special member cannot have cv-qualifiers.
4766 if (Type->getTypeQuals()) {
4767 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004768 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004769 HadError = true;
4770 }
4771 }
4772
4773 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004774 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004775 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004776 if (ExpectedParams && ArgType->isReferenceType()) {
4777 // Argument must be reference to possibly-const T.
4778 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004779 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004780
4781 if (ReferentType.isVolatileQualified()) {
4782 Diag(MD->getLocation(),
4783 diag::err_defaulted_special_member_volatile_param) << CSM;
4784 HadError = true;
4785 }
4786
Richard Smithb5800092012-06-10 05:43:50 +00004787 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004788 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4789 Diag(MD->getLocation(),
4790 diag::err_defaulted_special_member_copy_const_param)
4791 << (CSM == CXXCopyAssignment);
4792 // FIXME: Explain why this special member can't be const.
4793 } else {
4794 Diag(MD->getLocation(),
4795 diag::err_defaulted_special_member_move_const_param)
4796 << (CSM == CXXMoveAssignment);
4797 }
4798 HadError = true;
4799 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004800 } else if (ExpectedParams) {
4801 // A copy assignment operator can take its argument by value, but a
4802 // defaulted one cannot.
4803 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004804 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004805 HadError = true;
4806 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004807
Richard Smithcc36f692011-12-22 02:22:31 +00004808 // C++11 [dcl.fct.def.default]p2:
4809 // An explicitly-defaulted function may be declared constexpr only if it
4810 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004811 // Do not apply this rule to members of class templates, since core issue 1358
4812 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004813 // functions which cannot be constexpr (for non-constructors in C++11 and for
4814 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004815 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4816 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004817 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4818 : isa<CXXConstructorDecl>(MD)) &&
4819 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004820 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4821 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004822 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004823 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004824 }
Richard Smithbd305122012-12-11 01:14:52 +00004825
Richard Smithcc36f692011-12-22 02:22:31 +00004826 // and may have an explicit exception-specification only if it is compatible
4827 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004828 if (Type->hasExceptionSpec()) {
4829 // Delay the check if this is the first declaration of the special member,
4830 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004831 if (First) {
4832 // If the exception specification needs to be instantiated, do so now,
4833 // before we clobber it with an EST_Unevaluated specification below.
4834 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4835 InstantiateExceptionSpec(MD->getLocStart(), MD);
4836 Type = MD->getType()->getAs<FunctionProtoType>();
4837 }
Richard Smithbd305122012-12-11 01:14:52 +00004838 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004839 } else
Richard Smithbd305122012-12-11 01:14:52 +00004840 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4841 }
Richard Smithcc36f692011-12-22 02:22:31 +00004842
4843 // If a function is explicitly defaulted on its first declaration,
4844 if (First) {
4845 // -- it is implicitly considered to be constexpr if the implicit
4846 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004847 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004848
Richard Smithb9e90b12012-05-15 04:39:51 +00004849 // -- it is implicitly considered to have the same exception-specification
4850 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004851 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4852 EPI.ExceptionSpecType = EST_Unevaluated;
4853 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004854 MD->setType(Context.getFunctionType(ReturnType,
4855 ArrayRef<QualType>(&ArgType,
4856 ExpectedParams),
4857 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004858 }
4859
Richard Smithb9e90b12012-05-15 04:39:51 +00004860 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004861 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004862 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004863 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004864 // C++11 [dcl.fct.def.default]p4:
4865 // [For a] user-provided explicitly-defaulted function [...] if such a
4866 // function is implicitly defined as deleted, the program is ill-formed.
4867 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00004868 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00004869 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004870 }
4871 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004872
Richard Smithb9e90b12012-05-15 04:39:51 +00004873 if (HadError)
4874 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004875}
4876
Richard Smithbd305122012-12-11 01:14:52 +00004877/// Check whether the exception specification provided for an
4878/// explicitly-defaulted special member matches the exception specification
4879/// that would have been generated for an implicit special member, per
4880/// C++11 [dcl.fct.def.default]p2.
4881void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4882 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4883 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004884 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4885 /*IsCXXMethod=*/true);
4886 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004887 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4888 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004889 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004890
4891 // Ensure that it matches.
4892 CheckEquivalentExceptionSpec(
4893 PDiag(diag::err_incorrect_defaulted_exception_spec)
4894 << getSpecialMember(MD), PDiag(),
4895 ImplicitType, SourceLocation(),
4896 SpecifiedType, MD->getLocation());
4897}
4898
Alp Tokerae3a9442013-10-18 05:54:19 +00004899void Sema::CheckDelayedMemberExceptionSpecs() {
4900 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4901 2> Checks;
4902 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00004903
Alp Tokerae3a9442013-10-18 05:54:19 +00004904 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4905 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4906
4907 // Perform any deferred checking of exception specifications for virtual
4908 // destructors.
4909 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4910 const CXXDestructorDecl *Dtor = Checks[i].first;
4911 assert(!Dtor->getParent()->isDependentType() &&
4912 "Should not ever add destructors of templates into the list.");
4913 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4914 }
4915
4916 // Check that any explicitly-defaulted methods have exception specifications
4917 // compatible with their implicit exception specifications.
4918 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4919 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4920 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00004921}
4922
Richard Smithd951a1d2012-02-18 02:02:13 +00004923namespace {
4924struct SpecialMemberDeletionInfo {
4925 Sema &S;
4926 CXXMethodDecl *MD;
4927 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004928 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004929
4930 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00004931 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00004932 SourceLocation Loc;
4933
4934 bool AllFieldsAreConst;
4935
4936 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004937 Sema::CXXSpecialMember CSM, bool Diagnose)
4938 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004939 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00004940 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00004941 AllFieldsAreConst(true) {
4942 switch (CSM) {
4943 case Sema::CXXDefaultConstructor:
4944 case Sema::CXXCopyConstructor:
4945 IsConstructor = true;
4946 break;
4947 case Sema::CXXMoveConstructor:
4948 IsConstructor = true;
4949 IsMove = true;
4950 break;
4951 case Sema::CXXCopyAssignment:
4952 IsAssignment = true;
4953 break;
4954 case Sema::CXXMoveAssignment:
4955 IsAssignment = true;
4956 IsMove = true;
4957 break;
4958 case Sema::CXXDestructor:
4959 break;
4960 case Sema::CXXInvalid:
4961 llvm_unreachable("invalid special member kind");
4962 }
4963
4964 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00004965 if (const ReferenceType *RT =
4966 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
4967 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00004968 }
4969 }
4970
4971 bool inUnion() const { return MD->getParent()->isUnion(); }
4972
4973 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00004974 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00004975 unsigned Quals, bool IsMutable) {
4976 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
4977 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00004978 }
4979
Richard Smith852265f2012-03-30 20:53:28 +00004980 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00004981
Richard Smith852265f2012-03-30 20:53:28 +00004982 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00004983 bool shouldDeleteForField(FieldDecl *FD);
4984 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00004985
Richard Smithaf136f82012-07-18 03:51:16 +00004986 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4987 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00004988 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4989 Sema::SpecialMemberOverloadResult *SMOR,
4990 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00004991
4992 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00004993};
4994}
4995
John McCalld4274212012-04-09 20:53:23 +00004996/// Is the given special member inaccessible when used on the given
4997/// sub-object.
4998bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4999 CXXMethodDecl *target) {
5000 /// If we're operating on a base class, the object type is the
5001 /// type of this special member.
5002 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005003 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005004 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5005 objectTy = S.Context.getTypeDeclType(MD->getParent());
5006 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5007
5008 // If we're operating on a field, the object type is the type of the field.
5009 } else {
5010 objectTy = S.Context.getTypeDeclType(target->getParent());
5011 }
5012
5013 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5014}
5015
Richard Smith852265f2012-03-30 20:53:28 +00005016/// Check whether we should delete a special member due to the implicit
5017/// definition containing a call to a special member of a subobject.
5018bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5019 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5020 bool IsDtorCallInCtor) {
5021 CXXMethodDecl *Decl = SMOR->getMethod();
5022 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5023
5024 int DiagKind = -1;
5025
5026 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5027 DiagKind = !Decl ? 0 : 1;
5028 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5029 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005030 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005031 DiagKind = 3;
5032 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5033 !Decl->isTrivial()) {
5034 // A member of a union must have a trivial corresponding special member.
5035 // As a weird special case, a destructor call from a union's constructor
5036 // must be accessible and non-deleted, but need not be trivial. Such a
5037 // destructor is never actually called, but is semantically checked as
5038 // if it were.
5039 DiagKind = 4;
5040 }
5041
5042 if (DiagKind == -1)
5043 return false;
5044
5045 if (Diagnose) {
5046 if (Field) {
5047 S.Diag(Field->getLocation(),
5048 diag::note_deleted_special_member_class_subobject)
5049 << CSM << MD->getParent() << /*IsField*/true
5050 << Field << DiagKind << IsDtorCallInCtor;
5051 } else {
5052 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5053 S.Diag(Base->getLocStart(),
5054 diag::note_deleted_special_member_class_subobject)
5055 << CSM << MD->getParent() << /*IsField*/false
5056 << Base->getType() << DiagKind << IsDtorCallInCtor;
5057 }
5058
5059 if (DiagKind == 1)
5060 S.NoteDeletedFunction(Decl);
5061 // FIXME: Explain inaccessibility if DiagKind == 3.
5062 }
5063
5064 return true;
5065}
5066
Richard Smith921bd202012-02-26 09:11:52 +00005067/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005068/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005069bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005070 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005071 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005072 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005073
5074 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005075 // -- any direct or virtual base class, or non-static data member with no
5076 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005077 // either M has no default constructor or overload resolution as applied
5078 // to M's default constructor results in an ambiguity or in a function
5079 // that is deleted or inaccessible
5080 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5081 // -- a direct or virtual base class B that cannot be copied/moved because
5082 // overload resolution, as applied to B's corresponding special member,
5083 // results in an ambiguity or a function that is deleted or inaccessible
5084 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005085 // C++11 [class.dtor]p5:
5086 // -- any direct or virtual base class [...] has a type with a destructor
5087 // that is deleted or inaccessible
5088 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005089 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005090 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5091 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005092 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005093
Richard Smith852265f2012-03-30 20:53:28 +00005094 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5095 // -- any direct or virtual base class or non-static data member has a
5096 // type with a destructor that is deleted or inaccessible
5097 if (IsConstructor) {
5098 Sema::SpecialMemberOverloadResult *SMOR =
5099 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5100 false, false, false, false, false);
5101 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5102 return true;
5103 }
5104
Richard Smith921bd202012-02-26 09:11:52 +00005105 return false;
5106}
5107
5108/// Check whether we should delete a special member function due to the class
5109/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005110bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005111 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005112 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005113}
5114
5115/// Check whether we should delete a special member function due to the class
5116/// having a particular non-static data member.
5117bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5118 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5119 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5120
5121 if (CSM == Sema::CXXDefaultConstructor) {
5122 // For a default constructor, all references must be initialized in-class
5123 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005124 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5125 if (Diagnose)
5126 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5127 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005128 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005129 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005130 // C++11 [class.ctor]p5: any non-variant non-static data member of
5131 // const-qualified type (or array thereof) with no
5132 // brace-or-equal-initializer does not have a user-provided default
5133 // constructor.
5134 if (!inUnion() && FieldType.isConstQualified() &&
5135 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005136 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5137 if (Diagnose)
5138 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005139 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005140 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005141 }
5142
5143 if (inUnion() && !FieldType.isConstQualified())
5144 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005145 } else if (CSM == Sema::CXXCopyConstructor) {
5146 // For a copy constructor, data members must not be of rvalue reference
5147 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005148 if (FieldType->isRValueReferenceType()) {
5149 if (Diagnose)
5150 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5151 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005152 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005153 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005154 } else if (IsAssignment) {
5155 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005156 if (FieldType->isReferenceType()) {
5157 if (Diagnose)
5158 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5159 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005160 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005161 }
5162 if (!FieldRecord && FieldType.isConstQualified()) {
5163 // C++11 [class.copy]p23:
5164 // -- a non-static data member of const non-class type (or array thereof)
5165 if (Diagnose)
5166 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005167 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005168 return true;
5169 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005170 }
5171
5172 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005173 // Some additional restrictions exist on the variant members.
5174 if (!inUnion() && FieldRecord->isUnion() &&
5175 FieldRecord->isAnonymousStructOrUnion()) {
5176 bool AllVariantFieldsAreConst = true;
5177
Richard Smith5704fe82012-03-29 19:00:10 +00005178 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005179 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005180 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005181
5182 if (!UnionFieldType.isConstQualified())
5183 AllVariantFieldsAreConst = false;
5184
Richard Smith921bd202012-02-26 09:11:52 +00005185 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5186 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005187 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005188 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005189 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005190 }
5191
5192 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005193 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005194 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005195 if (Diagnose)
5196 S.Diag(FieldRecord->getLocation(),
5197 diag::note_deleted_default_ctor_all_const)
5198 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005199 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005200 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005201
Richard Smith5704fe82012-03-29 19:00:10 +00005202 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005203 // This is technically non-conformant, but sanity demands it.
5204 return false;
5205 }
5206
Richard Smithaf136f82012-07-18 03:51:16 +00005207 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5208 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005209 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005210 }
5211
5212 return false;
5213}
5214
5215/// C++11 [class.ctor] p5:
5216/// A defaulted default constructor for a class X is defined as deleted if
5217/// X is a union and all of its variant members are of const-qualified type.
5218bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005219 // This is a silly definition, because it gives an empty union a deleted
5220 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005221 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005222 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005223 if (Diagnose)
5224 S.Diag(MD->getParent()->getLocation(),
5225 diag::note_deleted_default_ctor_all_const)
5226 << MD->getParent() << /*not anonymous union*/0;
5227 return true;
5228 }
5229 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005230}
5231
5232/// Determine whether a defaulted special member function should be defined as
5233/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5234/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005235bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5236 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005237 if (MD->isInvalidDecl())
5238 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005239 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005240 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005241 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005242 return false;
5243
Richard Smithd951a1d2012-02-18 02:02:13 +00005244 // C++11 [expr.lambda.prim]p19:
5245 // The closure type associated with a lambda-expression has a
5246 // deleted (8.4.3) default constructor and a deleted copy
5247 // assignment operator.
5248 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005249 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5250 if (Diagnose)
5251 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005252 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005253 }
5254
Richard Smith6f1e2c62012-04-02 20:59:25 +00005255 // For an anonymous struct or union, the copy and assignment special members
5256 // will never be used, so skip the check. For an anonymous union declared at
5257 // namespace scope, the constructor and destructor are used.
5258 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5259 RD->isAnonymousStructOrUnion())
5260 return false;
5261
Richard Smith852265f2012-03-30 20:53:28 +00005262 // C++11 [class.copy]p7, p18:
5263 // If the class definition declares a move constructor or move assignment
5264 // operator, an implicitly declared copy constructor or copy assignment
5265 // operator is defined as deleted.
5266 if (MD->isImplicit() &&
5267 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5268 CXXMethodDecl *UserDeclaredMove = 0;
5269
5270 // In Microsoft mode, a user-declared move only causes the deletion of the
5271 // corresponding copy operation, not both copy operations.
5272 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005273 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005274 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005275
5276 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005277 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005278 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005279 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005280 break;
5281 }
5282 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005283 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005284 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005285 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005286 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005287
5288 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005289 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005290 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005291 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005292 break;
5293 }
5294 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005295 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005296 }
5297
5298 if (UserDeclaredMove) {
5299 Diag(UserDeclaredMove->getLocation(),
5300 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005301 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005302 << UserDeclaredMove->isMoveAssignmentOperator();
5303 return true;
5304 }
5305 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005306
Richard Smith6f1e2c62012-04-02 20:59:25 +00005307 // Do access control from the special member function
5308 ContextRAII MethodContext(*this, MD);
5309
Richard Smith921bd202012-02-26 09:11:52 +00005310 // C++11 [class.dtor]p5:
5311 // -- for a virtual destructor, lookup of the non-array deallocation function
5312 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005313 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005314 FunctionDecl *OperatorDelete = 0;
5315 DeclarationName Name =
5316 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5317 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005318 OperatorDelete, false)) {
5319 if (Diagnose)
5320 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005321 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005322 }
Richard Smith921bd202012-02-26 09:11:52 +00005323 }
5324
Richard Smith852265f2012-03-30 20:53:28 +00005325 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005326
Aaron Ballman574705e2014-03-13 15:41:46 +00005327 for (auto &BI : RD->bases())
5328 if (!BI.isVirtual() &&
5329 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005330 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005331
Richard Smithd1627032013-07-22 18:06:23 +00005332 // Per DR1611, do not consider virtual bases of constructors of abstract
5333 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005334 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005335 for (auto &BI : RD->vbases())
5336 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005337 return true;
5338 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005339
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005340 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005341 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005342 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005343 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005344
Richard Smithd951a1d2012-02-18 02:02:13 +00005345 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005346 return true;
5347
5348 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005349}
5350
Richard Smith92f241f2012-12-08 02:53:02 +00005351/// Perform lookup for a special member of the specified kind, and determine
5352/// whether it is trivial. If the triviality can be determined without the
5353/// lookup, skip it. This is intended for use when determining whether a
5354/// special member of a containing object is trivial, and thus does not ever
5355/// perform overload resolution for default constructors.
5356///
5357/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5358/// member that was most likely to be intended to be trivial, if any.
5359static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5360 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005361 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005362 if (Selected)
5363 *Selected = 0;
5364
5365 switch (CSM) {
5366 case Sema::CXXInvalid:
5367 llvm_unreachable("not a special member");
5368
5369 case Sema::CXXDefaultConstructor:
5370 // C++11 [class.ctor]p5:
5371 // A default constructor is trivial if:
5372 // - all the [direct subobjects] have trivial default constructors
5373 //
5374 // Note, no overload resolution is performed in this case.
5375 if (RD->hasTrivialDefaultConstructor())
5376 return true;
5377
5378 if (Selected) {
5379 // If there's a default constructor which could have been trivial, dig it
5380 // out. Otherwise, if there's any user-provided default constructor, point
5381 // to that as an example of why there's not a trivial one.
5382 CXXConstructorDecl *DefCtor = 0;
5383 if (RD->needsImplicitDefaultConstructor())
5384 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005385 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005386 if (!CI->isDefaultConstructor())
5387 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005388 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005389 if (!DefCtor->isUserProvided())
5390 break;
5391 }
5392
5393 *Selected = DefCtor;
5394 }
5395
5396 return false;
5397
5398 case Sema::CXXDestructor:
5399 // C++11 [class.dtor]p5:
5400 // A destructor is trivial if:
5401 // - all the direct [subobjects] have trivial destructors
5402 if (RD->hasTrivialDestructor())
5403 return true;
5404
5405 if (Selected) {
5406 if (RD->needsImplicitDestructor())
5407 S.DeclareImplicitDestructor(RD);
5408 *Selected = RD->getDestructor();
5409 }
5410
5411 return false;
5412
5413 case Sema::CXXCopyConstructor:
5414 // C++11 [class.copy]p12:
5415 // A copy constructor is trivial if:
5416 // - the constructor selected to copy each direct [subobject] is trivial
5417 if (RD->hasTrivialCopyConstructor()) {
5418 if (Quals == Qualifiers::Const)
5419 // We must either select the trivial copy constructor or reach an
5420 // ambiguity; no need to actually perform overload resolution.
5421 return true;
5422 } else if (!Selected) {
5423 return false;
5424 }
5425 // In C++98, we are not supposed to perform overload resolution here, but we
5426 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5427 // cases like B as having a non-trivial copy constructor:
5428 // struct A { template<typename T> A(T&); };
5429 // struct B { mutable A a; };
5430 goto NeedOverloadResolution;
5431
5432 case Sema::CXXCopyAssignment:
5433 // C++11 [class.copy]p25:
5434 // A copy assignment operator is trivial if:
5435 // - the assignment operator selected to copy each direct [subobject] is
5436 // trivial
5437 if (RD->hasTrivialCopyAssignment()) {
5438 if (Quals == Qualifiers::Const)
5439 return true;
5440 } else if (!Selected) {
5441 return false;
5442 }
5443 // In C++98, we are not supposed to perform overload resolution here, but we
5444 // treat that as a language defect.
5445 goto NeedOverloadResolution;
5446
5447 case Sema::CXXMoveConstructor:
5448 case Sema::CXXMoveAssignment:
5449 NeedOverloadResolution:
5450 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005451 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005452
5453 // The standard doesn't describe how to behave if the lookup is ambiguous.
5454 // We treat it as not making the member non-trivial, just like the standard
5455 // mandates for the default constructor. This should rarely matter, because
5456 // the member will also be deleted.
5457 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5458 return true;
5459
5460 if (!SMOR->getMethod()) {
5461 assert(SMOR->getKind() ==
5462 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5463 return false;
5464 }
5465
5466 // We deliberately don't check if we found a deleted special member. We're
5467 // not supposed to!
5468 if (Selected)
5469 *Selected = SMOR->getMethod();
5470 return SMOR->getMethod()->isTrivial();
5471 }
5472
5473 llvm_unreachable("unknown special method kind");
5474}
5475
Benjamin Kramer3e350262013-02-15 12:30:38 +00005476static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005477 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005478 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005479 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005480
5481 // Look for constructor templates.
5482 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5483 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5484 if (CXXConstructorDecl *CD =
5485 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5486 return CD;
5487 }
5488
5489 return 0;
5490}
5491
5492/// The kind of subobject we are checking for triviality. The values of this
5493/// enumeration are used in diagnostics.
5494enum TrivialSubobjectKind {
5495 /// The subobject is a base class.
5496 TSK_BaseClass,
5497 /// The subobject is a non-static data member.
5498 TSK_Field,
5499 /// The object is actually the complete object.
5500 TSK_CompleteObject
5501};
5502
5503/// Check whether the special member selected for a given type would be trivial.
5504static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005505 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005506 Sema::CXXSpecialMember CSM,
5507 TrivialSubobjectKind Kind,
5508 bool Diagnose) {
5509 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5510 if (!SubRD)
5511 return true;
5512
5513 CXXMethodDecl *Selected;
5514 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Richard Smith41c35d62013-11-27 03:39:20 +00005515 ConstRHS, Diagnose ? &Selected : 0))
Richard Smith92f241f2012-12-08 02:53:02 +00005516 return true;
5517
5518 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005519 if (ConstRHS)
5520 SubType.addConst();
5521
Richard Smith92f241f2012-12-08 02:53:02 +00005522 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5523 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5524 << Kind << SubType.getUnqualifiedType();
5525 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5526 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5527 } else if (!Selected)
5528 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5529 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5530 else if (Selected->isUserProvided()) {
5531 if (Kind == TSK_CompleteObject)
5532 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5533 << Kind << SubType.getUnqualifiedType() << CSM;
5534 else {
5535 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5536 << Kind << SubType.getUnqualifiedType() << CSM;
5537 S.Diag(Selected->getLocation(), diag::note_declared_at);
5538 }
5539 } else {
5540 if (Kind != TSK_CompleteObject)
5541 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5542 << Kind << SubType.getUnqualifiedType() << CSM;
5543
5544 // Explain why the defaulted or deleted special member isn't trivial.
5545 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5546 }
5547 }
5548
5549 return false;
5550}
5551
5552/// Check whether the members of a class type allow a special member to be
5553/// trivial.
5554static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5555 Sema::CXXSpecialMember CSM,
5556 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005557 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005558 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5559 continue;
5560
5561 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5562
5563 // Pretend anonymous struct or union members are members of this class.
5564 if (FI->isAnonymousStructOrUnion()) {
5565 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5566 CSM, ConstArg, Diagnose))
5567 return false;
5568 continue;
5569 }
5570
5571 // C++11 [class.ctor]p5:
5572 // A default constructor is trivial if [...]
5573 // -- no non-static data member of its class has a
5574 // brace-or-equal-initializer
5575 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5576 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005577 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005578 return false;
5579 }
5580
5581 // Objective C ARC 4.3.5:
5582 // [...] nontrivally ownership-qualified types are [...] not trivially
5583 // default constructible, copy constructible, move constructible, copy
5584 // assignable, move assignable, or destructible [...]
5585 if (S.getLangOpts().ObjCAutoRefCount &&
5586 FieldType.hasNonTrivialObjCLifetime()) {
5587 if (Diagnose)
5588 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5589 << RD << FieldType.getObjCLifetime();
5590 return false;
5591 }
5592
Richard Smith41c35d62013-11-27 03:39:20 +00005593 bool ConstRHS = ConstArg && !FI->isMutable();
5594 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5595 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005596 return false;
5597 }
5598
5599 return true;
5600}
5601
5602/// Diagnose why the specified class does not have a trivial special member of
5603/// the given kind.
5604void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5605 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005606
Richard Smith41c35d62013-11-27 03:39:20 +00005607 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5608 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005609 TSK_CompleteObject, /*Diagnose*/true);
5610}
5611
5612/// Determine whether a defaulted or deleted special member function is trivial,
5613/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5614/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5615bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5616 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005617 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5618
5619 CXXRecordDecl *RD = MD->getParent();
5620
5621 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005622
Richard Smith2002bfe2013-11-04 02:02:27 +00005623 // C++11 [class.copy]p12, p25: [DR1593]
5624 // A [special member] is trivial if [...] its parameter-type-list is
5625 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005626 switch (CSM) {
5627 case CXXDefaultConstructor:
5628 case CXXDestructor:
5629 // Trivial default constructors and destructors cannot have parameters.
5630 break;
5631
5632 case CXXCopyConstructor:
5633 case CXXCopyAssignment: {
5634 // Trivial copy operations always have const, non-volatile parameter types.
5635 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005636 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005637 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5638 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5639 if (Diagnose)
5640 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5641 << Param0->getSourceRange() << Param0->getType()
5642 << Context.getLValueReferenceType(
5643 Context.getRecordType(RD).withConst());
5644 return false;
5645 }
5646 break;
5647 }
5648
5649 case CXXMoveConstructor:
5650 case CXXMoveAssignment: {
5651 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005652 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005653 const RValueReferenceType *RT =
5654 Param0->getType()->getAs<RValueReferenceType>();
5655 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5656 if (Diagnose)
5657 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5658 << Param0->getSourceRange() << Param0->getType()
5659 << Context.getRValueReferenceType(Context.getRecordType(RD));
5660 return false;
5661 }
5662 break;
5663 }
5664
5665 case CXXInvalid:
5666 llvm_unreachable("not a special member");
5667 }
5668
Richard Smith92f241f2012-12-08 02:53:02 +00005669 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5670 if (Diagnose)
5671 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5672 diag::note_nontrivial_default_arg)
5673 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5674 return false;
5675 }
5676 if (MD->isVariadic()) {
5677 if (Diagnose)
5678 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5679 return false;
5680 }
5681
5682 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5683 // A copy/move [constructor or assignment operator] is trivial if
5684 // -- the [member] selected to copy/move each direct base class subobject
5685 // is trivial
5686 //
5687 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5688 // A [default constructor or destructor] is trivial if
5689 // -- all the direct base classes have trivial [default constructors or
5690 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005691 for (const auto &BI : RD->bases())
5692 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005693 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005694 return false;
5695
5696 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5697 // A copy/move [constructor or assignment operator] for a class X is
5698 // trivial if
5699 // -- for each non-static data member of X that is of class type (or array
5700 // thereof), the constructor selected to copy/move that member is
5701 // trivial
5702 //
5703 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5704 // A [default constructor or destructor] is trivial if
5705 // -- for all of the non-static data members of its class that are of class
5706 // type (or array thereof), each such class has a trivial [default
5707 // constructor or destructor]
5708 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5709 return false;
5710
5711 // C++11 [class.dtor]p5:
5712 // A destructor is trivial if [...]
5713 // -- the destructor is not virtual
5714 if (CSM == CXXDestructor && MD->isVirtual()) {
5715 if (Diagnose)
5716 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5717 return false;
5718 }
5719
5720 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5721 // A [special member] for class X is trivial if [...]
5722 // -- class X has no virtual functions and no virtual base classes
5723 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5724 if (!Diagnose)
5725 return false;
5726
5727 if (RD->getNumVBases()) {
5728 // Check for virtual bases. We already know that the corresponding
5729 // member in all bases is trivial, so vbases must all be direct.
5730 CXXBaseSpecifier &BS = *RD->vbases_begin();
5731 assert(BS.isVirtual());
5732 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5733 return false;
5734 }
5735
5736 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005737 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005738 if (MI->isVirtual()) {
5739 SourceLocation MLoc = MI->getLocStart();
5740 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5741 return false;
5742 }
5743 }
5744
5745 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5746 }
5747
5748 // Looks like it's trivial!
5749 return true;
5750}
5751
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005752/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005753namespace {
5754 struct FindHiddenVirtualMethodData {
5755 Sema *S;
5756 CXXMethodDecl *Method;
5757 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005758 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005759 };
5760}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005761
David Blaikie282c92a2012-10-19 00:53:08 +00005762/// \brief Check whether any most overriden method from MD in Methods
5763static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5764 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5765 if (MD->size_overridden_methods() == 0)
5766 return Methods.count(MD->getCanonicalDecl());
5767 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5768 E = MD->end_overridden_methods();
5769 I != E; ++I)
5770 if (CheckMostOverridenMethods(*I, Methods))
5771 return true;
5772 return false;
5773}
5774
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005775/// \brief Member lookup function that determines whether a given C++
5776/// method overloads virtual methods in a base class without overriding any,
5777/// to be used with CXXRecordDecl::lookupInBases().
5778static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5779 CXXBasePath &Path,
5780 void *UserData) {
5781 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5782
5783 FindHiddenVirtualMethodData &Data
5784 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5785
5786 DeclarationName Name = Data.Method->getDeclName();
5787 assert(Name.getNameKind() == DeclarationName::Identifier);
5788
5789 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005790 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005791 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005792 !Path.Decls.empty();
5793 Path.Decls = Path.Decls.slice(1)) {
5794 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005795 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005796 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005797 foundSameNameMethod = true;
5798 // Interested only in hidden virtual methods.
5799 if (!MD->isVirtual())
5800 continue;
5801 // If the method we are checking overrides a method from its base
5802 // don't warn about the other overloaded methods.
5803 if (!Data.S->IsOverload(Data.Method, MD, false))
5804 return true;
5805 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005806 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005807 overloadedMethods.push_back(MD);
5808 }
5809 }
5810
5811 if (foundSameNameMethod)
5812 Data.OverloadedMethods.append(overloadedMethods.begin(),
5813 overloadedMethods.end());
5814 return foundSameNameMethod;
5815}
5816
David Blaikie282c92a2012-10-19 00:53:08 +00005817/// \brief Add the most overriden methods from MD to Methods
5818static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5819 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5820 if (MD->size_overridden_methods() == 0)
5821 Methods.insert(MD->getCanonicalDecl());
5822 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5823 E = MD->end_overridden_methods();
5824 I != E; ++I)
5825 AddMostOverridenMethods(*I, Methods);
5826}
5827
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005828/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005829/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005830void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5831 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005832 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005833 return;
5834
5835 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5836 /*bool RecordPaths=*/false,
5837 /*bool DetectVirtual=*/false);
5838 FindHiddenVirtualMethodData Data;
5839 Data.Method = MD;
5840 Data.S = this;
5841
5842 // Keep the base methods that were overriden or introduced in the subclass
5843 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005844 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005845 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5846 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5847 NamedDecl *ND = *I;
5848 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005849 ND = shad->getTargetDecl();
5850 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5851 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005852 }
5853
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005854 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5855 OverloadedMethods = Data.OverloadedMethods;
5856}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005857
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005858void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5859 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5860 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5861 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5862 PartialDiagnostic PD = PDiag(
5863 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5864 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5865 Diag(overloadedMD->getLocation(), PD);
5866 }
5867}
5868
5869/// \brief Diagnose methods which overload virtual methods in a base class
5870/// without overriding any.
5871void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5872 if (MD->isInvalidDecl())
5873 return;
5874
5875 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5876 MD->getLocation()) == DiagnosticsEngine::Ignored)
5877 return;
5878
5879 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5880 FindHiddenVirtualMethods(MD, OverloadedMethods);
5881 if (!OverloadedMethods.empty()) {
5882 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5883 << MD << (OverloadedMethods.size() > 1);
5884
5885 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005886 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005887}
5888
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005889void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005890 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005891 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005892 SourceLocation RBrac,
5893 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005894 if (!TagDecl)
5895 return;
Mike Stump11289f42009-09-09 15:08:12 +00005896
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005897 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005898
Rafael Espindola06e1b132012-07-12 04:32:30 +00005899 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5900 if (l->getKind() != AttributeList::AT_Visibility)
5901 continue;
5902 l->setInvalid();
5903 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5904 l->getName();
5905 }
5906
David Blaikie751c5582011-09-22 02:58:26 +00005907 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005908 // strict aliasing violation!
5909 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005910 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005911
Douglas Gregor0be31a22010-07-02 17:43:08 +00005912 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005913 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005914}
5915
Douglas Gregor05379422008-11-03 17:51:48 +00005916/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5917/// special functions, such as the default constructor, copy
5918/// constructor, or destructor, to the given C++ class (C++
5919/// [special]p1). This routine can only be executed just before the
5920/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005921void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005922 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005923 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005924
Richard Smith6b02d462012-12-08 08:32:28 +00005925 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005926 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005927
Richard Smith6b02d462012-12-08 08:32:28 +00005928 // If the properties or semantics of the copy constructor couldn't be
5929 // determined while the class was being declared, force a declaration
5930 // of it now.
5931 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5932 DeclareImplicitCopyConstructor(ClassDecl);
5933 }
5934
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005935 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005936 ++ASTContext::NumImplicitMoveConstructors;
5937
Richard Smith6b02d462012-12-08 08:32:28 +00005938 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5939 DeclareImplicitMoveConstructor(ClassDecl);
5940 }
5941
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005942 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5943 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00005944
5945 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005946 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00005947 // it shows up in the right place in the vtable and that we diagnose
5948 // problems with the implicit exception specification.
5949 if (ClassDecl->isDynamicClass() ||
5950 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005951 DeclareImplicitCopyAssignment(ClassDecl);
5952 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005953
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005954 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005955 ++ASTContext::NumImplicitMoveAssignmentOperators;
5956
5957 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00005958 if (ClassDecl->isDynamicClass() ||
5959 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00005960 DeclareImplicitMoveAssignment(ClassDecl);
5961 }
5962
Douglas Gregor7454c562010-07-02 20:37:36 +00005963 if (!ClassDecl->hasUserDeclaredDestructor()) {
5964 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00005965
5966 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00005967 // have to declare the destructor immediately. This ensures that, e.g., it
5968 // shows up in the right place in the vtable and that we diagnose problems
5969 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00005970 if (ClassDecl->isDynamicClass() ||
5971 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00005972 DeclareImplicitDestructor(ClassDecl);
5973 }
Douglas Gregor05379422008-11-03 17:51:48 +00005974}
5975
Francois Pichet1c229c02011-04-22 22:18:13 +00005976void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5977 if (!D)
5978 return;
5979
5980 int NumParamList = D->getNumTemplateParameterLists();
5981 for (int i = 0; i < NumParamList; i++) {
5982 TemplateParameterList* Params = D->getTemplateParameterList(i);
5983 for (TemplateParameterList::iterator Param = Params->begin(),
5984 ParamEnd = Params->end();
5985 Param != ParamEnd; ++Param) {
5986 NamedDecl *Named = cast<NamedDecl>(*Param);
5987 if (Named->getDeclName()) {
5988 S->AddDecl(Named);
5989 IdResolver.AddDecl(Named);
5990 }
5991 }
5992 }
5993}
5994
John McCall48871652010-08-21 09:40:31 +00005995void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00005996 if (!D)
5997 return;
5998
5999 TemplateParameterList *Params = 0;
6000 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
6001 Params = Template->getTemplateParameters();
6002 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6003 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6004 Params = PartialSpec->getTemplateParameters();
6005 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006006 return;
6007
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006008 for (TemplateParameterList::iterator Param = Params->begin(),
6009 ParamEnd = Params->end();
6010 Param != ParamEnd; ++Param) {
6011 NamedDecl *Named = cast<NamedDecl>(*Param);
6012 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00006013 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006014 IdResolver.AddDecl(Named);
6015 }
6016 }
6017}
6018
John McCall48871652010-08-21 09:40:31 +00006019void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006020 if (!RecordD) return;
6021 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006022 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006023 PushDeclContext(S, Record);
6024}
6025
John McCall48871652010-08-21 09:40:31 +00006026void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006027 if (!RecordD) return;
6028 PopDeclContext();
6029}
6030
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006031/// This is used to implement the constant expression evaluation part of the
6032/// attribute enable_if extension. There is nothing in standard C++ which would
6033/// require reentering parameters.
6034void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6035 if (!Param)
6036 return;
6037
6038 S->AddDecl(Param);
6039 if (Param->getDeclName())
6040 IdResolver.AddDecl(Param);
6041}
6042
Douglas Gregor4d87df52008-12-16 21:30:33 +00006043/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6044/// parsing a top-level (non-nested) C++ class, and we are now
6045/// parsing those parts of the given Method declaration that could
6046/// not be parsed earlier (C++ [class.mem]p2), such as default
6047/// arguments. This action should enter the scope of the given
6048/// Method declaration as if we had just parsed the qualified method
6049/// name. However, it should not bring the parameters into scope;
6050/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006051void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006052}
6053
6054/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6055/// C++ method declaration. We're (re-)introducing the given
6056/// function parameter into scope for use in parsing later parts of
6057/// the method declaration. For example, we could see an
6058/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006059void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006060 if (!ParamD)
6061 return;
Mike Stump11289f42009-09-09 15:08:12 +00006062
John McCall48871652010-08-21 09:40:31 +00006063 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006064
6065 // If this parameter has an unparsed default argument, clear it out
6066 // to make way for the parsed default argument.
6067 if (Param->hasUnparsedDefaultArg())
6068 Param->setDefaultArg(0);
6069
John McCall48871652010-08-21 09:40:31 +00006070 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006071 if (Param->getDeclName())
6072 IdResolver.AddDecl(Param);
6073}
6074
6075/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6076/// processing the delayed method declaration for Method. The method
6077/// declaration is now considered finished. There may be a separate
6078/// ActOnStartOfFunctionDef action later (not necessarily
6079/// immediately!) for this method, if it was also defined inside the
6080/// class body.
John McCall48871652010-08-21 09:40:31 +00006081void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006082 if (!MethodD)
6083 return;
Mike Stump11289f42009-09-09 15:08:12 +00006084
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006085 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006086
John McCall48871652010-08-21 09:40:31 +00006087 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006088
6089 // Now that we have our default arguments, check the constructor
6090 // again. It could produce additional diagnostics or affect whether
6091 // the class has implicitly-declared destructors, among other
6092 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006093 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6094 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006095
6096 // Check the default arguments, which we may have added.
6097 if (!Method->isInvalidDecl())
6098 CheckCXXDefaultArguments(Method);
6099}
6100
Douglas Gregor831c93f2008-11-05 20:51:48 +00006101/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006102/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006103/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006104/// emit diagnostics and set the invalid bit to true. In any case, the type
6105/// will be updated to reflect a well-formed type for the constructor and
6106/// returned.
6107QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006108 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006109 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006110
6111 // C++ [class.ctor]p3:
6112 // A constructor shall not be virtual (10.3) or static (9.4). A
6113 // constructor can be invoked for a const, volatile or const
6114 // volatile object. A constructor shall not be declared const,
6115 // volatile, or const volatile (9.3.2).
6116 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006117 if (!D.isInvalidType())
6118 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6119 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6120 << SourceRange(D.getIdentifierLoc());
6121 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006122 }
John McCall8e7d6562010-08-26 03:08:43 +00006123 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006124 if (!D.isInvalidType())
6125 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6126 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6127 << SourceRange(D.getIdentifierLoc());
6128 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006129 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006130 }
Mike Stump11289f42009-09-09 15:08:12 +00006131
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006132 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006133 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006134 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006135 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6136 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006137 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006138 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6139 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006140 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006141 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6142 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006143 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006144 }
Mike Stump11289f42009-09-09 15:08:12 +00006145
Douglas Gregordb9d6642011-01-26 05:01:58 +00006146 // C++0x [class.ctor]p4:
6147 // A constructor shall not be declared with a ref-qualifier.
6148 if (FTI.hasRefQualifier()) {
6149 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6150 << FTI.RefQualifierIsLValueRef
6151 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6152 D.setInvalidType();
6153 }
6154
Douglas Gregor831c93f2008-11-05 20:51:48 +00006155 // Rebuild the function type "R" without any type qualifiers (in
6156 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006157 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006158 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006159 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006160 return R;
6161
6162 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6163 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006164 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006165
6166 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006167}
6168
Douglas Gregor4d87df52008-12-16 21:30:33 +00006169/// CheckConstructor - Checks a fully-formed constructor for
6170/// well-formedness, issuing any diagnostics required. Returns true if
6171/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006172void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006173 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006174 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6175 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006176 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006177
6178 // C++ [class.copy]p3:
6179 // A declaration of a constructor for a class X is ill-formed if
6180 // its first parameter is of type (optionally cv-qualified) X and
6181 // either there are no other parameters or else all other
6182 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006183 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006184 ((Constructor->getNumParams() == 1) ||
6185 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006186 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6187 Constructor->getTemplateSpecializationKind()
6188 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006189 QualType ParamType = Constructor->getParamDecl(0)->getType();
6190 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6191 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006192 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006193 const char *ConstRef
6194 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6195 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006196 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006197 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006198
6199 // FIXME: Rather that making the constructor invalid, we should endeavor
6200 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006201 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006202 }
6203 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006204}
6205
John McCalldeb646e2010-08-04 01:04:25 +00006206/// CheckDestructor - Checks a fully-formed destructor definition for
6207/// well-formedness, issuing any diagnostics required. Returns true
6208/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006209bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006210 CXXRecordDecl *RD = Destructor->getParent();
6211
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006212 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006213 SourceLocation Loc;
6214
6215 if (!Destructor->isImplicit())
6216 Loc = Destructor->getLocation();
6217 else
6218 Loc = RD->getLocation();
6219
6220 // If we have a virtual destructor, look up the deallocation function
6221 FunctionDecl *OperatorDelete = 0;
6222 DeclarationName Name =
6223 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006224 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006225 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006226 // If there's no class-specific operator delete, look up the global
6227 // non-array delete.
6228 if (!OperatorDelete)
6229 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006230
Eli Friedmanfa0df832012-02-02 03:46:19 +00006231 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006232
6233 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006234 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006235
6236 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006237}
6238
Mike Stump11289f42009-09-09 15:08:12 +00006239static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00006240FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
Alp Tokerc5350722014-02-26 22:27:52 +00006241 return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6242 FTI.Params[0].Param &&
6243 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00006244}
6245
Douglas Gregor831c93f2008-11-05 20:51:48 +00006246/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6247/// the well-formednes of the destructor declarator @p D with type @p
6248/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006249/// emit diagnostics and set the declarator to invalid. Even if this happens,
6250/// will be updated to reflect a well-formed type for the destructor and
6251/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006252QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006253 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006254 // C++ [class.dtor]p1:
6255 // [...] A typedef-name that names a class is a class-name
6256 // (7.1.3); however, a typedef-name that names a class shall not
6257 // be used as the identifier in the declarator for a destructor
6258 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006259 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006260 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006261 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006262 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006263 else if (const TemplateSpecializationType *TST =
6264 DeclaratorType->getAs<TemplateSpecializationType>())
6265 if (TST->isTypeAlias())
6266 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6267 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006268
6269 // C++ [class.dtor]p2:
6270 // A destructor is used to destroy objects of its class type. A
6271 // destructor takes no parameters, and no return type can be
6272 // specified for it (not even void). The address of a destructor
6273 // shall not be taken. A destructor shall not be static. A
6274 // destructor can be invoked for a const, volatile or const
6275 // volatile object. A destructor shall not be declared const,
6276 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006277 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006278 if (!D.isInvalidType())
6279 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6280 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006281 << SourceRange(D.getIdentifierLoc())
6282 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6283
John McCall8e7d6562010-08-26 03:08:43 +00006284 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006285 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006286 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006287 // Destructors don't have return types, but the parser will
6288 // happily parse something like:
6289 //
6290 // class X {
6291 // float ~X();
6292 // };
6293 //
6294 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006295 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6296 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6297 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006298 }
Mike Stump11289f42009-09-09 15:08:12 +00006299
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006300 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006301 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006302 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006303 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6304 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006305 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006306 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6307 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006308 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006309 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6310 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006311 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006312 }
6313
Douglas Gregordb9d6642011-01-26 05:01:58 +00006314 // C++0x [class.dtor]p2:
6315 // A destructor shall not be declared with a ref-qualifier.
6316 if (FTI.hasRefQualifier()) {
6317 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6318 << FTI.RefQualifierIsLValueRef
6319 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6320 D.setInvalidType();
6321 }
6322
Douglas Gregor831c93f2008-11-05 20:51:48 +00006323 // Make sure we don't have any parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006324 if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006325 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6326
6327 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006328 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006329 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006330 }
6331
Mike Stump11289f42009-09-09 15:08:12 +00006332 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006333 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006334 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006335 D.setInvalidType();
6336 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006337
6338 // Rebuild the function type "R" without any type qualifiers or
6339 // parameters (in case any of the errors above fired) and with
6340 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006341 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006342 if (!D.isInvalidType())
6343 return R;
6344
Douglas Gregor95755162010-07-01 05:10:53 +00006345 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006346 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6347 EPI.Variadic = false;
6348 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006349 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006350 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006351}
6352
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006353/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6354/// well-formednes of the conversion function declarator @p D with
6355/// type @p R. If there are any errors in the declarator, this routine
6356/// will emit diagnostics and return true. Otherwise, it will return
6357/// false. Either way, the type @p R will be updated to reflect a
6358/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006359void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006360 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006361 // C++ [class.conv.fct]p1:
6362 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006363 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006364 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006365 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006366 if (!D.isInvalidType())
6367 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006368 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6369 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006370 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006371 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006372 }
John McCall212fa2e2010-04-13 00:04:31 +00006373
6374 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6375
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006376 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006377 // Conversion functions don't have return types, but the parser will
6378 // happily parse something like:
6379 //
6380 // class X {
6381 // float operator bool();
6382 // };
6383 //
6384 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006385 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6386 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6387 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006388 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006389 }
6390
John McCall212fa2e2010-04-13 00:04:31 +00006391 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6392
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006393 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006394 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006395 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6396
6397 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006398 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006399 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006400 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006401 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006402 D.setInvalidType();
6403 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006404
John McCall212fa2e2010-04-13 00:04:31 +00006405 // Diagnose "&operator bool()" and other such nonsense. This
6406 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006407 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006408 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006409 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006410 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006411 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006412 }
6413
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006414 // C++ [class.conv.fct]p4:
6415 // The conversion-type-id shall not represent a function type nor
6416 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006417 if (ConvType->isArrayType()) {
6418 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6419 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006420 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006421 } else if (ConvType->isFunctionType()) {
6422 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6423 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006424 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006425 }
6426
6427 // Rebuild the function type "R" without any parameters (in case any
6428 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006429 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006430 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006431 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006432
Douglas Gregor5fb53972009-01-14 15:45:31 +00006433 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006434 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006435 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006436 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006437 diag::warn_cxx98_compat_explicit_conversion_functions :
6438 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006439 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006440}
6441
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006442/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6443/// the declaration of the given C++ conversion function. This routine
6444/// is responsible for recording the conversion function in the C++
6445/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006446Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006447 assert(Conversion && "Expected to receive a conversion function declaration");
6448
Douglas Gregor4287b372008-12-12 08:25:50 +00006449 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006450
6451 // Make sure we aren't redeclaring the conversion function.
6452 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006453
6454 // C++ [class.conv.fct]p1:
6455 // [...] A conversion function is never used to convert a
6456 // (possibly cv-qualified) object to the (possibly cv-qualified)
6457 // same object type (or a reference to it), to a (possibly
6458 // cv-qualified) base class of that type (or a reference to it),
6459 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006460 // FIXME: Suppress this warning if the conversion function ends up being a
6461 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006462 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006463 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006464 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006465 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006466 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6467 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006468 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006469 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006470 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6471 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006472 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006473 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006474 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006475 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006476 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006477 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006478 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006479 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006480 }
6481
Douglas Gregor457104e2010-09-29 04:25:11 +00006482 if (FunctionTemplateDecl *ConversionTemplate
6483 = Conversion->getDescribedFunctionTemplate())
6484 return ConversionTemplate;
6485
John McCall48871652010-08-21 09:40:31 +00006486 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006487}
6488
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006489//===----------------------------------------------------------------------===//
6490// Namespace Handling
6491//===----------------------------------------------------------------------===//
6492
Richard Smith45bb8852012-10-04 22:13:39 +00006493/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6494/// reopened.
6495static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6496 SourceLocation Loc,
6497 IdentifierInfo *II, bool *IsInline,
6498 NamespaceDecl *PrevNS) {
6499 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006500
Richard Smithf501cc32012-10-05 01:46:25 +00006501 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6502 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6503 // inline namespaces, with the intention of bringing names into namespace std.
6504 //
6505 // We support this just well enough to get that case working; this is not
6506 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006507 if (*IsInline && II && II->getName().startswith("__atomic") &&
6508 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006509 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006510 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6511 NS = NS->getPreviousDecl())
6512 NS->setInline(*IsInline);
6513 // Patch up the lookup table for the containing namespace. This isn't really
6514 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006515 for (auto *I : PrevNS->decls())
6516 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006517 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6518 return;
6519 }
6520
6521 if (PrevNS->isInline())
6522 // The user probably just forgot the 'inline', so suggest that it
6523 // be added back.
6524 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6525 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6526 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006527 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006528
6529 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6530 *IsInline = PrevNS->isInline();
6531}
John McCallb1be5232010-08-26 09:15:37 +00006532
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006533/// ActOnStartNamespaceDef - This is called at the start of a namespace
6534/// definition.
John McCall48871652010-08-21 09:40:31 +00006535Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006536 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006537 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006538 SourceLocation IdentLoc,
6539 IdentifierInfo *II,
6540 SourceLocation LBrace,
6541 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006542 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6543 // For anonymous namespace, take the location of the left brace.
6544 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006545 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006546 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006547 bool IsStd = false;
6548 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006549 Scope *DeclRegionScope = NamespcScope->getParent();
6550
Douglas Gregore57e7522012-01-07 09:11:48 +00006551 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006552 if (II) {
6553 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006554 // The identifier in an original-namespace-definition shall not
6555 // have been previously defined in the declarative region in
6556 // which the original-namespace-definition appears. The
6557 // identifier in an original-namespace-definition is the name of
6558 // the namespace. Subsequently in that declarative region, it is
6559 // treated as an original-namespace-name.
6560 //
6561 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006562 // look through using directives, just look for any ordinary names.
6563
6564 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006565 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6566 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006567 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006568 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6569 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6570 ++I) {
6571 if ((*I)->getIdentifierNamespace() & IDNS) {
6572 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006573 break;
6574 }
6575 }
6576
Douglas Gregore57e7522012-01-07 09:11:48 +00006577 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6578
6579 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006580 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006581 if (IsInline != PrevNS->isInline())
6582 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6583 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006584 } else if (PrevDecl) {
6585 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006586 Diag(Loc, diag::err_redefinition_different_kind)
6587 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006588 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006589 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006590 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006591 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006592 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006593 // This is the first "real" definition of the namespace "std", so update
6594 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006595 PrevNS = getStdNamespace();
6596 IsStd = true;
6597 AddToKnown = !IsInline;
6598 } else {
6599 // We've seen this namespace for the first time.
6600 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006601 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006602 } else {
John McCall4fa53422009-10-01 00:25:31 +00006603 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006604
6605 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006606 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006607 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006608 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006609 } else {
6610 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006611 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006612 }
6613
Richard Smith45bb8852012-10-04 22:13:39 +00006614 if (PrevNS && IsInline != PrevNS->isInline())
6615 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6616 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006617 }
6618
6619 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6620 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006621 if (IsInvalid)
6622 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006623
6624 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006625
Douglas Gregore57e7522012-01-07 09:11:48 +00006626 // FIXME: Should we be merging attributes?
6627 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006628 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006629
6630 if (IsStd)
6631 StdNamespace = Namespc;
6632 if (AddToKnown)
6633 KnownNamespaces[Namespc] = false;
6634
6635 if (II) {
6636 PushOnScopeChains(Namespc, DeclRegionScope);
6637 } else {
6638 // Link the anonymous namespace into its parent.
6639 DeclContext *Parent = CurContext->getRedeclContext();
6640 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6641 TU->setAnonymousNamespace(Namespc);
6642 } else {
6643 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006644 }
John McCall4fa53422009-10-01 00:25:31 +00006645
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006646 CurContext->addDecl(Namespc);
6647
John McCall4fa53422009-10-01 00:25:31 +00006648 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6649 // behaves as if it were replaced by
6650 // namespace unique { /* empty body */ }
6651 // using namespace unique;
6652 // namespace unique { namespace-body }
6653 // where all occurrences of 'unique' in a translation unit are
6654 // replaced by the same identifier and this identifier differs
6655 // from all other identifiers in the entire program.
6656
6657 // We just create the namespace with an empty name and then add an
6658 // implicit using declaration, just like the standard suggests.
6659 //
6660 // CodeGen enforces the "universally unique" aspect by giving all
6661 // declarations semantically contained within an anonymous
6662 // namespace internal linkage.
6663
Douglas Gregore57e7522012-01-07 09:11:48 +00006664 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006665 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006666 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006667 /* 'using' */ LBrace,
6668 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006669 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006670 /* identifier */ SourceLocation(),
6671 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006672 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006673 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006674 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006675 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006676 }
6677
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006678 ActOnDocumentableDecl(Namespc);
6679
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006680 // Although we could have an invalid decl (i.e. the namespace name is a
6681 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006682 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6683 // for the namespace has the declarations that showed up in that particular
6684 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006685 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006686 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006687}
6688
Sebastian Redla6602e92009-11-23 15:34:23 +00006689/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6690/// is a namespace alias, returns the namespace it points to.
6691static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6692 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6693 return AD->getNamespace();
6694 return dyn_cast_or_null<NamespaceDecl>(D);
6695}
6696
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006697/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6698/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006699void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006700 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6701 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006702 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006703 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006704 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006705 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006706}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006707
John McCall28a0cf72010-08-25 07:42:41 +00006708CXXRecordDecl *Sema::getStdBadAlloc() const {
6709 return cast_or_null<CXXRecordDecl>(
6710 StdBadAlloc.get(Context.getExternalSource()));
6711}
6712
6713NamespaceDecl *Sema::getStdNamespace() const {
6714 return cast_or_null<NamespaceDecl>(
6715 StdNamespace.get(Context.getExternalSource()));
6716}
6717
Douglas Gregorcdf87022010-06-29 17:53:46 +00006718/// \brief Retrieve the special "std" namespace, which may require us to
6719/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006720NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006721 if (!StdNamespace) {
6722 // The "std" namespace has not yet been defined, so build one implicitly.
6723 StdNamespace = NamespaceDecl::Create(Context,
6724 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006725 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006726 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006727 &PP.getIdentifierTable().get("std"),
6728 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006729 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006730 }
6731
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006732 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006733}
6734
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006735bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006736 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006737 "Looking for std::initializer_list outside of C++.");
6738
6739 // We're looking for implicit instantiations of
6740 // template <typename E> class std::initializer_list.
6741
6742 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6743 return false;
6744
Sebastian Redl43144e72012-01-17 22:49:58 +00006745 ClassTemplateDecl *Template = 0;
6746 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006747
Sebastian Redl43144e72012-01-17 22:49:58 +00006748 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006749
Sebastian Redl43144e72012-01-17 22:49:58 +00006750 ClassTemplateSpecializationDecl *Specialization =
6751 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6752 if (!Specialization)
6753 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006754
Sebastian Redl43144e72012-01-17 22:49:58 +00006755 Template = Specialization->getSpecializedTemplate();
6756 Arguments = Specialization->getTemplateArgs().data();
6757 } else if (const TemplateSpecializationType *TST =
6758 Ty->getAs<TemplateSpecializationType>()) {
6759 Template = dyn_cast_or_null<ClassTemplateDecl>(
6760 TST->getTemplateName().getAsTemplateDecl());
6761 Arguments = TST->getArgs();
6762 }
6763 if (!Template)
6764 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006765
6766 if (!StdInitializerList) {
6767 // Haven't recognized std::initializer_list yet, maybe this is it.
6768 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6769 if (TemplateClass->getIdentifier() !=
6770 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006771 !getStdNamespace()->InEnclosingNamespaceSetOf(
6772 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006773 return false;
6774 // This is a template called std::initializer_list, but is it the right
6775 // template?
6776 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006777 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006778 return false;
6779 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6780 return false;
6781
6782 // It's the right template.
6783 StdInitializerList = Template;
6784 }
6785
6786 if (Template != StdInitializerList)
6787 return false;
6788
6789 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006790 if (Element)
6791 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006792 return true;
6793}
6794
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006795static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6796 NamespaceDecl *Std = S.getStdNamespace();
6797 if (!Std) {
6798 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6799 return 0;
6800 }
6801
6802 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6803 Loc, Sema::LookupOrdinaryName);
6804 if (!S.LookupQualifiedName(Result, Std)) {
6805 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6806 return 0;
6807 }
6808 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6809 if (!Template) {
6810 Result.suppressDiagnostics();
6811 // We found something weird. Complain about the first thing we found.
6812 NamedDecl *Found = *Result.begin();
6813 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6814 return 0;
6815 }
6816
6817 // We found some template called std::initializer_list. Now verify that it's
6818 // correct.
6819 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006820 if (Params->getMinRequiredArguments() != 1 ||
6821 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006822 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6823 return 0;
6824 }
6825
6826 return Template;
6827}
6828
6829QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6830 if (!StdInitializerList) {
6831 StdInitializerList = LookupStdInitializerList(*this, Loc);
6832 if (!StdInitializerList)
6833 return QualType();
6834 }
6835
6836 TemplateArgumentListInfo Args(Loc, Loc);
6837 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6838 Context.getTrivialTypeSourceInfo(Element,
6839 Loc)));
6840 return Context.getCanonicalType(
6841 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6842}
6843
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006844bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6845 // C++ [dcl.init.list]p2:
6846 // A constructor is an initializer-list constructor if its first parameter
6847 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6848 // std::initializer_list<E> for some type E, and either there are no other
6849 // parameters or else all other parameters have default arguments.
6850 if (Ctor->getNumParams() < 1 ||
6851 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6852 return false;
6853
6854 QualType ArgType = Ctor->getParamDecl(0)->getType();
6855 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6856 ArgType = RT->getPointeeType().getUnqualifiedType();
6857
6858 return isStdInitializerList(ArgType, 0);
6859}
6860
Douglas Gregora172e082011-03-26 22:25:30 +00006861/// \brief Determine whether a using statement is in a context where it will be
6862/// apply in all contexts.
6863static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6864 switch (CurContext->getDeclKind()) {
6865 case Decl::TranslationUnit:
6866 return true;
6867 case Decl::LinkageSpec:
6868 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6869 default:
6870 return false;
6871 }
6872}
6873
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006874namespace {
6875
6876// Callback to only accept typo corrections that are namespaces.
6877class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006878public:
Craig Toppera798a9d2014-03-02 09:32:10 +00006879 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006880 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006881 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006882 return false;
6883 }
6884};
6885
6886}
6887
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006888static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6889 CXXScopeSpec &SS,
6890 SourceLocation IdentLoc,
6891 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006892 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006893 R.clear();
6894 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006895 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00006896 Validator)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006897 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006898 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6899 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006900 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006901 S.diagnoseTypo(Corrected,
6902 S.PDiag(diag::err_using_directive_member_suggest)
6903 << Ident << DC << DroppedSpecifier << SS.getRange(),
6904 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006905 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006906 S.diagnoseTypo(Corrected,
6907 S.PDiag(diag::err_using_directive_suggest) << Ident,
6908 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006909 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006910 R.addDecl(Corrected.getCorrectionDecl());
6911 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006912 }
6913 return false;
6914}
6915
John McCall48871652010-08-21 09:40:31 +00006916Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006917 SourceLocation UsingLoc,
6918 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006919 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006920 SourceLocation IdentLoc,
6921 IdentifierInfo *NamespcName,
6922 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006923 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6924 assert(NamespcName && "Invalid NamespcName.");
6925 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006926
6927 // This can only happen along a recovery path.
6928 while (S->getFlags() & Scope::TemplateParamScope)
6929 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006930 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006931
Douglas Gregor889ceb72009-02-03 19:21:40 +00006932 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006933 NestedNameSpecifier *Qualifier = 0;
6934 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00006935 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006936
Douglas Gregor34074322009-01-14 22:20:51 +00006937 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006938 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6939 LookupParsedName(R, S, &SS);
6940 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006941 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006942
Douglas Gregorcdf87022010-06-29 17:53:46 +00006943 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006944 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006945 // Allow "using namespace std;" or "using namespace ::std;" even if
6946 // "std" hasn't been defined yet, for GCC compatibility.
6947 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6948 NamespcName->isStr("std")) {
6949 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006950 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006951 R.resolveKind();
6952 }
6953 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006954 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006955 }
6956
John McCall9f3059a2009-10-09 21:13:30 +00006957 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006958 NamedDecl *Named = R.getFoundDecl();
6959 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6960 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006961 // C++ [namespace.udir]p1:
6962 // A using-directive specifies that the names in the nominated
6963 // namespace can be used in the scope in which the
6964 // using-directive appears after the using-directive. During
6965 // unqualified name lookup (3.4.1), the names appear as if they
6966 // were declared in the nearest enclosing namespace which
6967 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006968 // namespace. [Note: in this context, "contains" means "contains
6969 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006970
6971 // Find enclosing context containing both using-directive and
6972 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006973 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006974 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6975 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6976 CommonAncestor = CommonAncestor->getParent();
6977
Sebastian Redla6602e92009-11-23 15:34:23 +00006978 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006979 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006980 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006981
Douglas Gregora172e082011-03-26 22:25:30 +00006982 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00006983 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006984 Diag(IdentLoc, diag::warn_using_directive_in_header);
6985 }
6986
Douglas Gregor889ceb72009-02-03 19:21:40 +00006987 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006988 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006989 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006990 }
6991
Richard Smith54ecd982013-02-20 19:22:51 +00006992 if (UDir)
6993 ProcessDeclAttributeList(S, UDir, AttrList);
6994
John McCall48871652010-08-21 09:40:31 +00006995 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00006996}
6997
6998void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00006999 // If the scope has an associated entity and the using directive is at
7000 // namespace or translation unit scope, add the UsingDirectiveDecl into
7001 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007002 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007003 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007004 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007005 else
Richard Smith05afe5e2012-03-13 03:12:56 +00007006 // Otherwise, it is at block sope. The using-directives will affect lookup
7007 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007008 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007009}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007010
Douglas Gregorfec52632009-06-20 00:51:54 +00007011
John McCall48871652010-08-21 09:40:31 +00007012Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007013 AccessSpecifier AS,
7014 bool HasUsingKeyword,
7015 SourceLocation UsingLoc,
7016 CXXScopeSpec &SS,
7017 UnqualifiedId &Name,
7018 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007019 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007020 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007021 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007022
Douglas Gregor220f4272009-11-04 16:30:06 +00007023 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007024 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007025 case UnqualifiedId::IK_Identifier:
7026 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007027 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007028 case UnqualifiedId::IK_ConversionFunctionId:
7029 break;
7030
7031 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007032 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007033 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007034 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007035 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007036 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007037 diag::err_using_decl_constructor)
7038 << SS.getRange();
7039
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007040 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007041
John McCall48871652010-08-21 09:40:31 +00007042 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007043
7044 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007045 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007046 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007047 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007048
7049 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007050 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007051 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00007052 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007053 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007054
7055 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7056 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007057 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00007058 return 0;
John McCall3969e302009-12-08 07:46:18 +00007059
Richard Smithc2bc61b2013-03-18 21:12:30 +00007060 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007061 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007062 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007063 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7064 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007065 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007066 }
7067
Douglas Gregorc4356532010-12-16 00:46:58 +00007068 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7069 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7070 return 0;
7071
John McCall3f746822009-11-17 05:59:44 +00007072 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007073 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007074 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007075 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007076 if (UD)
7077 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007078
John McCall48871652010-08-21 09:40:31 +00007079 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007080}
7081
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007082/// \brief Determine whether a using declaration considers the given
7083/// declarations as "equivalent", e.g., if they are redeclarations of
7084/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007085static bool
7086IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7087 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007088 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007089
Richard Smithdda56e42011-04-15 14:24:37 +00007090 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007091 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007092 return Context.hasSameType(TD1->getUnderlyingType(),
7093 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007094
7095 return false;
7096}
7097
7098
John McCall84d87672009-12-10 09:41:52 +00007099/// Determines whether to create a using shadow decl for a particular
7100/// decl, given the set of decls existing prior to this using lookup.
7101bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007102 const LookupResult &Previous,
7103 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007104 // Diagnose finding a decl which is not from a base class of the
7105 // current class. We do this now because there are cases where this
7106 // function will silently decide not to build a shadow decl, which
7107 // will pre-empt further diagnostics.
7108 //
7109 // We don't need to do this in C++0x because we do the check once on
7110 // the qualifier.
7111 //
7112 // FIXME: diagnose the following if we care enough:
7113 // struct A { int foo; };
7114 // struct B : A { using A::foo; };
7115 // template <class T> struct C : A {};
7116 // template <class T> struct D : C<T> { using B::foo; } // <---
7117 // This is invalid (during instantiation) in C++03 because B::foo
7118 // resolves to the using decl in B, which is not a base class of D<T>.
7119 // We can't diagnose it immediately because C<T> is an unknown
7120 // specialization. The UsingShadowDecl in D<T> then points directly
7121 // to A::foo, which will look well-formed when we instantiate.
7122 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007123 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007124 DeclContext *OrigDC = Orig->getDeclContext();
7125
7126 // Handle enums and anonymous structs.
7127 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7128 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7129 while (OrigRec->isAnonymousStructOrUnion())
7130 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7131
7132 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7133 if (OrigDC == CurContext) {
7134 Diag(Using->getLocation(),
7135 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007136 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007137 Diag(Orig->getLocation(), diag::note_using_decl_target);
7138 return true;
7139 }
7140
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007141 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007142 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007143 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007144 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007145 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007146 Diag(Orig->getLocation(), diag::note_using_decl_target);
7147 return true;
7148 }
7149 }
7150
7151 if (Previous.empty()) return false;
7152
7153 NamedDecl *Target = Orig;
7154 if (isa<UsingShadowDecl>(Target))
7155 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7156
John McCalla17e83e2009-12-11 02:33:26 +00007157 // If the target happens to be one of the previous declarations, we
7158 // don't have a conflict.
7159 //
7160 // FIXME: but we might be increasing its access, in which case we
7161 // should redeclare it.
7162 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithfd8634a2013-10-23 02:17:46 +00007163 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007164 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7165 I != E; ++I) {
7166 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007167 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7168 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7169 PrevShadow = Shadow;
7170 FoundEquivalentDecl = true;
7171 }
John McCalla17e83e2009-12-11 02:33:26 +00007172
7173 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7174 }
7175
Richard Smithfd8634a2013-10-23 02:17:46 +00007176 if (FoundEquivalentDecl)
7177 return false;
7178
Alp Tokera2794f92014-01-22 07:29:52 +00007179 if (FunctionDecl *FD = Target->getAsFunction()) {
John McCall84d87672009-12-10 09:41:52 +00007180 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00007181 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007182 case Ovl_Overload:
7183 return false;
7184
7185 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007186 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007187 break;
Richard Smith18819302014-02-06 01:31:33 +00007188
John McCall84d87672009-12-10 09:41:52 +00007189 // We found a decl with the exact signature.
7190 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007191 // If we're in a record, we want to hide the target, so we
7192 // return true (without a diagnostic) to tell the caller not to
7193 // build a shadow decl.
7194 if (CurContext->isRecord())
7195 return true;
7196
7197 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007198 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007199 break;
7200 }
7201
7202 Diag(Target->getLocation(), diag::note_using_decl_target);
7203 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7204 return true;
7205 }
7206
7207 // Target is not a function.
7208
John McCall84d87672009-12-10 09:41:52 +00007209 if (isa<TagDecl>(Target)) {
7210 // No conflict between a tag and a non-tag.
7211 if (!Tag) return false;
7212
John McCalle29c5cd2009-12-10 19:51:03 +00007213 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007214 Diag(Target->getLocation(), diag::note_using_decl_target);
7215 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7216 return true;
7217 }
7218
7219 // No conflict between a tag and a non-tag.
7220 if (!NonTag) return false;
7221
John McCalle29c5cd2009-12-10 19:51:03 +00007222 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007223 Diag(Target->getLocation(), diag::note_using_decl_target);
7224 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7225 return true;
7226}
7227
John McCall3f746822009-11-17 05:59:44 +00007228/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007229UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007230 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007231 NamedDecl *Orig,
7232 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007233
7234 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007235 NamedDecl *Target = Orig;
7236 if (isa<UsingShadowDecl>(Target)) {
7237 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7238 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007239 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007240
John McCall3f746822009-11-17 05:59:44 +00007241 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007242 = UsingShadowDecl::Create(Context, CurContext,
7243 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007244 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007245
Douglas Gregor457104e2010-09-29 04:25:11 +00007246 Shadow->setAccess(UD->getAccess());
7247 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7248 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007249
7250 Shadow->setPreviousDecl(PrevDecl);
7251
John McCall3f746822009-11-17 05:59:44 +00007252 if (S)
John McCall3969e302009-12-08 07:46:18 +00007253 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007254 else
John McCall3969e302009-12-08 07:46:18 +00007255 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007256
John McCall3969e302009-12-08 07:46:18 +00007257
John McCall84d87672009-12-10 09:41:52 +00007258 return Shadow;
7259}
John McCall3969e302009-12-08 07:46:18 +00007260
John McCall84d87672009-12-10 09:41:52 +00007261/// Hides a using shadow declaration. This is required by the current
7262/// using-decl implementation when a resolvable using declaration in a
7263/// class is followed by a declaration which would hide or override
7264/// one or more of the using decl's targets; for example:
7265///
7266/// struct Base { void foo(int); };
7267/// struct Derived : Base {
7268/// using Base::foo;
7269/// void foo(int);
7270/// };
7271///
7272/// The governing language is C++03 [namespace.udecl]p12:
7273///
7274/// When a using-declaration brings names from a base class into a
7275/// derived class scope, member functions in the derived class
7276/// override and/or hide member functions with the same name and
7277/// parameter types in a base class (rather than conflicting).
7278///
7279/// There are two ways to implement this:
7280/// (1) optimistically create shadow decls when they're not hidden
7281/// by existing declarations, or
7282/// (2) don't create any shadow decls (or at least don't make them
7283/// visible) until we've fully parsed/instantiated the class.
7284/// The problem with (1) is that we might have to retroactively remove
7285/// a shadow decl, which requires several O(n) operations because the
7286/// decl structures are (very reasonably) not designed for removal.
7287/// (2) avoids this but is very fiddly and phase-dependent.
7288void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007289 if (Shadow->getDeclName().getNameKind() ==
7290 DeclarationName::CXXConversionFunctionName)
7291 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7292
John McCall84d87672009-12-10 09:41:52 +00007293 // Remove it from the DeclContext...
7294 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007295
John McCall84d87672009-12-10 09:41:52 +00007296 // ...and the scope, if applicable...
7297 if (S) {
John McCall48871652010-08-21 09:40:31 +00007298 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007299 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007300 }
7301
John McCall84d87672009-12-10 09:41:52 +00007302 // ...and the using decl.
7303 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7304
7305 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007306 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007307}
7308
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007309namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007310class UsingValidatorCCC : public CorrectionCandidateCallback {
7311public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007312 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7313 bool RequireMember)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007314 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007315 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007316
Craig Toppera798a9d2014-03-02 09:32:10 +00007317 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007318 NamedDecl *ND = Candidate.getCorrectionDecl();
7319
7320 // Keywords are not valid here.
7321 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007322 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007323
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007324 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7325 !isa<TypeDecl>(ND))
7326 return false;
7327
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007328 // Completely unqualified names are invalid for a 'using' declaration.
7329 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7330 return false;
7331
7332 if (isa<TypeDecl>(ND))
7333 return HasTypenameKeyword || !IsInstantiation;
7334
7335 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007336 }
7337
7338private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007339 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007340 bool IsInstantiation;
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007341 bool RequireMember;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007342};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007343} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007344
John McCalle61f2ba2009-11-18 02:36:19 +00007345/// Builds a using declaration.
7346///
7347/// \param IsInstantiation - Whether this call arises from an
7348/// instantiation of an unresolved using declaration. We treat
7349/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007350NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7351 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007352 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007353 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007354 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007355 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007356 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007357 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007358 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007359 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007360 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007361
Anders Carlssonf038fc22009-08-28 05:49:21 +00007362 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007363
Anders Carlsson59140b32009-08-28 03:16:11 +00007364 if (SS.isEmpty()) {
7365 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007366 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007367 }
Mike Stump11289f42009-09-09 15:08:12 +00007368
John McCall84d87672009-12-10 09:41:52 +00007369 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007370 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007371 ForRedeclaration);
7372 Previous.setHideTags(false);
7373 if (S) {
7374 LookupName(Previous, S);
7375
7376 // It is really dumb that we have to do this.
7377 LookupResult::Filter F = Previous.makeFilter();
7378 while (F.hasNext()) {
7379 NamedDecl *D = F.next();
7380 if (!isDeclInScope(D, CurContext, S))
7381 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007382 // If we found a local extern declaration that's not ordinarily visible,
7383 // and this declaration is being added to a non-block scope, ignore it.
7384 // We're only checking for scope conflicts here, not also for violations
7385 // of the linkage rules.
7386 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7387 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7388 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007389 }
7390 F.done();
7391 } else {
7392 assert(IsInstantiation && "no scope in non-instantiation");
7393 assert(CurContext->isRecord() && "scope not record in instantiation");
7394 LookupQualifiedName(Previous, CurContext);
7395 }
7396
John McCall84d87672009-12-10 09:41:52 +00007397 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007398 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7399 SS, IdentLoc, Previous))
John McCall84d87672009-12-10 09:41:52 +00007400 return 0;
7401
7402 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007403 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
John McCallb96ec562009-12-04 22:46:56 +00007404 return 0;
7405
John McCall84c16cf2009-11-12 03:15:40 +00007406 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007407 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007408 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007409 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007410 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007411 // FIXME: not all declaration name kinds are legal here
7412 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7413 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007414 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007415 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007416 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007417 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7418 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007419 }
John McCallb96ec562009-12-04 22:46:56 +00007420 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007421 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007422 NameInfo, HasTypenameKeyword);
Anders Carlssonf038fc22009-08-28 05:49:21 +00007423 }
John McCallb96ec562009-12-04 22:46:56 +00007424 D->setAccess(AS);
7425 CurContext->addDecl(D);
7426
7427 if (!LookupContext) return D;
7428 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00007429
John McCall0b66eb32010-05-01 00:40:08 +00007430 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00007431 UD->setInvalidDecl();
7432 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00007433 }
7434
Richard Smith23d55872012-04-02 01:30:27 +00007435 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007436 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith23d55872012-04-02 01:30:27 +00007437 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlc1f8e492011-03-12 13:44:32 +00007438 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007439 return UD;
7440 }
7441
7442 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007443
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007444 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007445
John McCall3969e302009-12-08 07:46:18 +00007446 // Unlike most lookups, we don't always want to hide tag
7447 // declarations: tag names are visible through the using declaration
7448 // even if hidden by ordinary names, *except* in a dependent context
7449 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007450 if (!IsInstantiation)
7451 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007452
John McCall5dadb652012-04-07 03:04:20 +00007453 // For the purposes of this lookup, we have a base object type
7454 // equal to that of the current context.
7455 if (CurContext->isRecord()) {
7456 R.setBaseObjectType(
7457 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7458 }
7459
John McCall27b18f82009-11-17 02:14:36 +00007460 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007461
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007462 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007463 if (R.empty()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007464 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7465 CurContext->isRecord());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007466 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7467 R.getLookupKind(), S, &SS, CCC)){
7468 // We reject any correction for which ND would be NULL.
7469 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007470 R.setLookupName(Corrected.getCorrection());
7471 R.addDecl(ND);
Richard Smithf9b15102013-08-17 00:46:16 +00007472 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007473 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007474 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7475 << NameInfo.getName() << LookupContext << 0
7476 << SS.getRange());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007477 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007478 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007479 << NameInfo.getName() << LookupContext << SS.getRange();
7480 UD->setInvalidDecl();
7481 return UD;
7482 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007483 }
7484
John McCallb96ec562009-12-04 22:46:56 +00007485 if (R.isAmbiguous()) {
7486 UD->setInvalidDecl();
7487 return UD;
7488 }
Mike Stump11289f42009-09-09 15:08:12 +00007489
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007490 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007491 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007492 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007493 Diag(IdentLoc, diag::err_using_typename_non_type);
7494 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7495 Diag((*I)->getUnderlyingDecl()->getLocation(),
7496 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007497 UD->setInvalidDecl();
7498 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007499 }
7500 } else {
7501 // If we asked for a non-typename and we got a type, error out,
7502 // but only if this is an instantiation of an unresolved using
7503 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007504 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007505 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7506 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007507 UD->setInvalidDecl();
7508 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007509 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007510 }
7511
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007512 // C++0x N2914 [namespace.udecl]p6:
7513 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007514 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007515 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7516 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007517 UD->setInvalidDecl();
7518 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007519 }
Mike Stump11289f42009-09-09 15:08:12 +00007520
John McCall84d87672009-12-10 09:41:52 +00007521 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithfd8634a2013-10-23 02:17:46 +00007522 UsingShadowDecl *PrevDecl = 0;
7523 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7524 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007525 }
John McCall3f746822009-11-17 05:59:44 +00007526
7527 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007528}
7529
Sebastian Redl08905022011-02-05 19:23:19 +00007530/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007531bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007532 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007533
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007534 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007535 assert(SourceType &&
7536 "Using decl naming constructor doesn't have type in scope spec.");
7537 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7538
7539 // Check whether the named type is a direct base class.
7540 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7541 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7542 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7543 BaseIt != BaseE; ++BaseIt) {
7544 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7545 if (CanonicalSourceType == BaseType)
7546 break;
Richard Smith23d55872012-04-02 01:30:27 +00007547 if (BaseIt->getType()->isDependentType())
7548 break;
Sebastian Redl08905022011-02-05 19:23:19 +00007549 }
7550
7551 if (BaseIt == BaseE) {
7552 // Did not find SourceType in the bases.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007553 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007554 diag::err_using_decl_constructor_not_in_direct_base)
7555 << UD->getNameInfo().getSourceRange()
7556 << QualType(SourceType, 0) << TargetClass;
7557 return true;
7558 }
7559
Richard Smith23d55872012-04-02 01:30:27 +00007560 if (!CurContext->isDependentContext())
7561 BaseIt->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007562
7563 return false;
7564}
7565
John McCall84d87672009-12-10 09:41:52 +00007566/// Checks that the given using declaration is not an invalid
7567/// redeclaration. Note that this is checking only for the using decl
7568/// itself, not for any ill-formedness among the UsingShadowDecls.
7569bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007570 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007571 const CXXScopeSpec &SS,
7572 SourceLocation NameLoc,
7573 const LookupResult &Prev) {
7574 // C++03 [namespace.udecl]p8:
7575 // C++0x [namespace.udecl]p10:
7576 // A using-declaration is a declaration and can therefore be used
7577 // repeatedly where (and only where) multiple declarations are
7578 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007579 //
John McCall032092f2010-11-29 18:01:58 +00007580 // That's in non-member contexts.
7581 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007582 return false;
7583
Aaron Ballman4a979672014-01-03 13:56:08 +00007584 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007585
7586 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7587 NamedDecl *D = *I;
7588
7589 bool DTypename;
7590 NestedNameSpecifier *DQual;
7591 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007592 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007593 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007594 } else if (UnresolvedUsingValueDecl *UD
7595 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7596 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007597 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007598 } else if (UnresolvedUsingTypenameDecl *UD
7599 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7600 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007601 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007602 } else continue;
7603
7604 // using decls differ if one says 'typename' and the other doesn't.
7605 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007606 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007607
7608 // using decls differ if they name different scopes (but note that
7609 // template instantiation can cause this check to trigger when it
7610 // didn't before instantiation).
7611 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7612 Context.getCanonicalNestedNameSpecifier(DQual))
7613 continue;
7614
7615 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007616 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007617 return true;
7618 }
7619
7620 return false;
7621}
7622
John McCall3969e302009-12-08 07:46:18 +00007623
John McCallb96ec562009-12-04 22:46:56 +00007624/// Checks that the given nested-name qualifier used in a using decl
7625/// in the current context is appropriately related to the current
7626/// scope. If an error is found, diagnoses it and returns true.
7627bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7628 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00007629 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00007630 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007631 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007632
John McCall3969e302009-12-08 07:46:18 +00007633 if (!CurContext->isRecord()) {
7634 // C++03 [namespace.udecl]p3:
7635 // C++0x [namespace.udecl]p8:
7636 // A using-declaration for a class member shall be a member-declaration.
7637
7638 // If we weren't able to compute a valid scope, it must be a
7639 // dependent class scope.
7640 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00007641 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7642 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
7643 RD = 0;
7644
John McCall3969e302009-12-08 07:46:18 +00007645 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7646 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00007647
7648 // If we have a complete, non-dependent source type, try to suggest a
7649 // way to get the same effect.
7650 if (!RD)
7651 return true;
7652
7653 // Find what this using-declaration was referring to.
7654 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7655 R.setHideTags(false);
7656 R.suppressDiagnostics();
7657 LookupQualifiedName(R, RD);
7658
7659 if (R.getAsSingle<TypeDecl>()) {
7660 if (getLangOpts().CPlusPlus11) {
7661 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7662 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7663 << 0 // alias declaration
7664 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7665 NameInfo.getName().getAsString() +
7666 " = ");
7667 } else {
7668 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7669 SourceLocation InsertLoc =
7670 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7671 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7672 << 1 // typedef declaration
7673 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7674 << FixItHint::CreateInsertion(
7675 InsertLoc, " " + NameInfo.getName().getAsString());
7676 }
7677 } else if (R.getAsSingle<VarDecl>()) {
7678 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7679 // repeating the type of the static data member here.
7680 FixItHint FixIt;
7681 if (getLangOpts().CPlusPlus11) {
7682 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7683 FixIt = FixItHint::CreateReplacement(
7684 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7685 }
7686
7687 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7688 << 2 // reference declaration
7689 << FixIt;
7690 }
John McCall3969e302009-12-08 07:46:18 +00007691 return true;
7692 }
7693
7694 // Otherwise, everything is known to be fine.
7695 return false;
7696 }
7697
7698 // The current scope is a record.
7699
7700 // If the named context is dependent, we can't decide much.
7701 if (!NamedContext) {
7702 // FIXME: in C++0x, we can diagnose if we can prove that the
7703 // nested-name-specifier does not refer to a base class, which is
7704 // still possible in some cases.
7705
7706 // Otherwise we have to conservatively report that things might be
7707 // okay.
7708 return false;
7709 }
7710
7711 if (!NamedContext->isRecord()) {
7712 // Ideally this would point at the last name in the specifier,
7713 // but we don't have that level of source info.
7714 Diag(SS.getRange().getBegin(),
7715 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007716 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007717 return true;
7718 }
7719
Douglas Gregor7c842292010-12-21 07:41:49 +00007720 if (!NamedContext->isDependentContext() &&
7721 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7722 return true;
7723
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007724 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007725 // C++0x [namespace.udecl]p3:
7726 // In a using-declaration used as a member-declaration, the
7727 // nested-name-specifier shall name a base class of the class
7728 // being defined.
7729
7730 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7731 cast<CXXRecordDecl>(NamedContext))) {
7732 if (CurContext == NamedContext) {
7733 Diag(NameLoc,
7734 diag::err_using_decl_nested_name_specifier_is_current_class)
7735 << SS.getRange();
7736 return true;
7737 }
7738
7739 Diag(SS.getRange().getBegin(),
7740 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007741 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007742 << cast<CXXRecordDecl>(CurContext)
7743 << SS.getRange();
7744 return true;
7745 }
7746
7747 return false;
7748 }
7749
7750 // C++03 [namespace.udecl]p4:
7751 // A using-declaration used as a member-declaration shall refer
7752 // to a member of a base class of the class being defined [etc.].
7753
7754 // Salient point: SS doesn't have to name a base class as long as
7755 // lookup only finds members from base classes. Therefore we can
7756 // diagnose here only if we can prove that that can't happen,
7757 // i.e. if the class hierarchies provably don't intersect.
7758
7759 // TODO: it would be nice if "definitely valid" results were cached
7760 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7761 // need to be repeated.
7762
7763 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007764 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007765
7766 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7767 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7768 Data->Bases.insert(Base);
7769 return true;
7770 }
7771
7772 bool hasDependentBases(const CXXRecordDecl *Class) {
7773 return !Class->forallBases(collect, this);
7774 }
7775
7776 /// Returns true if the base is dependent or is one of the
7777 /// accumulated base classes.
7778 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7779 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7780 return !Data->Bases.count(Base);
7781 }
7782
7783 bool mightShareBases(const CXXRecordDecl *Class) {
7784 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7785 }
7786 };
7787
7788 UserData Data;
7789
7790 // Returns false if we find a dependent base.
7791 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7792 return false;
7793
7794 // Returns false if the class has a dependent base or if it or one
7795 // of its bases is present in the base set of the current context.
7796 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7797 return false;
7798
7799 Diag(SS.getRange().getBegin(),
7800 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007801 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007802 << cast<CXXRecordDecl>(CurContext)
7803 << SS.getRange();
7804
7805 return true;
John McCallb96ec562009-12-04 22:46:56 +00007806}
7807
Richard Smithdda56e42011-04-15 14:24:37 +00007808Decl *Sema::ActOnAliasDeclaration(Scope *S,
7809 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007810 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007811 SourceLocation UsingLoc,
7812 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007813 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007814 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007815 // Skip up to the relevant declaration scope.
7816 while (S->getFlags() & Scope::TemplateParamScope)
7817 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007818 assert((S->getFlags() & Scope::DeclScope) &&
7819 "got alias-declaration outside of declaration scope");
7820
7821 if (Type.isInvalid())
7822 return 0;
7823
7824 bool Invalid = false;
7825 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7826 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007827 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007828
7829 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7830 return 0;
7831
7832 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007833 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007834 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007835 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7836 TInfo->getTypeLoc().getBeginLoc());
7837 }
Richard Smithdda56e42011-04-15 14:24:37 +00007838
7839 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7840 LookupName(Previous, S);
7841
7842 // Warn about shadowing the name of a template parameter.
7843 if (Previous.isSingleResult() &&
7844 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007845 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007846 Previous.clear();
7847 }
7848
7849 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7850 "name in alias declaration must be an identifier");
7851 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7852 Name.StartLocation,
7853 Name.Identifier, TInfo);
7854
7855 NewTD->setAccess(AS);
7856
7857 if (Invalid)
7858 NewTD->setInvalidDecl();
7859
Richard Smith54ecd982013-02-20 19:22:51 +00007860 ProcessDeclAttributeList(S, NewTD, AttrList);
7861
Richard Smith3f1b5d02011-05-05 21:57:07 +00007862 CheckTypedefForVariablyModifiedType(S, NewTD);
7863 Invalid |= NewTD->isInvalidDecl();
7864
Richard Smithdda56e42011-04-15 14:24:37 +00007865 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007866
7867 NamedDecl *NewND;
7868 if (TemplateParamLists.size()) {
7869 TypeAliasTemplateDecl *OldDecl = 0;
7870 TemplateParameterList *OldTemplateParams = 0;
7871
7872 if (TemplateParamLists.size() != 1) {
7873 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007874 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7875 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007876 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007877 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007878
7879 // Only consider previous declarations in the same scope.
7880 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7881 /*ExplicitInstantiationOrSpecialization*/false);
7882 if (!Previous.empty()) {
7883 Redeclaration = true;
7884
7885 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7886 if (!OldDecl && !Invalid) {
7887 Diag(UsingLoc, diag::err_redefinition_different_kind)
7888 << Name.Identifier;
7889
7890 NamedDecl *OldD = Previous.getRepresentativeDecl();
7891 if (OldD->getLocation().isValid())
7892 Diag(OldD->getLocation(), diag::note_previous_definition);
7893
7894 Invalid = true;
7895 }
7896
7897 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7898 if (TemplateParameterListsAreEqual(TemplateParams,
7899 OldDecl->getTemplateParameters(),
7900 /*Complain=*/true,
7901 TPL_TemplateMatch))
7902 OldTemplateParams = OldDecl->getTemplateParameters();
7903 else
7904 Invalid = true;
7905
7906 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7907 if (!Invalid &&
7908 !Context.hasSameType(OldTD->getUnderlyingType(),
7909 NewTD->getUnderlyingType())) {
7910 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7911 // but we can't reasonably accept it.
7912 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7913 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7914 if (OldTD->getLocation().isValid())
7915 Diag(OldTD->getLocation(), diag::note_previous_definition);
7916 Invalid = true;
7917 }
7918 }
7919 }
7920
7921 // Merge any previous default template arguments into our parameters,
7922 // and check the parameter list.
7923 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7924 TPC_TypeAliasTemplate))
7925 return 0;
7926
7927 TypeAliasTemplateDecl *NewDecl =
7928 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7929 Name.Identifier, TemplateParams,
7930 NewTD);
7931
7932 NewDecl->setAccess(AS);
7933
7934 if (Invalid)
7935 NewDecl->setInvalidDecl();
7936 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00007937 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007938
7939 NewND = NewDecl;
7940 } else {
7941 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7942 NewND = NewTD;
7943 }
Richard Smithdda56e42011-04-15 14:24:37 +00007944
7945 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00007946 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00007947
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00007948 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007949 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00007950}
7951
John McCall48871652010-08-21 09:40:31 +00007952Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007953 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00007954 SourceLocation AliasLoc,
7955 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007956 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007957 SourceLocation IdentLoc,
7958 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00007959
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007960 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007961 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7962 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007963
Anders Carlssondca83c42009-03-28 06:23:46 +00007964 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00007965 NamedDecl *PrevDecl
7966 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7967 ForRedeclaration);
7968 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7969 PrevDecl = 0;
7970
7971 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007972 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00007973 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007974 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00007975 // FIXME: At some point, we'll want to create the (redundant)
7976 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00007977 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00007978 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00007979 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007980 }
Mike Stump11289f42009-09-09 15:08:12 +00007981
Anders Carlssondca83c42009-03-28 06:23:46 +00007982 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7983 diag::err_redefinition_different_kind;
7984 Diag(AliasLoc, DiagID) << Alias;
7985 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007986 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00007987 }
7988
John McCall27b18f82009-11-17 02:14:36 +00007989 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007990 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00007991
John McCall9f3059a2009-10-09 21:13:30 +00007992 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007993 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00007994 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007995 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00007996 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00007997 }
Mike Stump11289f42009-09-09 15:08:12 +00007998
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007999 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008000 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008001 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008002 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008003
John McCalld8d0d432010-02-16 06:53:13 +00008004 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008005 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008006}
8007
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008008Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008009Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8010 CXXMethodDecl *MD) {
8011 CXXRecordDecl *ClassDecl = MD->getParent();
8012
Douglas Gregor6d880b12010-07-01 22:31:05 +00008013 // C++ [except.spec]p14:
8014 // An implicitly declared special member function (Clause 12) shall have an
8015 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008016 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008017 if (ClassDecl->isInvalidDecl())
8018 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008019
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008020 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008021 for (const auto &B : ClassDecl->bases()) {
8022 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008023 continue;
8024
Aaron Ballman574705e2014-03-13 15:41:46 +00008025 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008026 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008027 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8028 // If this is a deleted function, add it anyway. This might be conformant
8029 // with the standard. This might not. I'm not sure. It might not matter.
8030 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008031 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008032 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008033 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008034
8035 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008036 for (const auto &B : ClassDecl->vbases()) {
8037 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008038 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008039 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8040 // If this is a deleted function, add it anyway. This might be conformant
8041 // with the standard. This might not. I'm not sure. It might not matter.
8042 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008043 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008044 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008045 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008046
8047 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008048 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008049 if (F->hasInClassInitializer()) {
8050 if (Expr *E = F->getInClassInitializer())
8051 ExceptSpec.CalledExpr(E);
8052 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008053 // DR1351:
8054 // If the brace-or-equal-initializer of a non-static data member
8055 // invokes a defaulted default constructor of its class or of an
8056 // enclosing class in a potentially evaluated subexpression, the
8057 // program is ill-formed.
8058 //
8059 // This resolution is unworkable: the exception specification of the
8060 // default constructor can be needed in an unevaluated context, in
8061 // particular, in the operand of a noexcept-expression, and we can be
8062 // unable to compute an exception specification for an enclosed class.
8063 //
8064 // We do not allow an in-class initializer to require the evaluation
8065 // of the exception specification for any in-class initializer whose
8066 // definition is not lexically complete.
8067 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008068 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008069 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008070 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8071 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8072 // If this is a deleted function, add it anyway. This might be conformant
8073 // with the standard. This might not. I'm not sure. It might not matter.
8074 // In particular, the problem is that this function never gets called. It
8075 // might just be ill-formed because this function attempts to refer to
8076 // a deleted function here.
8077 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008078 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008079 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008080 }
John McCalldb40c7f2010-12-14 08:05:40 +00008081
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008082 return ExceptSpec;
8083}
8084
Richard Smithc2bc61b2013-03-18 21:12:30 +00008085Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008086Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8087 CXXRecordDecl *ClassDecl = CD->getParent();
8088
8089 // C++ [except.spec]p14:
8090 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008091 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008092 if (ClassDecl->isInvalidDecl())
8093 return ExceptSpec;
8094
8095 // Inherited constructor.
8096 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8097 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8098 // FIXME: Copying or moving the parameters could add extra exceptions to the
8099 // set, as could the default arguments for the inherited constructor. This
8100 // will be addressed when we implement the resolution of core issue 1351.
8101 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8102
8103 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008104 for (const auto &B : ClassDecl->bases()) {
8105 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008106 continue;
8107
Aaron Ballman574705e2014-03-13 15:41:46 +00008108 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008109 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8110 if (BaseClassDecl == InheritedDecl)
8111 continue;
8112 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8113 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008114 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008115 }
8116 }
8117
8118 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008119 for (const auto &B : ClassDecl->vbases()) {
8120 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008121 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8122 if (BaseClassDecl == InheritedDecl)
8123 continue;
8124 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8125 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008126 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008127 }
8128 }
8129
8130 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008131 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008132 if (F->hasInClassInitializer()) {
8133 if (Expr *E = F->getInClassInitializer())
8134 ExceptSpec.CalledExpr(E);
8135 else if (!F->isInvalidDecl())
8136 Diag(CD->getLocation(),
8137 diag::err_in_class_initializer_references_def_ctor) << CD;
8138 } else if (const RecordType *RecordTy
8139 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8140 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8141 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8142 if (Constructor)
8143 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8144 }
8145 }
8146
Richard Smithc2bc61b2013-03-18 21:12:30 +00008147 return ExceptSpec;
8148}
8149
Richard Smith8bf22e52012-11-29 01:34:07 +00008150namespace {
8151/// RAII object to register a special member as being currently declared.
8152struct DeclaringSpecialMember {
8153 Sema &S;
8154 Sema::SpecialMemberDecl D;
8155 bool WasAlreadyBeingDeclared;
8156
8157 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8158 : S(S), D(RD, CSM) {
8159 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8160 if (WasAlreadyBeingDeclared)
8161 // This almost never happens, but if it does, ensure that our cache
8162 // doesn't contain a stale result.
8163 S.SpecialMemberCache.clear();
8164
8165 // FIXME: Register a note to be produced if we encounter an error while
8166 // declaring the special member.
8167 }
8168 ~DeclaringSpecialMember() {
8169 if (!WasAlreadyBeingDeclared)
8170 S.SpecialMembersBeingDeclared.erase(D);
8171 }
8172
8173 /// \brief Are we already trying to declare this special member?
8174 bool isAlreadyBeingDeclared() const {
8175 return WasAlreadyBeingDeclared;
8176 }
8177};
8178}
8179
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008180CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8181 CXXRecordDecl *ClassDecl) {
8182 // C++ [class.ctor]p5:
8183 // A default constructor for a class X is a constructor of class X
8184 // that can be called without an argument. If there is no
8185 // user-declared constructor for class X, a default constructor is
8186 // implicitly declared. An implicitly-declared default constructor
8187 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008188 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008189 "Should not build implicit default constructor!");
8190
Richard Smith8bf22e52012-11-29 01:34:07 +00008191 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8192 if (DSM.isAlreadyBeingDeclared())
8193 return 0;
8194
Richard Smithb5800092012-06-10 05:43:50 +00008195 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8196 CXXDefaultConstructor,
8197 false);
8198
Douglas Gregor6d880b12010-07-01 22:31:05 +00008199 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008200 CanQualType ClassType
8201 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008202 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008203 DeclarationName Name
8204 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008205 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008206 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00008207 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00008208 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00008209 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008210 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008211 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008212 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008213
8214 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008215 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008216 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008217
Richard Smith6b02d462012-12-08 08:32:28 +00008218 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8219 // constructors is easy to compute.
8220 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8221
8222 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008223 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008224
Douglas Gregor9672f922010-07-03 00:47:00 +00008225 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008226 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008227
Douglas Gregor0be31a22010-07-02 17:43:08 +00008228 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008229 PushOnScopeChains(DefaultCon, S, false);
8230 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008231
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008232 return DefaultCon;
8233}
8234
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008235void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8236 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008237 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008238 !Constructor->doesThisDeclarationHaveABody() &&
8239 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008240 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008241
Anders Carlsson423f5d82010-04-23 16:04:08 +00008242 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008243 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008244
Eli Friedmaneaf34142012-10-18 20:14:08 +00008245 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008246 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008247 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008248 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008249 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008250 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008251 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008252 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008253 }
Douglas Gregor73193272010-09-20 16:48:21 +00008254
8255 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008256 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008257
Eli Friedman276dd182013-09-05 00:02:25 +00008258 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008259 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008260
8261 if (ASTMutationListener *L = getASTMutationListener()) {
8262 L->CompletedImplicitDefinition(Constructor);
8263 }
Richard Trieuef64e942013-10-25 00:56:00 +00008264
8265 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008266}
8267
Richard Smith938f40b2011-06-11 17:19:42 +00008268void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008269 // Perform any delayed checks on exception specifications.
8270 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008271}
8272
Richard Smith185be182013-04-10 05:48:59 +00008273namespace {
8274/// Information on inheriting constructors to declare.
8275class InheritingConstructorInfo {
8276public:
8277 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8278 : SemaRef(SemaRef), Derived(Derived) {
8279 // Mark the constructors that we already have in the derived class.
8280 //
8281 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8282 // unless there is a user-declared constructor with the same signature in
8283 // the class where the using-declaration appears.
8284 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8285 }
8286
8287 void inheritAll(CXXRecordDecl *RD) {
8288 visitAll(RD, &InheritingConstructorInfo::inherit);
8289 }
8290
8291private:
8292 /// Information about an inheriting constructor.
8293 struct InheritingConstructor {
8294 InheritingConstructor()
8295 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8296
8297 /// If \c true, a constructor with this signature is already declared
8298 /// in the derived class.
8299 bool DeclaredInDerived;
8300
8301 /// The constructor which is inherited.
8302 const CXXConstructorDecl *BaseCtor;
8303
8304 /// The derived constructor we declared.
8305 CXXConstructorDecl *DerivedCtor;
8306 };
8307
8308 /// Inheriting constructors with a given canonical type. There can be at
8309 /// most one such non-template constructor, and any number of templated
8310 /// constructors.
8311 struct InheritingConstructorsForType {
8312 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008313 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8314 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008315
8316 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8317 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8318 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8319 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8320 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8321 false, S.TPL_TemplateMatch))
8322 return Templates[I].second;
8323 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8324 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008325 }
Richard Smith185be182013-04-10 05:48:59 +00008326
8327 return NonTemplate;
8328 }
8329 };
8330
8331 /// Get or create the inheriting constructor record for a constructor.
8332 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8333 QualType CtorType) {
8334 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8335 .getEntry(SemaRef, Ctor);
8336 }
8337
8338 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8339
8340 /// Process all constructors for a class.
8341 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008342 for (const auto *Ctor : RD->ctors())
8343 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008344 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8345 I(RD->decls_begin()), E(RD->decls_end());
8346 I != E; ++I) {
8347 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8348 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8349 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008350 }
8351 }
Richard Smith185be182013-04-10 05:48:59 +00008352
8353 /// Note that a constructor (or constructor template) was declared in Derived.
8354 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8355 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8356 }
8357
8358 /// Inherit a single constructor.
8359 void inherit(const CXXConstructorDecl *Ctor) {
8360 const FunctionProtoType *CtorType =
8361 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008362 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008363 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8364
8365 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8366
8367 // Core issue (no number yet): the ellipsis is always discarded.
8368 if (EPI.Variadic) {
8369 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8370 SemaRef.Diag(Ctor->getLocation(),
8371 diag::note_using_decl_constructor_ellipsis);
8372 EPI.Variadic = false;
8373 }
8374
8375 // Declare a constructor for each number of parameters.
8376 //
8377 // C++11 [class.inhctor]p1:
8378 // The candidate set of inherited constructors from the class X named in
8379 // the using-declaration consists of [... modulo defects ...] for each
8380 // constructor or constructor template of X, the set of constructors or
8381 // constructor templates that results from omitting any ellipsis parameter
8382 // specification and successively omitting parameters with a default
8383 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008384 unsigned MinParams = minParamsToInherit(Ctor);
8385 unsigned Params = Ctor->getNumParams();
8386 if (Params >= MinParams) {
8387 do
8388 declareCtor(UsingLoc, Ctor,
8389 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008390 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008391 while (Params > MinParams &&
8392 Ctor->getParamDecl(--Params)->hasDefaultArg());
8393 }
Richard Smith185be182013-04-10 05:48:59 +00008394 }
8395
8396 /// Find the using-declaration which specified that we should inherit the
8397 /// constructors of \p Base.
8398 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8399 // No fancy lookup required; just look for the base constructor name
8400 // directly within the derived class.
8401 ASTContext &Context = SemaRef.Context;
8402 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8403 Context.getCanonicalType(Context.getRecordType(Base)));
8404 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8405 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8406 }
8407
8408 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8409 // C++11 [class.inhctor]p3:
8410 // [F]or each constructor template in the candidate set of inherited
8411 // constructors, a constructor template is implicitly declared
8412 if (Ctor->getDescribedFunctionTemplate())
8413 return 0;
8414
8415 // For each non-template constructor in the candidate set of inherited
8416 // constructors other than a constructor having no parameters or a
8417 // copy/move constructor having a single parameter, a constructor is
8418 // implicitly declared [...]
8419 if (Ctor->getNumParams() == 0)
8420 return 1;
8421 if (Ctor->isCopyOrMoveConstructor())
8422 return 2;
8423
8424 // Per discussion on core reflector, never inherit a constructor which
8425 // would become a default, copy, or move constructor of Derived either.
8426 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8427 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8428 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8429 }
8430
8431 /// Declare a single inheriting constructor, inheriting the specified
8432 /// constructor, with the given type.
8433 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8434 QualType DerivedType) {
8435 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8436
8437 // C++11 [class.inhctor]p3:
8438 // ... a constructor is implicitly declared with the same constructor
8439 // characteristics unless there is a user-declared constructor with
8440 // the same signature in the class where the using-declaration appears
8441 if (Entry.DeclaredInDerived)
8442 return;
8443
8444 // C++11 [class.inhctor]p7:
8445 // If two using-declarations declare inheriting constructors with the
8446 // same signature, the program is ill-formed
8447 if (Entry.DerivedCtor) {
8448 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8449 // Only diagnose this once per constructor.
8450 if (Entry.DerivedCtor->isInvalidDecl())
8451 return;
8452 Entry.DerivedCtor->setInvalidDecl();
8453
8454 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8455 SemaRef.Diag(BaseCtor->getLocation(),
8456 diag::note_using_decl_constructor_conflict_current_ctor);
8457 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8458 diag::note_using_decl_constructor_conflict_previous_ctor);
8459 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8460 diag::note_using_decl_constructor_conflict_previous_using);
8461 } else {
8462 // Core issue (no number): if the same inheriting constructor is
8463 // produced by multiple base class constructors from the same base
8464 // class, the inheriting constructor is defined as deleted.
8465 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8466 }
8467
8468 return;
8469 }
8470
8471 ASTContext &Context = SemaRef.Context;
8472 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8473 Context.getCanonicalType(Context.getRecordType(Derived)));
8474 DeclarationNameInfo NameInfo(Name, UsingLoc);
8475
8476 TemplateParameterList *TemplateParams = 0;
8477 if (const FunctionTemplateDecl *FTD =
8478 BaseCtor->getDescribedFunctionTemplate()) {
8479 TemplateParams = FTD->getTemplateParameters();
8480 // We're reusing template parameters from a different DeclContext. This
8481 // is questionable at best, but works out because the template depth in
8482 // both places is guaranteed to be 0.
8483 // FIXME: Rebuild the template parameters in the new context, and
8484 // transform the function type to refer to them.
8485 }
8486
8487 // Build type source info pointing at the using-declaration. This is
8488 // required by template instantiation.
8489 TypeSourceInfo *TInfo =
8490 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8491 FunctionProtoTypeLoc ProtoLoc =
8492 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8493
8494 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8495 Context, Derived, UsingLoc, NameInfo, DerivedType,
8496 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8497 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8498
8499 // Build an unevaluated exception specification for this constructor.
8500 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8501 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8502 EPI.ExceptionSpecType = EST_Unevaluated;
8503 EPI.ExceptionSpecDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008504 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008505 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008506
8507 // Build the parameter declarations.
8508 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008509 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008510 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008511 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008512 ParmVarDecl *PD = ParmVarDecl::Create(
8513 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
Alp Toker9cacbab2014-01-20 20:26:09 +00008514 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
Richard Smith185be182013-04-10 05:48:59 +00008515 PD->setScopeInfo(0, I);
8516 PD->setImplicit();
8517 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008518 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008519 }
8520
8521 // Set up the new constructor.
8522 DerivedCtor->setAccess(BaseCtor->getAccess());
8523 DerivedCtor->setParams(ParamDecls);
8524 DerivedCtor->setInheritedConstructor(BaseCtor);
8525 if (BaseCtor->isDeleted())
8526 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8527
8528 // If this is a constructor template, build the template declaration.
8529 if (TemplateParams) {
8530 FunctionTemplateDecl *DerivedTemplate =
8531 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8532 TemplateParams, DerivedCtor);
8533 DerivedTemplate->setAccess(BaseCtor->getAccess());
8534 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8535 Derived->addDecl(DerivedTemplate);
8536 } else {
8537 Derived->addDecl(DerivedCtor);
8538 }
8539
8540 Entry.BaseCtor = BaseCtor;
8541 Entry.DerivedCtor = DerivedCtor;
8542 }
8543
8544 Sema &SemaRef;
8545 CXXRecordDecl *Derived;
8546 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8547 MapType Map;
8548};
8549}
8550
8551void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8552 // Defer declaring the inheriting constructors until the class is
8553 // instantiated.
8554 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008555 return;
8556
Richard Smith185be182013-04-10 05:48:59 +00008557 // Find base classes from which we might inherit constructors.
8558 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008559 for (const auto &BaseIt : ClassDecl->bases())
8560 if (BaseIt.getInheritConstructors())
8561 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008562
Richard Smith185be182013-04-10 05:48:59 +00008563 // Go no further if we're not inheriting any constructors.
8564 if (InheritedBases.empty())
8565 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008566
Richard Smith185be182013-04-10 05:48:59 +00008567 // Declare the inherited constructors.
8568 InheritingConstructorInfo ICI(*this, ClassDecl);
8569 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8570 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008571}
8572
Richard Smithc2bc61b2013-03-18 21:12:30 +00008573void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8574 CXXConstructorDecl *Constructor) {
8575 CXXRecordDecl *ClassDecl = Constructor->getParent();
8576 assert(Constructor->getInheritedConstructor() &&
8577 !Constructor->doesThisDeclarationHaveABody() &&
8578 !Constructor->isDeleted());
8579
8580 SynthesizedFunctionScope Scope(*this, Constructor);
8581 DiagnosticErrorTrap Trap(Diags);
8582 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8583 Trap.hasErrorOccurred()) {
8584 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8585 << Context.getTagDeclType(ClassDecl);
8586 Constructor->setInvalidDecl();
8587 return;
8588 }
8589
8590 SourceLocation Loc = Constructor->getLocation();
8591 Constructor->setBody(new (Context) CompoundStmt(Loc));
8592
Eli Friedman276dd182013-09-05 00:02:25 +00008593 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008594 MarkVTableUsed(CurrentLocation, ClassDecl);
8595
8596 if (ASTMutationListener *L = getASTMutationListener()) {
8597 L->CompletedImplicitDefinition(Constructor);
8598 }
8599}
8600
8601
Alexis Huntf91729462011-05-12 22:46:25 +00008602Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008603Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8604 CXXRecordDecl *ClassDecl = MD->getParent();
8605
Douglas Gregorf1203042010-07-01 19:09:28 +00008606 // C++ [except.spec]p14:
8607 // An implicitly declared special member function (Clause 12) shall have
8608 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008609 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008610 if (ClassDecl->isInvalidDecl())
8611 return ExceptSpec;
8612
Douglas Gregorf1203042010-07-01 19:09:28 +00008613 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008614 for (const auto &B : ClassDecl->bases()) {
8615 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008616 continue;
8617
Aaron Ballman574705e2014-03-13 15:41:46 +00008618 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8619 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008620 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008621 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008622
Douglas Gregorf1203042010-07-01 19:09:28 +00008623 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008624 for (const auto &B : ClassDecl->vbases()) {
8625 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8626 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008627 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008628 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008629
Douglas Gregorf1203042010-07-01 19:09:28 +00008630 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008631 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008632 if (const RecordType *RecordTy
8633 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008634 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008635 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008636 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008637
Alexis Huntf91729462011-05-12 22:46:25 +00008638 return ExceptSpec;
8639}
8640
8641CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8642 // C++ [class.dtor]p2:
8643 // If a class has no user-declared destructor, a destructor is
8644 // declared implicitly. An implicitly-declared destructor is an
8645 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008646 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008647
Richard Smith8bf22e52012-11-29 01:34:07 +00008648 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8649 if (DSM.isAlreadyBeingDeclared())
8650 return 0;
8651
Douglas Gregor7454c562010-07-02 20:37:36 +00008652 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008653 CanQualType ClassType
8654 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008655 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008656 DeclarationName Name
8657 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008658 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008659 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008660 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8661 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008662 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008663 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008664 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008665 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008666
8667 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008668 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008669 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008670
Richard Smith6b02d462012-12-08 08:32:28 +00008671 AddOverriddenMethods(ClassDecl, Destructor);
8672
8673 // We don't need to use SpecialMemberIsTrivial here; triviality for
8674 // destructors is easy to compute.
8675 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8676
8677 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008678 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008679
Douglas Gregor7454c562010-07-02 20:37:36 +00008680 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008681 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008682
Douglas Gregor7454c562010-07-02 20:37:36 +00008683 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008684 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008685 PushOnScopeChains(Destructor, S, false);
8686 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008687
Douglas Gregorf1203042010-07-01 19:09:28 +00008688 return Destructor;
8689}
8690
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008691void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008692 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008693 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008694 !Destructor->doesThisDeclarationHaveABody() &&
8695 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008696 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008697 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008698 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008699
Douglas Gregor54818f02010-05-12 16:39:35 +00008700 if (Destructor->isInvalidDecl())
8701 return;
8702
Eli Friedmaneaf34142012-10-18 20:14:08 +00008703 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008704
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008705 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008706 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8707 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008708
Douglas Gregor54818f02010-05-12 16:39:35 +00008709 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008710 Diag(CurrentLocation, diag::note_member_synthesized_at)
8711 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8712
8713 Destructor->setInvalidDecl();
8714 return;
8715 }
8716
Douglas Gregor73193272010-09-20 16:48:21 +00008717 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008718 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008719 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008720 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008721
8722 if (ASTMutationListener *L = getASTMutationListener()) {
8723 L->CompletedImplicitDefinition(Destructor);
8724 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008725}
8726
Richard Smith84973e52012-04-21 18:42:51 +00008727/// \brief Perform any semantic analysis which needs to be delayed until all
8728/// pending class member declarations have been parsed.
8729void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008730 // If the context is an invalid C++ class, just suppress these checks.
8731 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8732 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008733 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008734 DelayedDestructorExceptionSpecChecks.clear();
8735 return;
8736 }
8737 }
Richard Smith84973e52012-04-21 18:42:51 +00008738}
8739
Richard Smithd3b5c9082012-07-27 04:22:15 +00008740void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8741 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008742 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008743 "adjusting dtor exception specs was introduced in c++11");
8744
Sebastian Redl623ea822011-05-19 05:13:44 +00008745 // C++11 [class.dtor]p3:
8746 // A declaration of a destructor that does not have an exception-
8747 // specification is implicitly considered to have the same exception-
8748 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008749 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008750 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008751 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008752 return;
8753
Chandler Carruth9a797572011-09-20 04:55:26 +00008754 // Replace the destructor's type, building off the existing one. Fortunately,
8755 // the only thing of interest in the destructor type is its extended info.
8756 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008757 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8758 EPI.ExceptionSpecType = EST_Unevaluated;
8759 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008760 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008761
Sebastian Redl623ea822011-05-19 05:13:44 +00008762 // FIXME: If the destructor has a body that could throw, and the newly created
8763 // spec doesn't allow exceptions, we should emit a warning, because this
8764 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008765 // However, we don't have a body or an exception specification yet, so it
8766 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008767}
8768
Pavel Labath58934982013-08-30 08:52:28 +00008769namespace {
8770/// \brief An abstract base class for all helper classes used in building the
8771// copy/move operators. These classes serve as factory functions and help us
8772// avoid using the same Expr* in the AST twice.
8773class ExprBuilder {
8774 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8775 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8776
8777protected:
8778 static Expr *assertNotNull(Expr *E) {
8779 assert(E && "Expression construction must not fail.");
8780 return E;
8781 }
8782
8783public:
8784 ExprBuilder() {}
8785 virtual ~ExprBuilder() {}
8786
8787 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8788};
8789
8790class RefBuilder: public ExprBuilder {
8791 VarDecl *Var;
8792 QualType VarType;
8793
8794public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008795 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008796 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8797 }
8798
8799 RefBuilder(VarDecl *Var, QualType VarType)
8800 : Var(Var), VarType(VarType) {}
8801};
8802
8803class ThisBuilder: public ExprBuilder {
8804public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008805 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008806 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8807 }
8808};
8809
8810class CastBuilder: public ExprBuilder {
8811 const ExprBuilder &Builder;
8812 QualType Type;
8813 ExprValueKind Kind;
8814 const CXXCastPath &Path;
8815
8816public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008817 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008818 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8819 CK_UncheckedDerivedToBase, Kind,
8820 &Path).take());
8821 }
8822
8823 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8824 const CXXCastPath &Path)
8825 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8826};
8827
8828class DerefBuilder: public ExprBuilder {
8829 const ExprBuilder &Builder;
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(
8834 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8835 }
8836
8837 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8838};
8839
8840class MemberBuilder: public ExprBuilder {
8841 const ExprBuilder &Builder;
8842 QualType Type;
8843 CXXScopeSpec SS;
8844 bool IsArrow;
8845 LookupResult &MemberLookup;
8846
8847public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008848 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008849 return assertNotNull(S.BuildMemberReferenceExpr(
8850 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8851 MemberLookup, 0).take());
8852 }
8853
8854 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8855 LookupResult &MemberLookup)
8856 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8857 MemberLookup(MemberLookup) {}
8858};
8859
8860class MoveCastBuilder: public ExprBuilder {
8861 const ExprBuilder &Builder;
8862
8863public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008864 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008865 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8866 }
8867
8868 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8869};
8870
8871class LvalueConvBuilder: public ExprBuilder {
8872 const ExprBuilder &Builder;
8873
8874public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008875 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008876 return assertNotNull(
8877 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8878 }
8879
8880 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8881};
8882
8883class SubscriptBuilder: public ExprBuilder {
8884 const ExprBuilder &Base;
8885 const ExprBuilder &Index;
8886
8887public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008888 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008889 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8890 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8891 }
8892
8893 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8894 : Base(Base), Index(Index) {}
8895};
8896
8897} // end anonymous namespace
8898
Richard Smith41ae3282012-11-14 00:50:40 +00008899/// When generating a defaulted copy or move assignment operator, if a field
8900/// should be copied with __builtin_memcpy rather than via explicit assignments,
8901/// do so. This optimization only applies for arrays of scalars, and for arrays
8902/// of class type where the selected copy/move-assignment operator is trivial.
8903static StmtResult
8904buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008905 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00008906 // Compute the size of the memory buffer to be copied.
8907 QualType SizeType = S.Context.getSizeType();
8908 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8909 S.Context.getTypeSizeInChars(T).getQuantity());
8910
8911 // Take the address of the field references for "from" and "to". We
8912 // directly construct UnaryOperators here because semantic analysis
8913 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00008914 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008915 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8916 S.Context.getPointerType(From->getType()),
8917 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00008918 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008919 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8920 S.Context.getPointerType(To->getType()),
8921 VK_RValue, OK_Ordinary, Loc);
8922
8923 const Type *E = T->getBaseElementTypeUnsafe();
8924 bool NeedsCollectableMemCpy =
8925 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8926
8927 // Create a reference to the __builtin_objc_memmove_collectable function
8928 StringRef MemCpyName = NeedsCollectableMemCpy ?
8929 "__builtin_objc_memmove_collectable" :
8930 "__builtin_memcpy";
8931 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8932 Sema::LookupOrdinaryName);
8933 S.LookupName(R, S.TUScope, true);
8934
8935 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8936 if (!MemCpy)
8937 // Something went horribly wrong earlier, and we will have complained
8938 // about it.
8939 return StmtError();
8940
8941 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8942 VK_RValue, Loc, 0);
8943 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8944
8945 Expr *CallArgs[] = {
8946 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8947 };
8948 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8949 Loc, CallArgs, Loc);
8950
8951 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8952 return S.Owned(Call.takeAs<Stmt>());
8953}
8954
Sebastian Redl22653ba2011-08-30 19:58:05 +00008955/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00008956/// \c To.
8957///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008958/// This routine is used to copy/move the members of a class with an
8959/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00008960/// copied are arrays, this routine builds for loops to copy them.
8961///
8962/// \param S The Sema object used for type-checking.
8963///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008964/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008965///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008966/// \param T The type of the expressions being copied/moved. Both expressions
8967/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008968///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008969/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008970///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008971/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008972///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008973/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008974/// Otherwise, it's a non-static member subobject.
8975///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008976/// \param Copying Whether we're copying or moving.
8977///
Douglas Gregorb139cd52010-05-01 20:49:11 +00008978/// \param Depth Internal parameter recording the depth of the recursion.
8979///
Richard Smith41ae3282012-11-14 00:50:40 +00008980/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8981/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00008982static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00008983buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008984 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00008985 bool CopyingBaseSubobject, bool Copying,
8986 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00008987 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00008988 // Each subobject is assigned in the manner appropriate to its type:
8989 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00008990 // - if the subobject is of class type, as if by a call to operator= with
8991 // the subobject as the object expression and the corresponding
8992 // subobject of x as a single function argument (as if by explicit
8993 // qualification; that is, ignoring any possible virtual overriding
8994 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00008995 //
8996 // C++03 [class.copy]p13:
8997 // - if the subobject is of class type, the copy assignment operator for
8998 // the class is used (as if by explicit qualification; that is,
8999 // ignoring any possible virtual overriding functions in more derived
9000 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009001 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9002 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009003
Douglas Gregorb139cd52010-05-01 20:49:11 +00009004 // Look for operator=.
9005 DeclarationName Name
9006 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9007 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9008 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009009
Richard Smith52c0b582012-11-13 00:54:12 +00009010 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9011 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009012 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009013 LookupResult::Filter F = OpLookup.makeFilter();
9014 while (F.hasNext()) {
9015 NamedDecl *D = F.next();
9016 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9017 if (Method->isCopyAssignmentOperator() ||
9018 (!Copying && Method->isMoveAssignmentOperator()))
9019 continue;
9020
9021 F.erase();
9022 }
9023 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009024 }
Richard Smith52c0b582012-11-13 00:54:12 +00009025
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009026 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009027 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009028 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009029 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009030 // ambiguities), we need to cast "this" to that subobject type; to
9031 // ensure that we don't go through the virtual call mechanism, we need
9032 // to qualify the operator= name with the base class (see below). However,
9033 // this means that if the base class has a protected copy assignment
9034 // operator, the protected member access check will fail. So, we
9035 // rewrite "protected" access to "public" access in this case, since we
9036 // know by construction that we're calling from a derived class.
9037 if (CopyingBaseSubobject) {
9038 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9039 L != LEnd; ++L) {
9040 if (L.getAccess() == AS_protected)
9041 L.setAccess(AS_public);
9042 }
9043 }
Richard Smith52c0b582012-11-13 00:54:12 +00009044
Douglas Gregorb139cd52010-05-01 20:49:11 +00009045 // Create the nested-name-specifier that will be used to qualify the
9046 // reference to operator=; this is required to suppress the virtual
9047 // call mechanism.
9048 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009049 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009050 SS.MakeTrivial(S.Context,
9051 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009052 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009053 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009054
Douglas Gregorb139cd52010-05-01 20:49:11 +00009055 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009056 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009057 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9058 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00009059 /*FirstQualifierInScope=*/0,
9060 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009061 /*TemplateArgs=*/0,
9062 /*SuppressQualifierCheck=*/true);
9063 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009064 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009065
Douglas Gregorb139cd52010-05-01 20:49:11 +00009066 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009067
Pavel Labath58934982013-08-30 08:52:28 +00009068 Expr *FromInst = From.build(S, Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009069 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009070 OpEqualRef.takeAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009071 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009072 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009073 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009074
Richard Smith41ae3282012-11-14 00:50:40 +00009075 // If we built a call to a trivial 'operator=' while copying an array,
9076 // bail out. We'll replace the whole shebang with a memcpy.
9077 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9078 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9079 return StmtResult((Stmt*)0);
9080
Richard Smith52c0b582012-11-13 00:54:12 +00009081 // Convert to an expression-statement, and clean up any produced
9082 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009083 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009084 }
John McCallab8c2732010-03-16 06:11:48 +00009085
Richard Smith52c0b582012-11-13 00:54:12 +00009086 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009087 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009088 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009089 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009090 ExprResult Assignment = S.CreateBuiltinBinOp(
9091 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009092 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009093 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009094 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009095 }
Richard Smith52c0b582012-11-13 00:54:12 +00009096
9097 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009098 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009099
Douglas Gregorb139cd52010-05-01 20:49:11 +00009100 // Construct a loop over the array bounds, e.g.,
9101 //
9102 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9103 //
9104 // that will copy each of the array elements.
9105 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009106
Douglas Gregorb139cd52010-05-01 20:49:11 +00009107 // Create the iteration variable.
9108 IdentifierInfo *IterationVarName = 0;
9109 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009110 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009111 llvm::raw_svector_ostream OS(Str);
9112 OS << "__i" << Depth;
9113 IterationVarName = &S.Context.Idents.get(OS.str());
9114 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009115 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009116 IterationVarName, SizeType,
9117 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009118 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009119
Douglas Gregorb139cd52010-05-01 20:49:11 +00009120 // Initialize the iteration variable to zero.
9121 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009122 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009123
Pavel Labath58934982013-08-30 08:52:28 +00009124 // Creates a reference to the iteration variable.
9125 RefBuilder IterationVarRef(IterationVar, SizeType);
9126 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009127
Douglas Gregorb139cd52010-05-01 20:49:11 +00009128 // Create the DeclStmt that holds the iteration variable.
9129 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009130
Douglas Gregorb139cd52010-05-01 20:49:11 +00009131 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009132 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9133 MoveCastBuilder FromIndexMove(FromIndexCopy);
9134 const ExprBuilder *FromIndex;
9135 if (Copying)
9136 FromIndex = &FromIndexCopy;
9137 else
9138 FromIndex = &FromIndexMove;
9139
9140 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009141
9142 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009143 StmtResult Copy =
9144 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009145 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009146 Copying, Depth + 1);
9147 // Bail out if copying fails or if we determined that we should use memcpy.
9148 if (Copy.isInvalid() || !Copy.get())
9149 return Copy;
9150
9151 // Create the comparison against the array bound.
9152 llvm::APInt Upper
9153 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9154 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009155 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009156 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9157 BO_NE, S.Context.BoolTy,
9158 VK_RValue, OK_Ordinary, Loc, false);
9159
9160 // Create the pre-increment of the iteration variable.
9161 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009162 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9163 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009164
Douglas Gregorb139cd52010-05-01 20:49:11 +00009165 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009166 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009167 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00009168 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00009169 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009170}
9171
Richard Smith41ae3282012-11-14 00:50:40 +00009172static StmtResult
9173buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009174 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009175 bool CopyingBaseSubobject, bool Copying) {
9176 // Maybe we should use a memcpy?
9177 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9178 T.isTriviallyCopyableType(S.Context))
9179 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9180
9181 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9182 CopyingBaseSubobject,
9183 Copying, 0));
9184
9185 // If we ended up picking a trivial assignment operator for an array of a
9186 // non-trivially-copyable class type, just emit a memcpy.
9187 if (!Result.isInvalid() && !Result.get())
9188 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9189
9190 return Result;
9191}
9192
Richard Smithd3b5c9082012-07-27 04:22:15 +00009193Sema::ImplicitExceptionSpecification
9194Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9195 CXXRecordDecl *ClassDecl = MD->getParent();
9196
9197 ImplicitExceptionSpecification ExceptSpec(*this);
9198 if (ClassDecl->isInvalidDecl())
9199 return ExceptSpec;
9200
9201 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009202 assert(T->getNumParams() == 1 && "not a copy assignment op");
9203 unsigned ArgQuals =
9204 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009205
Douglas Gregor68e11362010-07-01 17:48:08 +00009206 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009207 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009208 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009209
9210 // It is unspecified whether or not an implicit copy assignment operator
9211 // attempts to deduplicate calls to assignment operators of virtual bases are
9212 // made. As such, this exception specification is effectively unspecified.
9213 // Based on a similar decision made for constness in C++0x, we're erring on
9214 // the side of assuming such calls to be made regardless of whether they
9215 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009216 for (const auto &Base : ClassDecl->bases()) {
9217 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009218 continue;
9219
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009220 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009221 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009222 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9223 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009224 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009225 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009226
Aaron Ballman445a9392014-03-13 16:15:17 +00009227 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009228 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009229 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009230 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9231 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009232 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009233 }
9234
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009235 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009236 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009237 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9238 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009239 LookupCopyingAssignment(FieldClassDecl,
9240 ArgQuals | FieldType.getCVRQualifiers(),
9241 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009242 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009243 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009244 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009245
Richard Smithd3b5c9082012-07-27 04:22:15 +00009246 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009247}
9248
9249CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9250 // Note: The following rules are largely analoguous to the copy
9251 // constructor rules. Note that virtual bases are not taken into account
9252 // for determining the argument type of the operator. Note also that
9253 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009254 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009255
Richard Smith8bf22e52012-11-29 01:34:07 +00009256 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9257 if (DSM.isAlreadyBeingDeclared())
9258 return 0;
9259
Alexis Hunt119f3652011-05-14 05:23:20 +00009260 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9261 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009262 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9263 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009264 ArgType = ArgType.withConst();
9265 ArgType = Context.getLValueReferenceType(ArgType);
9266
Richard Smith99005e62013-05-07 03:19:20 +00009267 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9268 CXXCopyAssignment,
9269 Const);
9270
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009271 // An implicitly-declared copy assignment operator is an inline public
9272 // member of its class.
9273 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009274 SourceLocation ClassLoc = ClassDecl->getLocation();
9275 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009276 CXXMethodDecl *CopyAssignment =
9277 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9278 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9279 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009280 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009281 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009282 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009283
9284 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009285 FunctionProtoType::ExtProtoInfo EPI =
9286 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009287 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009288
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009289 // Add the parameter to the operator.
9290 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009291 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009292 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009293 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009294 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009295
Richard Smith6b02d462012-12-08 08:32:28 +00009296 AddOverriddenMethods(ClassDecl, CopyAssignment);
9297
9298 CopyAssignment->setTrivial(
9299 ClassDecl->needsOverloadResolutionForCopyAssignment()
9300 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9301 : ClassDecl->hasTrivialCopyAssignment());
9302
Richard Smith852265f2012-03-30 20:53:28 +00009303 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009304 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009305
Richard Smith6b02d462012-12-08 08:32:28 +00009306 // Note that we have added this copy-assignment operator.
9307 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9308
9309 if (Scope *S = getScopeForContext(ClassDecl))
9310 PushOnScopeChains(CopyAssignment, S, false);
9311 ClassDecl->addDecl(CopyAssignment);
9312
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009313 return CopyAssignment;
9314}
9315
Richard Smithd577fbb2013-06-13 03:23:42 +00009316/// Diagnose an implicit copy operation for a class which is odr-used, but
9317/// which is deprecated because the class has a user-declared copy constructor,
9318/// copy assignment operator, or destructor.
9319static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9320 SourceLocation UseLoc) {
9321 assert(CopyOp->isImplicit());
9322
9323 CXXRecordDecl *RD = CopyOp->getParent();
9324 CXXMethodDecl *UserDeclaredOperation = 0;
9325
9326 // In Microsoft mode, assignment operations don't affect constructors and
9327 // vice versa.
9328 if (RD->hasUserDeclaredDestructor()) {
9329 UserDeclaredOperation = RD->getDestructor();
9330 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9331 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009332 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009333 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009334 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009335 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009336 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009337 break;
9338 }
9339 }
9340 assert(UserDeclaredOperation);
9341 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9342 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009343 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009344 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009345 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009346 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009347 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009348 break;
9349 }
9350 }
9351 assert(UserDeclaredOperation);
9352 }
9353
9354 if (UserDeclaredOperation) {
9355 S.Diag(UserDeclaredOperation->getLocation(),
9356 diag::warn_deprecated_copy_operation)
9357 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9358 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9359 S.Diag(UseLoc, diag::note_member_synthesized_at)
9360 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9361 : Sema::CXXCopyAssignment)
9362 << RD;
9363 }
9364}
9365
Douglas Gregorb139cd52010-05-01 20:49:11 +00009366void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9367 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009368 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009369 CopyAssignOperator->isOverloadedOperator() &&
9370 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009371 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9372 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009373 "DefineImplicitCopyAssignment called for wrong function");
9374
9375 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9376
9377 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9378 CopyAssignOperator->setInvalidDecl();
9379 return;
9380 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009381
9382 // C++11 [class.copy]p18:
9383 // The [definition of an implicitly declared copy assignment operator] is
9384 // deprecated if the class has a user-declared copy constructor or a
9385 // user-declared destructor.
9386 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9387 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9388
Eli Friedman276dd182013-09-05 00:02:25 +00009389 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009390
Eli Friedmaneaf34142012-10-18 20:14:08 +00009391 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009392 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009393
9394 // C++0x [class.copy]p30:
9395 // The implicitly-defined or explicitly-defaulted copy assignment operator
9396 // for a non-union class X performs memberwise copy assignment of its
9397 // subobjects. The direct base classes of X are assigned first, in the
9398 // order of their declaration in the base-specifier-list, and then the
9399 // immediate non-static data members of X are assigned, in the order in
9400 // which they were declared in the class definition.
9401
9402 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009403 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009404
9405 // The parameter for the "other" object, which we are copying from.
9406 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9407 Qualifiers OtherQuals = Other->getType().getQualifiers();
9408 QualType OtherRefType = Other->getType();
9409 if (const LValueReferenceType *OtherRef
9410 = OtherRefType->getAs<LValueReferenceType>()) {
9411 OtherRefType = OtherRef->getPointeeType();
9412 OtherQuals = OtherRefType.getQualifiers();
9413 }
9414
9415 // Our location for everything implicitly-generated.
9416 SourceLocation Loc = CopyAssignOperator->getLocation();
9417
Pavel Labath58934982013-08-30 08:52:28 +00009418 // Builds a DeclRefExpr for the "other" object.
9419 RefBuilder OtherRef(Other, OtherRefType);
9420
9421 // Builds the "this" pointer.
9422 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009423
9424 // Assign base classes.
9425 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009426 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009427 // Form the assignment:
9428 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009429 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009430 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009431 Invalid = true;
9432 continue;
9433 }
9434
John McCallcf142162010-08-07 06:22:56 +00009435 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009436 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009437
Douglas Gregorb139cd52010-05-01 20:49:11 +00009438 // Construct the "from" expression, which is an implicit cast to the
9439 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009440 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9441 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009442
9443 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009444 DerefBuilder DerefThis(This);
9445 CastBuilder To(DerefThis,
9446 Context.getCVRQualifiedType(
9447 BaseType, CopyAssignOperator->getTypeQualifiers()),
9448 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009449
9450 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009451 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009452 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009453 /*CopyingBaseSubobject=*/true,
9454 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009455 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009456 Diag(CurrentLocation, diag::note_member_synthesized_at)
9457 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9458 CopyAssignOperator->setInvalidDecl();
9459 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009460 }
9461
9462 // Success! Record the copy.
9463 Statements.push_back(Copy.takeAs<Expr>());
9464 }
9465
Douglas Gregorb139cd52010-05-01 20:49:11 +00009466 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009467 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009468 if (Field->isUnnamedBitfield())
9469 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009470
9471 if (Field->isInvalidDecl()) {
9472 Invalid = true;
9473 continue;
9474 }
9475
Douglas Gregorb139cd52010-05-01 20:49:11 +00009476 // Check for members of reference type; we can't copy those.
9477 if (Field->getType()->isReferenceType()) {
9478 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9479 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9480 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009481 Diag(CurrentLocation, diag::note_member_synthesized_at)
9482 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009483 Invalid = true;
9484 continue;
9485 }
9486
9487 // Check for members of const-qualified, non-class type.
9488 QualType BaseType = Context.getBaseElementType(Field->getType());
9489 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9490 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9491 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9492 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009493 Diag(CurrentLocation, diag::note_member_synthesized_at)
9494 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009495 Invalid = true;
9496 continue;
9497 }
John McCall1b1a1db2011-06-17 00:18:42 +00009498
9499 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009500 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9501 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009502
9503 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009504 if (FieldType->isIncompleteArrayType()) {
9505 assert(ClassDecl->hasFlexibleArrayMember() &&
9506 "Incomplete array type is not valid");
9507 continue;
9508 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009509
9510 // Build references to the field in the object we're copying from and to.
9511 CXXScopeSpec SS; // Intentionally empty
9512 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9513 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009514 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009515 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009516
9517 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9518
9519 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009520
Douglas Gregorb139cd52010-05-01 20:49:11 +00009521 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009522 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009523 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009524 /*CopyingBaseSubobject=*/false,
9525 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009526 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009527 Diag(CurrentLocation, diag::note_member_synthesized_at)
9528 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9529 CopyAssignOperator->setInvalidDecl();
9530 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009531 }
9532
9533 // Success! Record the copy.
9534 Statements.push_back(Copy.takeAs<Stmt>());
9535 }
9536
9537 if (!Invalid) {
9538 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009539 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009540
John McCalldadc5752010-08-24 06:29:42 +00009541 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009542 if (Return.isInvalid())
9543 Invalid = true;
9544 else {
9545 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009546
9547 if (Trap.hasErrorOccurred()) {
9548 Diag(CurrentLocation, diag::note_member_synthesized_at)
9549 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9550 Invalid = true;
9551 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009552 }
9553 }
9554
9555 if (Invalid) {
9556 CopyAssignOperator->setInvalidDecl();
9557 return;
9558 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009559
9560 StmtResult Body;
9561 {
9562 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009563 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009564 /*isStmtExpr=*/false);
9565 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9566 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009567 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009568
9569 if (ASTMutationListener *L = getASTMutationListener()) {
9570 L->CompletedImplicitDefinition(CopyAssignOperator);
9571 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009572}
9573
Sebastian Redl22653ba2011-08-30 19:58:05 +00009574Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009575Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9576 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009577
Richard Smithd3b5c9082012-07-27 04:22:15 +00009578 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009579 if (ClassDecl->isInvalidDecl())
9580 return ExceptSpec;
9581
9582 // C++0x [except.spec]p14:
9583 // An implicitly declared special member function (Clause 12) shall have an
9584 // exception-specification. [...]
9585
9586 // It is unspecified whether or not an implicit move assignment operator
9587 // attempts to deduplicate calls to assignment operators of virtual bases are
9588 // made. As such, this exception specification is effectively unspecified.
9589 // Based on a similar decision made for constness in C++0x, we're erring on
9590 // the side of assuming such calls to be made regardless of whether they
9591 // actually happen.
9592 // Note that a move constructor is not implicitly declared when there are
9593 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009594 for (const auto &Base : ClassDecl->bases()) {
9595 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009596 continue;
9597
9598 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009599 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009600 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009601 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009602 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009603 }
9604
Aaron Ballman445a9392014-03-13 16:15:17 +00009605 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009606 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009607 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009608 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009609 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009610 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009611 }
9612
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009613 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009614 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009615 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009616 if (CXXMethodDecl *MoveAssign =
9617 LookupMovingAssignment(FieldClassDecl,
9618 FieldType.getCVRQualifiers(),
9619 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009620 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009621 }
9622 }
9623
9624 return ExceptSpec;
9625}
9626
9627CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009628 assert(ClassDecl->needsImplicitMoveAssignment());
9629
Richard Smith8bf22e52012-11-29 01:34:07 +00009630 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9631 if (DSM.isAlreadyBeingDeclared())
9632 return 0;
9633
Sebastian Redl22653ba2011-08-30 19:58:05 +00009634 // Note: The following rules are largely analoguous to the move
9635 // constructor rules.
9636
Sebastian Redl22653ba2011-08-30 19:58:05 +00009637 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9638 QualType RetType = Context.getLValueReferenceType(ArgType);
9639 ArgType = Context.getRValueReferenceType(ArgType);
9640
Richard Smith99005e62013-05-07 03:19:20 +00009641 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9642 CXXMoveAssignment,
9643 false);
9644
Sebastian Redl22653ba2011-08-30 19:58:05 +00009645 // An implicitly-declared move assignment operator is an inline public
9646 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009647 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9648 SourceLocation ClassLoc = ClassDecl->getLocation();
9649 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009650 CXXMethodDecl *MoveAssignment =
9651 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9652 /*TInfo=*/0, /*StorageClass=*/SC_None,
9653 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009654 MoveAssignment->setAccess(AS_public);
9655 MoveAssignment->setDefaulted();
9656 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009657
Richard Smithd3b5c9082012-07-27 04:22:15 +00009658 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009659 FunctionProtoType::ExtProtoInfo EPI =
9660 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009661 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009662
Sebastian Redl22653ba2011-08-30 19:58:05 +00009663 // Add the parameter to the operator.
9664 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9665 ClassLoc, ClassLoc, /*Id=*/0,
9666 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009667 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009668 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009669
Richard Smith6b02d462012-12-08 08:32:28 +00009670 AddOverriddenMethods(ClassDecl, MoveAssignment);
9671
9672 MoveAssignment->setTrivial(
9673 ClassDecl->needsOverloadResolutionForMoveAssignment()
9674 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9675 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009676
Richard Smithd951a1d2012-02-18 02:02:13 +00009677 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009678 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9679 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009680 }
9681
Richard Smith6b02d462012-12-08 08:32:28 +00009682 // Note that we have added this copy-assignment operator.
9683 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9684
Sebastian Redl22653ba2011-08-30 19:58:05 +00009685 if (Scope *S = getScopeForContext(ClassDecl))
9686 PushOnScopeChains(MoveAssignment, S, false);
9687 ClassDecl->addDecl(MoveAssignment);
9688
Sebastian Redl22653ba2011-08-30 19:58:05 +00009689 return MoveAssignment;
9690}
9691
Richard Smithb2504bd2013-11-04 04:26:14 +00009692/// Check if we're implicitly defining a move assignment operator for a class
9693/// with virtual bases. Such a move assignment might move-assign the virtual
9694/// base multiple times.
9695static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9696 SourceLocation CurrentLocation) {
9697 assert(!Class->isDependentContext() && "should not define dependent move");
9698
9699 // Only a virtual base could get implicitly move-assigned multiple times.
9700 // Only a non-trivial move assignment can observe this. We only want to
9701 // diagnose if we implicitly define an assignment operator that assigns
9702 // two base classes, both of which move-assign the same virtual base.
9703 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9704 Class->getNumBases() < 2)
9705 return;
9706
9707 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9708 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9709 VBaseMap VBases;
9710
Aaron Ballman574705e2014-03-13 15:41:46 +00009711 for (auto &BI : Class->bases()) {
9712 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009713 while (!Worklist.empty()) {
9714 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9715 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9716
9717 // If the base has no non-trivial move assignment operators,
9718 // we don't care about moves from it.
9719 if (!Base->hasNonTrivialMoveAssignment())
9720 continue;
9721
9722 // If there's nothing virtual here, skip it.
9723 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9724 continue;
9725
9726 // If we're not actually going to call a move assignment for this base,
9727 // or the selected move assignment is trivial, skip it.
9728 Sema::SpecialMemberOverloadResult *SMOR =
9729 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9730 /*ConstArg*/false, /*VolatileArg*/false,
9731 /*RValueThis*/true, /*ConstThis*/false,
9732 /*VolatileThis*/false);
9733 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9734 !SMOR->getMethod()->isMoveAssignmentOperator())
9735 continue;
9736
9737 if (BaseSpec->isVirtual()) {
9738 // We're going to move-assign this virtual base, and its move
9739 // assignment operator is not trivial. If this can happen for
9740 // multiple distinct direct bases of Class, diagnose it. (If it
9741 // only happens in one base, we'll diagnose it when synthesizing
9742 // that base class's move assignment operator.)
9743 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +00009744 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +00009745 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +00009746 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009747 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9748 << Class << Base;
9749 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9750 << (Base->getCanonicalDecl() ==
9751 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9752 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +00009753 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +00009754 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +00009755 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9756 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +00009757
9758 // Only diagnose each vbase once.
9759 Existing = 0;
9760 }
9761 } else {
9762 // Only walk over bases that have defaulted move assignment operators.
9763 // We assume that any user-provided move assignment operator handles
9764 // the multiple-moves-of-vbase case itself somehow.
9765 if (!SMOR->getMethod()->isDefaulted())
9766 continue;
9767
9768 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +00009769 for (auto &BI : Base->bases())
9770 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009771 }
9772 }
9773 }
9774}
9775
Sebastian Redl22653ba2011-08-30 19:58:05 +00009776void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9777 CXXMethodDecl *MoveAssignOperator) {
9778 assert((MoveAssignOperator->isDefaulted() &&
9779 MoveAssignOperator->isOverloadedOperator() &&
9780 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009781 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9782 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009783 "DefineImplicitMoveAssignment called for wrong function");
9784
9785 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9786
9787 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9788 MoveAssignOperator->setInvalidDecl();
9789 return;
9790 }
9791
Eli Friedman276dd182013-09-05 00:02:25 +00009792 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009793
Eli Friedmaneaf34142012-10-18 20:14:08 +00009794 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009795 DiagnosticErrorTrap Trap(Diags);
9796
9797 // C++0x [class.copy]p28:
9798 // The implicitly-defined or move assignment operator for a non-union class
9799 // X performs memberwise move assignment of its subobjects. The direct base
9800 // classes of X are assigned first, in the order of their declaration in the
9801 // base-specifier-list, and then the immediate non-static data members of X
9802 // are assigned, in the order in which they were declared in the class
9803 // definition.
9804
Richard Smithb2504bd2013-11-04 04:26:14 +00009805 // Issue a warning if our implicit move assignment operator will move
9806 // from a virtual base more than once.
9807 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009808
Sebastian Redl22653ba2011-08-30 19:58:05 +00009809 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009810 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009811
9812 // The parameter for the "other" object, which we are move from.
9813 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9814 QualType OtherRefType = Other->getType()->
9815 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009816 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009817 "Bad argument type of defaulted move assignment");
9818
9819 // Our location for everything implicitly-generated.
9820 SourceLocation Loc = MoveAssignOperator->getLocation();
9821
Pavel Labath58934982013-08-30 08:52:28 +00009822 // Builds a reference to the "other" object.
9823 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009824 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009825 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009826
Pavel Labath58934982013-08-30 08:52:28 +00009827 // Builds the "this" pointer.
9828 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009829
Sebastian Redl22653ba2011-08-30 19:58:05 +00009830 // Assign base classes.
9831 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009832 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009833 // C++11 [class.copy]p28:
9834 // It is unspecified whether subobjects representing virtual base classes
9835 // are assigned more than once by the implicitly-defined copy assignment
9836 // operator.
9837 // FIXME: Do not assign to a vbase that will be assigned by some other base
9838 // class. For a move-assignment, this can result in the vbase being moved
9839 // multiple times.
9840
Sebastian Redl22653ba2011-08-30 19:58:05 +00009841 // Form the assignment:
9842 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009843 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009844 if (!BaseType->isRecordType()) {
9845 Invalid = true;
9846 continue;
9847 }
9848
9849 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009850 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009851
9852 // Construct the "from" expression, which is an implicit cast to the
9853 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009854 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009855
9856 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009857 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009858
9859 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009860 CastBuilder To(DerefThis,
9861 Context.getCVRQualifiedType(
9862 BaseType, MoveAssignOperator->getTypeQualifiers()),
9863 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009864
9865 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009866 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009867 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009868 /*CopyingBaseSubobject=*/true,
9869 /*Copying=*/false);
9870 if (Move.isInvalid()) {
9871 Diag(CurrentLocation, diag::note_member_synthesized_at)
9872 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9873 MoveAssignOperator->setInvalidDecl();
9874 return;
9875 }
9876
9877 // Success! Record the move.
9878 Statements.push_back(Move.takeAs<Expr>());
9879 }
9880
Sebastian Redl22653ba2011-08-30 19:58:05 +00009881 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009882 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009883 if (Field->isUnnamedBitfield())
9884 continue;
9885
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009886 if (Field->isInvalidDecl()) {
9887 Invalid = true;
9888 continue;
9889 }
9890
Sebastian Redl22653ba2011-08-30 19:58:05 +00009891 // Check for members of reference type; we can't move those.
9892 if (Field->getType()->isReferenceType()) {
9893 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9894 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9895 Diag(Field->getLocation(), diag::note_declared_at);
9896 Diag(CurrentLocation, diag::note_member_synthesized_at)
9897 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9898 Invalid = true;
9899 continue;
9900 }
9901
9902 // Check for members of const-qualified, non-class type.
9903 QualType BaseType = Context.getBaseElementType(Field->getType());
9904 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9905 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9906 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9907 Diag(Field->getLocation(), diag::note_declared_at);
9908 Diag(CurrentLocation, diag::note_member_synthesized_at)
9909 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9910 Invalid = true;
9911 continue;
9912 }
9913
9914 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009915 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9916 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009917
9918 QualType FieldType = Field->getType().getNonReferenceType();
9919 if (FieldType->isIncompleteArrayType()) {
9920 assert(ClassDecl->hasFlexibleArrayMember() &&
9921 "Incomplete array type is not valid");
9922 continue;
9923 }
9924
9925 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009926 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9927 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009928 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009929 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009930 MemberBuilder From(MoveOther, OtherRefType,
9931 /*IsArrow=*/false, MemberLookup);
9932 MemberBuilder To(This, getCurrentThisType(),
9933 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009934
Pavel Labath58934982013-08-30 08:52:28 +00009935 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +00009936 "Member reference with rvalue base must be rvalue except for reference "
9937 "members, which aren't allowed for move assignment.");
9938
Sebastian Redl22653ba2011-08-30 19:58:05 +00009939 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009940 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009941 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009942 /*CopyingBaseSubobject=*/false,
9943 /*Copying=*/false);
9944 if (Move.isInvalid()) {
9945 Diag(CurrentLocation, diag::note_member_synthesized_at)
9946 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9947 MoveAssignOperator->setInvalidDecl();
9948 return;
9949 }
Richard Smith11d19592012-11-12 23:33:00 +00009950
Sebastian Redl22653ba2011-08-30 19:58:05 +00009951 // Success! Record the copy.
9952 Statements.push_back(Move.takeAs<Stmt>());
9953 }
9954
9955 if (!Invalid) {
9956 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009957 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00009958
9959 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9960 if (Return.isInvalid())
9961 Invalid = true;
9962 else {
9963 Statements.push_back(Return.takeAs<Stmt>());
9964
9965 if (Trap.hasErrorOccurred()) {
9966 Diag(CurrentLocation, diag::note_member_synthesized_at)
9967 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9968 Invalid = true;
9969 }
9970 }
9971 }
9972
9973 if (Invalid) {
9974 MoveAssignOperator->setInvalidDecl();
9975 return;
9976 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009977
9978 StmtResult Body;
9979 {
9980 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009981 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009982 /*isStmtExpr=*/false);
9983 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9984 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00009985 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9986
9987 if (ASTMutationListener *L = getASTMutationListener()) {
9988 L->CompletedImplicitDefinition(MoveAssignOperator);
9989 }
9990}
9991
Richard Smithd3b5c9082012-07-27 04:22:15 +00009992Sema::ImplicitExceptionSpecification
9993Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9994 CXXRecordDecl *ClassDecl = MD->getParent();
9995
9996 ImplicitExceptionSpecification ExceptSpec(*this);
9997 if (ClassDecl->isInvalidDecl())
9998 return ExceptSpec;
9999
10000 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010001 assert(T->getNumParams() >= 1 && "not a copy ctor");
10002 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010003
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010004 // C++ [except.spec]p14:
10005 // An implicitly declared special member function (Clause 12) shall have an
10006 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010007 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010008 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010009 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010010 continue;
10011
Douglas Gregora6d69502010-07-02 23:41:54 +000010012 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010013 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010014 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010015 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010016 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010017 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010018 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010019 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010020 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010021 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010022 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010023 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010024 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010025 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010026 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010027 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10028 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010029 LookupCopyingConstructor(FieldClassDecl,
10030 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010031 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010032 }
10033 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010034
Richard Smithd3b5c9082012-07-27 04:22:15 +000010035 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010036}
10037
10038CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10039 CXXRecordDecl *ClassDecl) {
10040 // C++ [class.copy]p4:
10041 // If the class definition does not explicitly declare a copy
10042 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010043 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010044
Richard Smith8bf22e52012-11-29 01:34:07 +000010045 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10046 if (DSM.isAlreadyBeingDeclared())
10047 return 0;
10048
Alexis Hunt913820d2011-05-13 06:10:58 +000010049 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10050 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010051 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010052 if (Const)
10053 ArgType = ArgType.withConst();
10054 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010055
Richard Smithb5800092012-06-10 05:43:50 +000010056 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10057 CXXCopyConstructor,
10058 Const);
10059
Douglas Gregor54be3392010-07-01 17:57:27 +000010060 DeclarationName Name
10061 = Context.DeclarationNames.getCXXConstructorName(
10062 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010063 SourceLocation ClassLoc = ClassDecl->getLocation();
10064 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010065
10066 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010067 // member of its class.
10068 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010069 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010070 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010071 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010072 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010073 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010074
Richard Smithd3b5c9082012-07-27 04:22:15 +000010075 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010076 FunctionProtoType::ExtProtoInfo EPI =
10077 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010078 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010079 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010080
Douglas Gregor54be3392010-07-01 17:57:27 +000010081 // Add the parameter to the constructor.
10082 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010083 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +000010084 /*IdentifierInfo=*/0,
10085 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +000010086 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010087 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010088
Richard Smith6b02d462012-12-08 08:32:28 +000010089 CopyConstructor->setTrivial(
10090 ClassDecl->needsOverloadResolutionForCopyConstructor()
10091 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10092 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010093
Richard Smith852265f2012-03-30 20:53:28 +000010094 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010095 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010096
Richard Smith6b02d462012-12-08 08:32:28 +000010097 // Note that we have declared this constructor.
10098 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10099
10100 if (Scope *S = getScopeForContext(ClassDecl))
10101 PushOnScopeChains(CopyConstructor, S, false);
10102 ClassDecl->addDecl(CopyConstructor);
10103
Douglas Gregor54be3392010-07-01 17:57:27 +000010104 return CopyConstructor;
10105}
10106
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010107void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010108 CXXConstructorDecl *CopyConstructor) {
10109 assert((CopyConstructor->isDefaulted() &&
10110 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010111 !CopyConstructor->doesThisDeclarationHaveABody() &&
10112 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010113 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010114
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010115 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010116 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010117
Richard Smithd577fbb2013-06-13 03:23:42 +000010118 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010119 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010120 // deprecated if the class has a user-declared copy assignment operator
10121 // or a user-declared destructor.
10122 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10123 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10124
Eli Friedmaneaf34142012-10-18 20:14:08 +000010125 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010126 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010127
David Blaikie3fc2f912013-01-17 05:26:25 +000010128 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010129 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010130 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010131 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010132 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010133 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010134 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010135 CopyConstructor->setBody(ActOnCompoundStmt(
10136 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10137 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010138 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010139
Eli Friedman276dd182013-09-05 00:02:25 +000010140 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010141 if (ASTMutationListener *L = getASTMutationListener()) {
10142 L->CompletedImplicitDefinition(CopyConstructor);
10143 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010144}
10145
Sebastian Redl22653ba2011-08-30 19:58:05 +000010146Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010147Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10148 CXXRecordDecl *ClassDecl = MD->getParent();
10149
Sebastian Redl22653ba2011-08-30 19:58:05 +000010150 // C++ [except.spec]p14:
10151 // An implicitly declared special member function (Clause 12) shall have an
10152 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010153 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010154 if (ClassDecl->isInvalidDecl())
10155 return ExceptSpec;
10156
10157 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010158 for (const auto &B : ClassDecl->bases()) {
10159 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010160 continue;
10161
Aaron Ballman574705e2014-03-13 15:41:46 +000010162 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010163 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010164 CXXConstructorDecl *Constructor =
10165 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010166 // If this is a deleted function, add it anyway. This might be conformant
10167 // with the standard. This might not. I'm not sure. It might not matter.
10168 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010169 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010170 }
10171 }
10172
10173 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010174 for (const auto &B : ClassDecl->vbases()) {
10175 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010176 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010177 CXXConstructorDecl *Constructor =
10178 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010179 // If this is a deleted function, add it anyway. This might be conformant
10180 // with the standard. This might not. I'm not sure. It might not matter.
10181 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010182 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010183 }
10184 }
10185
10186 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010187 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010188 QualType FieldType = Context.getBaseElementType(F->getType());
10189 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10190 CXXConstructorDecl *Constructor =
10191 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010192 // If this is a deleted function, add it anyway. This might be conformant
10193 // with the standard. This might not. I'm not sure. It might not matter.
10194 // In particular, the problem is that this function never gets called. It
10195 // might just be ill-formed because this function attempts to refer to
10196 // a deleted function here.
10197 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010198 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010199 }
10200 }
10201
10202 return ExceptSpec;
10203}
10204
10205CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10206 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010207 assert(ClassDecl->needsImplicitMoveConstructor());
10208
Richard Smith8bf22e52012-11-29 01:34:07 +000010209 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10210 if (DSM.isAlreadyBeingDeclared())
10211 return 0;
10212
Sebastian Redl22653ba2011-08-30 19:58:05 +000010213 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10214 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010215
Richard Smithb5800092012-06-10 05:43:50 +000010216 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10217 CXXMoveConstructor,
10218 false);
10219
Sebastian Redl22653ba2011-08-30 19:58:05 +000010220 DeclarationName Name
10221 = Context.DeclarationNames.getCXXConstructorName(
10222 Context.getCanonicalType(ClassType));
10223 SourceLocation ClassLoc = ClassDecl->getLocation();
10224 DeclarationNameInfo NameInfo(Name, ClassLoc);
10225
Richard Smith99005e62013-05-07 03:19:20 +000010226 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010227 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010228 // member of its class.
10229 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010230 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010231 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010232 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010233 MoveConstructor->setAccess(AS_public);
10234 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010235
Richard Smithd3b5c9082012-07-27 04:22:15 +000010236 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010237 FunctionProtoType::ExtProtoInfo EPI =
10238 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010239 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010240 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010241
Sebastian Redl22653ba2011-08-30 19:58:05 +000010242 // Add the parameter to the constructor.
10243 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10244 ClassLoc, ClassLoc,
10245 /*IdentifierInfo=*/0,
10246 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010247 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010248 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010249
Richard Smith6b02d462012-12-08 08:32:28 +000010250 MoveConstructor->setTrivial(
10251 ClassDecl->needsOverloadResolutionForMoveConstructor()
10252 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10253 : ClassDecl->hasTrivialMoveConstructor());
10254
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010255 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010256 ClassDecl->setImplicitMoveConstructorIsDeleted();
10257 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010258 }
10259
10260 // Note that we have declared this constructor.
10261 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10262
10263 if (Scope *S = getScopeForContext(ClassDecl))
10264 PushOnScopeChains(MoveConstructor, S, false);
10265 ClassDecl->addDecl(MoveConstructor);
10266
10267 return MoveConstructor;
10268}
10269
10270void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10271 CXXConstructorDecl *MoveConstructor) {
10272 assert((MoveConstructor->isDefaulted() &&
10273 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010274 !MoveConstructor->doesThisDeclarationHaveABody() &&
10275 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010276 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10277
10278 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10279 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10280
Eli Friedmaneaf34142012-10-18 20:14:08 +000010281 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010282 DiagnosticErrorTrap Trap(Diags);
10283
David Blaikie3fc2f912013-01-17 05:26:25 +000010284 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010285 Trap.hasErrorOccurred()) {
10286 Diag(CurrentLocation, diag::note_member_synthesized_at)
10287 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10288 MoveConstructor->setInvalidDecl();
10289 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010290 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010291 MoveConstructor->setBody(ActOnCompoundStmt(
10292 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10293 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010294 }
10295
Eli Friedman276dd182013-09-05 00:02:25 +000010296 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010297
10298 if (ASTMutationListener *L = getASTMutationListener()) {
10299 L->CompletedImplicitDefinition(MoveConstructor);
10300 }
10301}
10302
Douglas Gregor74f7d502012-02-15 19:33:52 +000010303bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010304 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010305}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010306
10307void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010308 SourceLocation CurrentLocation,
10309 CXXConversionDecl *Conv) {
10310 CXXRecordDecl *Lambda = Conv->getParent();
10311 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10312 // If we are defining a specialization of a conversion to function-ptr
10313 // cache the deduced template arguments for this specialization
10314 // so that we can use them to retrieve the corresponding call-operator
10315 // and static-invoker.
10316 const TemplateArgumentList *DeducedTemplateArgs = 0;
10317
Douglas Gregor355efbb2012-02-17 03:02:34 +000010318
Faisal Vali571df122013-09-29 08:45:24 +000010319 // Retrieve the corresponding call-operator specialization.
10320 if (Lambda->isGenericLambda()) {
10321 assert(Conv->isFunctionTemplateSpecialization());
10322 FunctionTemplateDecl *CallOpTemplate =
10323 CallOp->getDescribedFunctionTemplate();
10324 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10325 void *InsertPos = 0;
10326 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10327 DeducedTemplateArgs->data(),
10328 DeducedTemplateArgs->size(),
10329 InsertPos);
10330 assert(CallOpSpec &&
10331 "Conversion operator must have a corresponding call operator");
10332 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10333 }
10334 // Mark the call operator referenced (and add to pending instantiations
10335 // if necessary).
10336 // For both the conversion and static-invoker template specializations
10337 // we construct their body's in this function, so no need to add them
10338 // to the PendingInstantiations.
10339 MarkFunctionReferenced(CurrentLocation, CallOp);
10340
Eli Friedmaneaf34142012-10-18 20:14:08 +000010341 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010342 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010343
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010344 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010345 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10346 // ... and get the corresponding specialization for a generic lambda.
10347 if (Lambda->isGenericLambda()) {
10348 assert(DeducedTemplateArgs &&
10349 "Must have deduced template arguments from Conversion Operator");
10350 FunctionTemplateDecl *InvokeTemplate =
10351 Invoker->getDescribedFunctionTemplate();
10352 void *InsertPos = 0;
10353 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10354 DeducedTemplateArgs->data(),
10355 DeducedTemplateArgs->size(),
10356 InsertPos);
10357 assert(InvokeSpec &&
10358 "Must have a corresponding static invoker specialization");
10359 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10360 }
10361 // Construct the body of the conversion function { return __invoke; }.
10362 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10363 VK_LValue, Conv->getLocation()).take();
10364 assert(FunctionRef && "Can't refer to __invoke function?");
10365 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10366 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10367 Conv->getLocation(),
10368 Conv->getLocation()));
10369
10370 Conv->markUsed(Context);
10371 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010372
Faisal Vali571df122013-09-29 08:45:24 +000010373 // Fill in the __invoke function with a dummy implementation. IR generation
10374 // will fill in the actual details.
10375 Invoker->markUsed(Context);
10376 Invoker->setReferenced();
10377 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10378
Douglas Gregord3b672c2012-02-16 01:06:16 +000010379 if (ASTMutationListener *L = getASTMutationListener()) {
10380 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010381 L->CompletedImplicitDefinition(Invoker);
10382 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010383}
10384
Faisal Vali571df122013-09-29 08:45:24 +000010385
10386
Douglas Gregord3b672c2012-02-16 01:06:16 +000010387void Sema::DefineImplicitLambdaToBlockPointerConversion(
10388 SourceLocation CurrentLocation,
10389 CXXConversionDecl *Conv)
10390{
Faisal Vali850da1a2013-09-29 17:08:32 +000010391 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010392
Eli Friedman276dd182013-09-05 00:02:25 +000010393 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010394
Eli Friedmaneaf34142012-10-18 20:14:08 +000010395 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010396 DiagnosticErrorTrap Trap(Diags);
10397
Douglas Gregored90df32012-02-22 05:02:47 +000010398 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010399 Expr *This = ActOnCXXThis(CurrentLocation).take();
10400 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010401
Eli Friedman98b01ed2012-03-01 04:01:32 +000010402 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10403 Conv->getLocation(),
10404 Conv, DerefThis);
10405
10406 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10407 // behavior. Note that only the general conversion function does this
10408 // (since it's unusable otherwise); in the case where we inline the
10409 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010410 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010411 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10412 CK_CopyAndAutoreleaseBlockObject,
10413 BuildBlock.get(), 0, VK_RValue);
10414
10415 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010416 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010417 Conv->setInvalidDecl();
10418 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010419 }
Douglas Gregored90df32012-02-22 05:02:47 +000010420
Douglas Gregored90df32012-02-22 05:02:47 +000010421 // Create the return statement that returns the block from the conversion
10422 // function.
Eli Friedman98b01ed2012-03-01 04:01:32 +000010423 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010424 if (Return.isInvalid()) {
10425 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10426 Conv->setInvalidDecl();
10427 return;
10428 }
10429
10430 // Set the body of the conversion function.
10431 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010432 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010433 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010434 Conv->getLocation()));
10435
Douglas Gregored90df32012-02-22 05:02:47 +000010436 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010437 if (ASTMutationListener *L = getASTMutationListener()) {
10438 L->CompletedImplicitDefinition(Conv);
10439 }
10440}
10441
Douglas Gregord2f70072012-03-10 06:53:13 +000010442/// \brief Determine whether the given list arguments contains exactly one
10443/// "real" (non-default) argument.
10444static bool hasOneRealArgument(MultiExprArg Args) {
10445 switch (Args.size()) {
10446 case 0:
10447 return false;
10448
10449 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010450 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010451 return false;
10452
10453 // fall through
10454 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010455 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010456 }
10457
10458 return false;
10459}
10460
John McCalldadc5752010-08-24 06:29:42 +000010461ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010462Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010463 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010464 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010465 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010466 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010467 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010468 unsigned ConstructKind,
10469 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010470 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010471
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010472 // C++0x [class.copy]p34:
10473 // When certain criteria are met, an implementation is allowed to
10474 // omit the copy/move construction of a class object, even if the
10475 // copy/move constructor and/or destructor for the object have
10476 // side effects. [...]
10477 // - when a temporary class object that has not been bound to a
10478 // reference (12.2) would be copied/moved to a class object
10479 // with the same cv-unqualified type, the copy/move operation
10480 // can be omitted by constructing the temporary object
10481 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010482 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010483 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010484 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010485 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010486 }
Mike Stump11289f42009-09-09 15:08:12 +000010487
10488 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010489 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010490 IsListInitialization, RequiresZeroInit,
10491 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010492}
10493
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010494/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10495/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010496ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010497Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10498 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010499 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010500 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010501 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010502 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010503 unsigned ConstructKind,
10504 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010505 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010506 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010507 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010508 HadMultipleCandidates,
10509 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010510 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10511 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010512}
10513
John McCall03c48482010-02-02 09:10:11 +000010514void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010515 if (VD->isInvalidDecl()) return;
10516
John McCall03c48482010-02-02 09:10:11 +000010517 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010518 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010519 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010520 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010521
Chandler Carruth86d17d32011-03-27 21:26:48 +000010522 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010523 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010524 CheckDestructorAccess(VD->getLocation(), Destructor,
10525 PDiag(diag::err_access_dtor_var)
10526 << VD->getDeclName()
10527 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010528 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010529
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010530 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010531 if (!VD->hasGlobalStorage()) return;
10532
10533 // Emit warning for non-trivial dtor in global scope (a real global,
10534 // class-static, function-static).
10535 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10536
10537 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010538 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000010539 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010540}
10541
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010542/// \brief Given a constructor and the set of arguments provided for the
10543/// constructor, convert the arguments and add any required default arguments
10544/// to form a proper call to this constructor.
10545///
10546/// \returns true if an error occurred, false otherwise.
10547bool
10548Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10549 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010550 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010551 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010552 bool AllowExplicit,
10553 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010554 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10555 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010556 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010557
10558 const FunctionProtoType *Proto
10559 = Constructor->getType()->getAs<FunctionProtoType>();
10560 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010561 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010562
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010563 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010564 if (NumArgs < NumParams)
10565 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010566 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010567 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010568
10569 VariadicCallType CallType =
10570 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010571 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010572 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010573 Proto, 0,
10574 llvm::makeArrayRef(Args, NumArgs),
10575 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010576 CallType, AllowExplicit,
10577 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010578 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010579
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010580 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010581
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010582 CheckConstructorCall(Constructor,
10583 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10584 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010585 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010586
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010587 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010588}
10589
Anders Carlssone363c8e2009-12-12 00:32:00 +000010590static inline bool
10591CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10592 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010593 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010594 if (isa<NamespaceDecl>(DC)) {
10595 return SemaRef.Diag(FnDecl->getLocation(),
10596 diag::err_operator_new_delete_declared_in_namespace)
10597 << FnDecl->getDeclName();
10598 }
10599
10600 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010601 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010602 return SemaRef.Diag(FnDecl->getLocation(),
10603 diag::err_operator_new_delete_declared_static)
10604 << FnDecl->getDeclName();
10605 }
10606
Anders Carlsson60659a82009-12-12 02:43:16 +000010607 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010608}
10609
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010610static inline bool
10611CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10612 CanQualType ExpectedResultType,
10613 CanQualType ExpectedFirstParamType,
10614 unsigned DependentParamTypeDiag,
10615 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010616 QualType ResultType =
10617 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010618
10619 // Check that the result type is not dependent.
10620 if (ResultType->isDependentType())
10621 return SemaRef.Diag(FnDecl->getLocation(),
10622 diag::err_operator_new_delete_dependent_result_type)
10623 << FnDecl->getDeclName() << ExpectedResultType;
10624
10625 // Check that the result type is what we expect.
10626 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10627 return SemaRef.Diag(FnDecl->getLocation(),
10628 diag::err_operator_new_delete_invalid_result_type)
10629 << FnDecl->getDeclName() << ExpectedResultType;
10630
10631 // A function template must have at least 2 parameters.
10632 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10633 return SemaRef.Diag(FnDecl->getLocation(),
10634 diag::err_operator_new_delete_template_too_few_parameters)
10635 << FnDecl->getDeclName();
10636
10637 // The function decl must have at least 1 parameter.
10638 if (FnDecl->getNumParams() == 0)
10639 return SemaRef.Diag(FnDecl->getLocation(),
10640 diag::err_operator_new_delete_too_few_parameters)
10641 << FnDecl->getDeclName();
10642
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010643 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010644 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10645 if (FirstParamType->isDependentType())
10646 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10647 << FnDecl->getDeclName() << ExpectedFirstParamType;
10648
10649 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010650 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010651 ExpectedFirstParamType)
10652 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10653 << FnDecl->getDeclName() << ExpectedFirstParamType;
10654
10655 return false;
10656}
10657
Anders Carlsson12308f42009-12-11 23:23:22 +000010658static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010659CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010660 // C++ [basic.stc.dynamic.allocation]p1:
10661 // A program is ill-formed if an allocation function is declared in a
10662 // namespace scope other than global scope or declared static in global
10663 // scope.
10664 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10665 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010666
10667 CanQualType SizeTy =
10668 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10669
10670 // C++ [basic.stc.dynamic.allocation]p1:
10671 // The return type shall be void*. The first parameter shall have type
10672 // std::size_t.
10673 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10674 SizeTy,
10675 diag::err_operator_new_dependent_param_type,
10676 diag::err_operator_new_param_type))
10677 return true;
10678
10679 // C++ [basic.stc.dynamic.allocation]p1:
10680 // The first parameter shall not have an associated default argument.
10681 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010682 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010683 diag::err_operator_new_default_arg)
10684 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10685
10686 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010687}
10688
10689static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010690CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010691 // C++ [basic.stc.dynamic.deallocation]p1:
10692 // A program is ill-formed if deallocation functions are declared in a
10693 // namespace scope other than global scope or declared static in global
10694 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010695 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10696 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010697
10698 // C++ [basic.stc.dynamic.deallocation]p2:
10699 // Each deallocation function shall return void and its first parameter
10700 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010701 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10702 SemaRef.Context.VoidPtrTy,
10703 diag::err_operator_delete_dependent_param_type,
10704 diag::err_operator_delete_param_type))
10705 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010706
Anders Carlsson12308f42009-12-11 23:23:22 +000010707 return false;
10708}
10709
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010710/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10711/// of this overloaded operator is well-formed. If so, returns false;
10712/// otherwise, emits appropriate diagnostics and returns true.
10713bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010714 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010715 "Expected an overloaded operator declaration");
10716
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010717 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10718
Mike Stump11289f42009-09-09 15:08:12 +000010719 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010720 // The allocation and deallocation functions, operator new,
10721 // operator new[], operator delete and operator delete[], are
10722 // described completely in 3.7.3. The attributes and restrictions
10723 // found in the rest of this subclause do not apply to them unless
10724 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010725 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010726 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010727
Anders Carlsson22f443f2009-12-12 00:26:23 +000010728 if (Op == OO_New || Op == OO_Array_New)
10729 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010730
10731 // C++ [over.oper]p6:
10732 // An operator function shall either be a non-static member
10733 // function or be a non-member function and have at least one
10734 // parameter whose type is a class, a reference to a class, an
10735 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010736 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10737 if (MethodDecl->isStatic())
10738 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010739 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010740 } else {
10741 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010742 for (auto Param : FnDecl->params()) {
10743 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010744 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10745 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010746 ClassOrEnumParam = true;
10747 break;
10748 }
10749 }
10750
Douglas Gregord69246b2008-11-17 16:14:12 +000010751 if (!ClassOrEnumParam)
10752 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010753 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010754 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010755 }
10756
10757 // C++ [over.oper]p8:
10758 // An operator function cannot have default arguments (8.3.6),
10759 // except where explicitly stated below.
10760 //
Mike Stump11289f42009-09-09 15:08:12 +000010761 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010762 // (C++ [over.call]p1).
10763 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010764 for (auto Param : FnDecl->params()) {
10765 if (Param->hasDefaultArg())
10766 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010767 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010768 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010769 }
10770 }
10771
Douglas Gregor6cf08062008-11-10 13:38:07 +000010772 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10773 { false, false, false }
10774#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10775 , { Unary, Binary, MemberOnly }
10776#include "clang/Basic/OperatorKinds.def"
10777 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010778
Douglas Gregor6cf08062008-11-10 13:38:07 +000010779 bool CanBeUnaryOperator = OperatorUses[Op][0];
10780 bool CanBeBinaryOperator = OperatorUses[Op][1];
10781 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010782
10783 // C++ [over.oper]p8:
10784 // [...] Operator functions cannot have more or fewer parameters
10785 // than the number required for the corresponding operator, as
10786 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010787 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010788 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010789 if (Op != OO_Call &&
10790 ((NumParams == 1 && !CanBeUnaryOperator) ||
10791 (NumParams == 2 && !CanBeBinaryOperator) ||
10792 (NumParams < 1) || (NumParams > 2))) {
10793 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010794 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010795 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010796 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010797 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010798 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010799 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010800 assert(CanBeBinaryOperator &&
10801 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010802 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010803 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010804
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010805 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010806 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010807 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010808
Douglas Gregord69246b2008-11-17 16:14:12 +000010809 // Overloaded operators other than operator() cannot be variadic.
10810 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010811 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010812 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010813 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010814 }
10815
10816 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010817 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10818 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010819 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010820 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010821 }
10822
10823 // C++ [over.inc]p1:
10824 // The user-defined function called operator++ implements the
10825 // prefix and postfix ++ operator. If this function is a member
10826 // function with no parameters, or a non-member function with one
10827 // parameter of class or enumeration type, it defines the prefix
10828 // increment operator ++ for objects of that type. If the function
10829 // is a member function with one parameter (which shall be of type
10830 // int) or a non-member function with two parameters (the second
10831 // of which shall be of type int), it defines the postfix
10832 // increment operator ++ for objects of that type.
10833 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10834 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000010835 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010836
Richard Smith538b52a2014-01-30 22:24:05 +000010837 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10838 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000010839 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010840 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010841 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010842 }
10843
Douglas Gregord69246b2008-11-17 16:14:12 +000010844 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010845}
Chris Lattner3b024a32008-12-17 07:09:26 +000010846
Alexis Huntc88db062010-01-13 09:01:02 +000010847/// CheckLiteralOperatorDeclaration - Check whether the declaration
10848/// of this literal operator function is well-formed. If so, returns
10849/// false; otherwise, emits appropriate diagnostics and returns true.
10850bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010851 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010852 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10853 << FnDecl->getDeclName();
10854 return true;
10855 }
10856
Richard Smith72eebee2012-03-04 09:41:16 +000010857 if (FnDecl->isExternC()) {
10858 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10859 return true;
10860 }
10861
Alexis Huntc88db062010-01-13 09:01:02 +000010862 bool Valid = false;
10863
Richard Smithbcc22fc2012-03-09 08:00:36 +000010864 // This might be the definition of a literal operator template.
10865 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10866 // This might be a specialization of a literal operator template.
10867 if (!TpDecl)
10868 TpDecl = FnDecl->getPrimaryTemplate();
10869
Richard Smithb8b41d32013-10-07 19:57:58 +000010870 // template <char...> type operator "" name() and
10871 // template <class T, T...> type operator "" name() are the only valid
10872 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010873 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010874 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000010875 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000010876 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10877 if (Params->size() == 1) {
10878 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010879 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010880
Alexis Hunt7dd26172010-04-07 23:11:06 +000010881 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010882 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10883 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10884 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000010885 } else if (Params->size() == 2) {
10886 TemplateTypeParmDecl *PmType =
10887 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10888 NonTypeTemplateParmDecl *PmArgs =
10889 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10890
10891 // The second template parameter must be a parameter pack with the
10892 // first template parameter as its type.
10893 if (PmType && PmArgs &&
10894 !PmType->isTemplateParameterPack() &&
10895 PmArgs->isTemplateParameterPack()) {
10896 const TemplateTypeParmType *TArgs =
10897 PmArgs->getType()->getAs<TemplateTypeParmType>();
10898 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10899 TArgs->getIndex() == PmType->getIndex()) {
10900 Valid = true;
10901 if (ActiveTemplateInstantiations.empty())
10902 Diag(FnDecl->getLocation(),
10903 diag::ext_string_literal_operator_template);
10904 }
10905 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000010906 }
10907 }
Richard Smith72eebee2012-03-04 09:41:16 +000010908 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010909 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010910 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10911
Richard Smith72eebee2012-03-04 09:41:16 +000010912 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010913
Alexis Hunt079a6f72010-04-07 22:57:35 +000010914 // unsigned long long int, long double, and any character type are allowed
10915 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010916 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10917 Context.hasSameType(T, Context.LongDoubleTy) ||
10918 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010919 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010920 Context.hasSameType(T, Context.Char16Ty) ||
10921 Context.hasSameType(T, Context.Char32Ty)) {
10922 if (++Param == FnDecl->param_end())
10923 Valid = true;
10924 goto FinishedParams;
10925 }
10926
Alexis Hunt079a6f72010-04-07 22:57:35 +000010927 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000010928 const PointerType *PT = T->getAs<PointerType>();
10929 if (!PT)
10930 goto FinishedParams;
10931 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000010932 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000010933 goto FinishedParams;
10934 T = T.getUnqualifiedType();
10935
10936 // Move on to the second parameter;
10937 ++Param;
10938
10939 // If there is no second parameter, the first must be a const char *
10940 if (Param == FnDecl->param_end()) {
10941 if (Context.hasSameType(T, Context.CharTy))
10942 Valid = true;
10943 goto FinishedParams;
10944 }
10945
10946 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10947 // are allowed as the first parameter to a two-parameter function
10948 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010949 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010950 Context.hasSameType(T, Context.Char16Ty) ||
10951 Context.hasSameType(T, Context.Char32Ty)))
10952 goto FinishedParams;
10953
10954 // The second and final parameter must be an std::size_t
10955 T = (*Param)->getType().getUnqualifiedType();
10956 if (Context.hasSameType(T, Context.getSizeType()) &&
10957 ++Param == FnDecl->param_end())
10958 Valid = true;
10959 }
10960
10961 // FIXME: This diagnostic is absolutely terrible.
10962FinishedParams:
10963 if (!Valid) {
10964 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10965 << FnDecl->getDeclName();
10966 return true;
10967 }
10968
Richard Smith768cecc2012-03-09 08:16:22 +000010969 // A parameter-declaration-clause containing a default argument is not
10970 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010971 for (auto Param : FnDecl->params()) {
10972 if (Param->hasDefaultArg()) {
10973 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000010974 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010975 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000010976 break;
10977 }
10978 }
10979
Richard Smith0df56f42012-03-08 02:39:21 +000010980 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000010981 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10982 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000010983 // C++11 [usrlit.suffix]p1:
10984 // Literal suffix identifiers that do not start with an underscore
10985 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000010986 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10987 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000010988 }
Richard Smith0df56f42012-03-08 02:39:21 +000010989
Alexis Huntc88db062010-01-13 09:01:02 +000010990 return false;
10991}
10992
Douglas Gregor07665a62009-01-05 19:45:36 +000010993/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10994/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000010995/// the '{'. ExternLoc is the location of the 'extern', Lang is the
10996/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000010997/// the '{' brace. Otherwise, this linkage specification does not
10998/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000010999Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011000 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011001 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011002 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11003 if (!Lit->isAscii()) {
11004 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11005 << LangStr->getSourceRange();
11006 return 0;
11007 }
11008
11009 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011010 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011011 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011012 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011013 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011014 Language = LinkageSpecDecl::lang_cxx;
11015 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011016 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11017 << LangStr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011018 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000011019 }
Mike Stump11289f42009-09-09 15:08:12 +000011020
Chris Lattner438e5012008-12-17 07:13:27 +000011021 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011022
Richard Smith4ee696d2014-02-17 23:25:27 +000011023 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11024 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011025 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011026 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011027 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011028 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011029}
11030
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011031/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011032/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11033/// valid, it's the position of the closing '}' brace in a linkage
11034/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011035Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011036 Decl *LinkageSpec,
11037 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011038 if (RBraceLoc.isValid()) {
11039 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11040 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011041 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011042 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011043 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011044}
11045
Michael Han84324352013-02-22 17:15:32 +000011046Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11047 AttributeList *AttrList,
11048 SourceLocation SemiLoc) {
11049 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11050 // Attribute declarations appertain to empty declaration so we handle
11051 // them here.
11052 if (AttrList)
11053 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011054
Michael Han84324352013-02-22 17:15:32 +000011055 CurContext->addDecl(ED);
11056 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011057}
11058
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011059/// \brief Perform semantic analysis for the variable declaration that
11060/// occurs within a C++ catch clause, returning the newly-created
11061/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011062VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011063 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011064 SourceLocation StartLoc,
11065 SourceLocation Loc,
11066 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011067 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011068 QualType ExDeclType = TInfo->getType();
11069
Sebastian Redl54c04d42008-12-22 19:15:10 +000011070 // Arrays and functions decay.
11071 if (ExDeclType->isArrayType())
11072 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11073 else if (ExDeclType->isFunctionType())
11074 ExDeclType = Context.getPointerType(ExDeclType);
11075
11076 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11077 // The exception-declaration shall not denote a pointer or reference to an
11078 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011079 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011080 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011081 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011082 Invalid = true;
11083 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011084
Sebastian Redl54c04d42008-12-22 19:15:10 +000011085 QualType BaseType = ExDeclType;
11086 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011087 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011088 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011089 BaseType = Ptr->getPointeeType();
11090 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011091 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011092 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011093 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011094 BaseType = Ref->getPointeeType();
11095 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011096 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011097 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011098 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011099 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011100 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011101
Mike Stump11289f42009-09-09 15:08:12 +000011102 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011103 RequireNonAbstractType(Loc, ExDeclType,
11104 diag::err_abstract_type_in_decl,
11105 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011106 Invalid = true;
11107
John McCall2ca705e2010-07-24 00:37:23 +000011108 // Only the non-fragile NeXT runtime currently supports C++ catches
11109 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011110 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011111 QualType T = ExDeclType;
11112 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11113 T = RT->getPointeeType();
11114
11115 if (T->isObjCObjectType()) {
11116 Diag(Loc, diag::err_objc_object_catch);
11117 Invalid = true;
11118 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011119 // FIXME: should this be a test for macosx-fragile specifically?
11120 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011121 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011122 }
11123 }
11124
Abramo Bagnaradff19302011-03-08 08:55:46 +000011125 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011126 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011127 ExDecl->setExceptionVariable(true);
11128
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011129 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011130 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011131 Invalid = true;
11132
Douglas Gregor750734c2011-07-06 18:14:43 +000011133 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011134 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011135 // Insulate this from anything else we might currently be parsing.
11136 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11137
Douglas Gregor6de584c2010-03-05 23:38:39 +000011138 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011139 // The object declared in an exception-declaration or, if the
11140 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011141 // copy-initialized (8.5) from the exception object. [...]
11142 // The object is destroyed when the handler exits, after the destruction
11143 // of any automatic objects initialized within the handler.
11144 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011145 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011146 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011147 QualType initType = ExDeclType;
11148
11149 InitializedEntity entity =
11150 InitializedEntity::InitializeVariable(ExDecl);
11151 InitializationKind initKind =
11152 InitializationKind::CreateCopy(Loc, SourceLocation());
11153
11154 Expr *opaqueValue =
11155 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011156 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11157 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011158 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011159 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011160 else {
11161 // If the constructor used was non-trivial, set this as the
11162 // "initializer".
Nick Lewycky0f292892013-09-22 10:06:57 +000011163 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011164 if (!construct->getConstructor()->isTrivial()) {
11165 Expr *init = MaybeCreateExprWithCleanups(construct);
11166 ExDecl->setInit(init);
11167 }
11168
11169 // And make sure it's destructable.
11170 FinalizeVarWithDestructor(ExDecl, recordType);
11171 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011172 }
11173 }
11174
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011175 if (Invalid)
11176 ExDecl->setInvalidDecl();
11177
11178 return ExDecl;
11179}
11180
11181/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11182/// handler.
John McCall48871652010-08-21 09:40:31 +000011183Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011184 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011185 bool Invalid = D.isInvalidType();
11186
11187 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011188 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11189 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011190 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11191 D.getIdentifierLoc());
11192 Invalid = true;
11193 }
11194
Sebastian Redl54c04d42008-12-22 19:15:10 +000011195 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011196 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011197 LookupOrdinaryName,
11198 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011199 // The scope should be freshly made just for us. There is just no way
11200 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000011201 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000011202 if (PrevDecl->isTemplateParameter()) {
11203 // Maybe we will complain about the shadowed template parameter.
11204 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000011205 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011206 }
11207 }
11208
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011209 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011210 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11211 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011212 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011213 }
11214
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011215 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011216 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011217 D.getIdentifierLoc(),
11218 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011219 if (Invalid)
11220 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011221
Sebastian Redl54c04d42008-12-22 19:15:10 +000011222 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011223 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011224 PushOnScopeChains(ExDecl, S);
11225 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011226 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011227
Douglas Gregor758a8692009-06-17 21:51:59 +000011228 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011229 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011230}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011231
Abramo Bagnaraea947882011-03-08 16:41:52 +000011232Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011233 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011234 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011235 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011236 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011237
Richard Smithded9c2e2012-07-11 22:37:56 +000011238 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11239 return 0;
11240
11241 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11242 AssertMessage, RParenLoc, false);
11243}
11244
11245Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11246 Expr *AssertExpr,
11247 StringLiteral *AssertMessage,
11248 SourceLocation RParenLoc,
11249 bool Failed) {
11250 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11251 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011252 // In a static_assert-declaration, the constant-expression shall be a
11253 // constant expression that can be contextually converted to bool.
11254 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11255 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011256 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011257
Richard Smith902ca212011-12-14 23:32:26 +000011258 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011259 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011260 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011261 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011262 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011263
Richard Smithded9c2e2012-07-11 22:37:56 +000011264 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011265 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011266 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000011267 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011268 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011269 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011270 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011271 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011272 }
Mike Stump11289f42009-09-09 15:08:12 +000011273
Abramo Bagnaraea947882011-03-08 16:41:52 +000011274 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011275 AssertExpr, AssertMessage, RParenLoc,
11276 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011277
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011278 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011279 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011280}
Sebastian Redlf769df52009-03-24 22:27:57 +000011281
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011282/// \brief Perform semantic analysis of the given friend type declaration.
11283///
11284/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011285FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011286 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011287 TypeSourceInfo *TSInfo) {
11288 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11289
11290 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011291 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011292
Richard Smithc8239732011-10-18 21:39:00 +000011293 // C++03 [class.friend]p2:
11294 // An elaborated-type-specifier shall be used in a friend declaration
11295 // for a class.*
11296 //
11297 // * The class-key of the elaborated-type-specifier is required.
11298 if (!ActiveTemplateInstantiations.empty()) {
11299 // Do not complain about the form of friend template types during
11300 // template instantiation; we will already have complained when the
11301 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011302 } else {
11303 if (!T->isElaboratedTypeSpecifier()) {
11304 // If we evaluated the type to a record type, suggest putting
11305 // a tag in front.
11306 if (const RecordType *RT = T->getAs<RecordType>()) {
11307 RecordDecl *RD = RT->getDecl();
Richard Smithc8239732011-10-18 21:39:00 +000011308
Nick Lewycky36722d22013-02-06 05:59:33 +000011309 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smithc8239732011-10-18 21:39:00 +000011310
Nick Lewycky36722d22013-02-06 05:59:33 +000011311 Diag(TypeRange.getBegin(),
11312 getLangOpts().CPlusPlus11 ?
11313 diag::warn_cxx98_compat_unelaborated_friend_type :
11314 diag::ext_unelaborated_friend_type)
11315 << (unsigned) RD->getTagKind()
11316 << T
11317 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11318 InsertionText);
11319 } else {
11320 Diag(FriendLoc,
11321 getLangOpts().CPlusPlus11 ?
11322 diag::warn_cxx98_compat_nonclass_type_friend :
11323 diag::ext_nonclass_type_friend)
11324 << T
11325 << TypeRange;
11326 }
11327 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011328 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011329 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011330 diag::warn_cxx98_compat_enum_friend :
11331 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011332 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011333 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011334 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011335
Nick Lewycky36722d22013-02-06 05:59:33 +000011336 // C++11 [class.friend]p3:
11337 // A friend declaration that does not declare a function shall have one
11338 // of the following forms:
11339 // friend elaborated-type-specifier ;
11340 // friend simple-type-specifier ;
11341 // friend typename-specifier ;
11342 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11343 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11344 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011345
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011346 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011347 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011348 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000011349 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011350}
11351
John McCallace48cd2010-10-19 01:40:49 +000011352/// Handle a friend tag declaration where the scope specifier was
11353/// templated.
11354Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11355 unsigned TagSpec, SourceLocation TagLoc,
11356 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011357 IdentifierInfo *Name,
11358 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011359 AttributeList *Attr,
11360 MultiTemplateParamsArg TempParamLists) {
11361 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11362
11363 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011364 bool Invalid = false;
11365
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011366 if (TemplateParameterList *TemplateParams =
11367 MatchTemplateParametersToScopeSpecifier(
11368 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11369 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011370 if (TemplateParams->size() > 0) {
11371 // This is a declaration of a class template.
11372 if (Invalid)
11373 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011374
Eric Christopher6f228b52011-07-21 05:34:24 +000011375 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11376 SS, Name, NameLoc, Attr,
11377 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011378 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011379 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011380 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000011381 } else {
11382 // The "template<>" header is extraneous.
11383 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11384 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11385 isExplicitSpecialization = true;
11386 }
11387 }
11388
11389 if (Invalid) return 0;
11390
John McCallace48cd2010-10-19 01:40:49 +000011391 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011392 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011393 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011394 isAllExplicitSpecializations = false;
11395 break;
11396 }
11397 }
11398
11399 // FIXME: don't ignore attributes.
11400
11401 // If it's explicit specializations all the way down, just forget
11402 // about the template header and build an appropriate non-templated
11403 // friend. TODO: for source fidelity, remember the headers.
11404 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011405 if (SS.isEmpty()) {
11406 bool Owned = false;
11407 bool IsDependent = false;
11408 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011409 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011410 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011411 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011412 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011413 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011414 /*UnderlyingType=*/TypeResult(),
11415 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011416 }
Richard Smith649c7b062014-01-08 00:56:48 +000011417
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011418 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011419 ElaboratedTypeKeyword Keyword
11420 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011421 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011422 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011423 if (T.isNull())
11424 return 0;
11425
11426 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11427 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011428 DependentNameTypeLoc TL =
11429 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011430 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011431 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011432 TL.setNameLoc(NameLoc);
11433 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011434 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011435 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011436 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011437 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011438 }
11439
11440 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011441 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011442 Friend->setAccess(AS_public);
11443 CurContext->addDecl(Friend);
11444 return Friend;
11445 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011446
11447 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11448
11449
John McCallace48cd2010-10-19 01:40:49 +000011450
11451 // Handle the case of a templated-scope friend class. e.g.
11452 // template <class T> class A<T>::B;
11453 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011454 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11455 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011456 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11457 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11458 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011459 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011460 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011461 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011462 TL.setNameLoc(NameLoc);
11463
11464 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011465 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011466 Friend->setAccess(AS_public);
11467 Friend->setUnsupportedFriend(true);
11468 CurContext->addDecl(Friend);
11469 return Friend;
11470}
11471
11472
John McCall11083da2009-09-16 22:47:08 +000011473/// Handle a friend type declaration. This works in tandem with
11474/// ActOnTag.
11475///
11476/// Notes on friend class templates:
11477///
11478/// We generally treat friend class declarations as if they were
11479/// declaring a class. So, for example, the elaborated type specifier
11480/// in a friend declaration is required to obey the restrictions of a
11481/// class-head (i.e. no typedefs in the scope chain), template
11482/// parameters are required to match up with simple template-ids, &c.
11483/// However, unlike when declaring a template specialization, it's
11484/// okay to refer to a template specialization without an empty
11485/// template parameter declaration, e.g.
11486/// friend class A<T>::B<unsigned>;
11487/// We permit this as a special case; if there are any template
11488/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011489/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011490Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011491 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011492 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011493
11494 assert(DS.isFriendSpecified());
11495 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11496
John McCall11083da2009-09-16 22:47:08 +000011497 // Try to convert the decl specifier to a type. This works for
11498 // friend templates because ActOnTag never produces a ClassTemplateDecl
11499 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011500 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011501 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11502 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011503 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011504 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011505
Douglas Gregor6c110f32010-12-16 01:14:37 +000011506 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11507 return 0;
11508
John McCall11083da2009-09-16 22:47:08 +000011509 // This is definitely an error in C++98. It's probably meant to
11510 // be forbidden in C++0x, too, but the specification is just
11511 // poorly written.
11512 //
11513 // The problem is with declarations like the following:
11514 // template <T> friend A<T>::foo;
11515 // where deciding whether a class C is a friend or not now hinges
11516 // on whether there exists an instantiation of A that causes
11517 // 'foo' to equal C. There are restrictions on class-heads
11518 // (which we declare (by fiat) elaborated friend declarations to
11519 // be) that makes this tractable.
11520 //
11521 // FIXME: handle "template <> friend class A<T>;", which
11522 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011523 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011524 Diag(Loc, diag::err_tagless_friend_type_template)
11525 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011526 return 0;
John McCall11083da2009-09-16 22:47:08 +000011527 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011528
John McCallaa74a0c2009-08-28 07:59:38 +000011529 // C++98 [class.friend]p1: A friend of a class is a function
11530 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011531 // This is fixed in DR77, which just barely didn't make the C++03
11532 // deadline. It's also a very silly restriction that seriously
11533 // affects inner classes and which nobody else seems to implement;
11534 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011535 //
11536 // But note that we could warn about it: it's always useless to
11537 // friend one of your own members (it's not, however, worthless to
11538 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011539
John McCall11083da2009-09-16 22:47:08 +000011540 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011541 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011542 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011543 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011544 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011545 TSI,
John McCall11083da2009-09-16 22:47:08 +000011546 DS.getFriendSpecLoc());
11547 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011548 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011549
11550 if (!D)
John McCall48871652010-08-21 09:40:31 +000011551 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011552
John McCall11083da2009-09-16 22:47:08 +000011553 D->setAccess(AS_public);
11554 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011555
John McCall48871652010-08-21 09:40:31 +000011556 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011557}
11558
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011559NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11560 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011561 const DeclSpec &DS = D.getDeclSpec();
11562
11563 assert(DS.isFriendSpecified());
11564 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11565
11566 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011567 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011568
11569 // C++ [class.friend]p1
11570 // A friend of a class is a function or class....
11571 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011572 // It *doesn't* see through dependent types, which is correct
11573 // according to [temp.arg.type]p3:
11574 // If a declaration acquires a function type through a
11575 // type dependent on a template-parameter and this causes
11576 // a declaration that does not use the syntactic form of a
11577 // function declarator to have a function type, the program
11578 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011579 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011580 Diag(Loc, diag::err_unexpected_friend);
11581
11582 // It might be worthwhile to try to recover by creating an
11583 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011584 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011585 }
11586
11587 // C++ [namespace.memdef]p3
11588 // - If a friend declaration in a non-local class first declares a
11589 // class or function, the friend class or function is a member
11590 // of the innermost enclosing namespace.
11591 // - The name of the friend is not found by simple name lookup
11592 // until a matching declaration is provided in that namespace
11593 // scope (either before or after the class declaration granting
11594 // friendship).
11595 // - If a friend function is called, its name may be found by the
11596 // name lookup that considers functions from namespaces and
11597 // classes associated with the types of the function arguments.
11598 // - When looking for a prior declaration of a class or a function
11599 // declared as a friend, scopes outside the innermost enclosing
11600 // namespace scope are not considered.
11601
John McCallde3fd222010-10-12 23:13:28 +000011602 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011603 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11604 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011605 assert(Name);
11606
Douglas Gregor6c110f32010-12-16 01:14:37 +000011607 // Check for unexpanded parameter packs.
11608 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11609 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11610 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11611 return 0;
11612
John McCall07e91c02009-08-06 02:15:43 +000011613 // The context we found the declaration in, or in which we should
11614 // create the declaration.
11615 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011616 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011617 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011618 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011619
Richard Smith114394f2013-08-09 04:35:01 +000011620 // There are five cases here.
11621 // - There's no scope specifier and we're in a local class. Only look
11622 // for functions declared in the immediately-enclosing block scope.
11623 // We recover from invalid scope qualifiers as if they just weren't there.
11624 FunctionDecl *FunctionContainingLocalClass = 0;
11625 if ((SS.isInvalid() || !SS.isSet()) &&
11626 (FunctionContainingLocalClass =
11627 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11628 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011629 // If a friend declaration appears in a local class and the name
11630 // specified is an unqualified name, a prior declaration is
11631 // looked up without considering scopes that are outside the
11632 // innermost enclosing non-class scope. For a friend function
11633 // declaration, if there is no prior declaration, the program is
11634 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011635
11636 // Find the innermost enclosing non-class scope. This is the block
11637 // scope containing the local class definition (or for a nested class,
11638 // the outer local class).
11639 DCScope = S->getFnParent();
11640
11641 // Look up the function name in the scope.
11642 Previous.clear(LookupLocalFriendName);
11643 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11644
11645 if (!Previous.empty()) {
11646 // All possible previous declarations must have the same context:
11647 // either they were declared at block scope or they are members of
11648 // one of the enclosing local classes.
11649 DC = Previous.getRepresentativeDecl()->getDeclContext();
11650 } else {
11651 // This is ill-formed, but provide the context that we would have
11652 // declared the function in, if we were permitted to, for error recovery.
11653 DC = FunctionContainingLocalClass;
11654 }
Richard Smith541b38b2013-09-20 01:15:31 +000011655 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011656
11657 // C++ [class.friend]p6:
11658 // A function can be defined in a friend declaration of a class if and
11659 // only if the class is a non-local class (9.8), the function name is
11660 // unqualified, and the function has namespace scope.
11661 if (D.isFunctionDefinition()) {
11662 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11663 }
11664
11665 // - There's no scope specifier, in which case we just go to the
11666 // appropriate scope and look for a function or function template
11667 // there as appropriate.
11668 } else if (SS.isInvalid() || !SS.isSet()) {
11669 // C++11 [namespace.memdef]p3:
11670 // If the name in a friend declaration is neither qualified nor
11671 // a template-id and the declaration is a function or an
11672 // elaborated-type-specifier, the lookup to determine whether
11673 // the entity has been previously declared shall not consider
11674 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011675 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011676
John McCallf7cfb222010-10-13 05:45:15 +000011677 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011678 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011679
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011680 // Skip class contexts. If someone can cite chapter and verse
11681 // for this behavior, that would be nice --- it's what GCC and
11682 // EDG do, and it seems like a reasonable intent, but the spec
11683 // really only says that checks for unqualified existing
11684 // declarations should stop at the nearest enclosing namespace,
11685 // not that they should only consider the nearest enclosing
11686 // namespace.
11687 while (DC->isRecord())
11688 DC = DC->getParent();
11689
11690 DeclContext *LookupDC = DC;
11691 while (LookupDC->isTransparentContext())
11692 LookupDC = LookupDC->getParent();
11693
11694 while (true) {
11695 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011696
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011697 if (!Previous.empty()) {
11698 DC = LookupDC;
11699 break;
John McCallf4776592010-10-14 22:22:28 +000011700 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011701
11702 if (isTemplateId) {
11703 if (isa<TranslationUnitDecl>(LookupDC)) break;
11704 } else {
11705 if (LookupDC->isFileContext()) break;
11706 }
11707 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011708 }
11709
John McCallccbc0322010-10-13 06:22:15 +000011710 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011711
John McCallde3fd222010-10-12 23:13:28 +000011712 // - There's a non-dependent scope specifier, in which case we
11713 // compute it and do a previous lookup there for a function
11714 // or function template.
11715 } else if (!SS.getScopeRep()->isDependent()) {
11716 DC = computeDeclContext(SS);
11717 if (!DC) return 0;
11718
11719 if (RequireCompleteDeclContext(SS, DC)) return 0;
11720
11721 LookupQualifiedName(Previous, DC);
11722
11723 // Ignore things found implicitly in the wrong scope.
11724 // TODO: better diagnostics for this case. Suggesting the right
11725 // qualified scope would be nice...
11726 LookupResult::Filter F = Previous.makeFilter();
11727 while (F.hasNext()) {
11728 NamedDecl *D = F.next();
11729 if (!DC->InEnclosingNamespaceSetOf(
11730 D->getDeclContext()->getRedeclContext()))
11731 F.erase();
11732 }
11733 F.done();
11734
11735 if (Previous.empty()) {
11736 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011737 Diag(Loc, diag::err_qualified_friend_not_found)
11738 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011739 return 0;
11740 }
11741
11742 // C++ [class.friend]p1: A friend of a class is a function or
11743 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011744 if (DC->Equals(CurContext))
11745 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011746 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011747 diag::warn_cxx98_compat_friend_is_member :
11748 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011749
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011750 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011751 // C++ [class.friend]p6:
11752 // A function can be defined in a friend declaration of a class if and
11753 // only if the class is a non-local class (9.8), the function name is
11754 // unqualified, and the function has namespace scope.
11755 SemaDiagnosticBuilder DB
11756 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11757
11758 DB << SS.getScopeRep();
11759 if (DC->isFileContext())
11760 DB << FixItHint::CreateRemoval(SS.getRange());
11761 SS.clear();
11762 }
John McCallde3fd222010-10-12 23:13:28 +000011763
11764 // - There's a scope specifier that does not match any template
11765 // parameter lists, in which case we use some arbitrary context,
11766 // create a method or method template, and wait for instantiation.
11767 // - There's a scope specifier that does match some template
11768 // parameter lists, which we don't handle right now.
11769 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011770 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011771 // C++ [class.friend]p6:
11772 // A function can be defined in a friend declaration of a class if and
11773 // only if the class is a non-local class (9.8), the function name is
11774 // unqualified, and the function has namespace scope.
11775 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11776 << SS.getScopeRep();
11777 }
11778
John McCallde3fd222010-10-12 23:13:28 +000011779 DC = CurContext;
11780 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011781 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011782
John McCallf7cfb222010-10-13 05:45:15 +000011783 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011784 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011785 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11786 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11787 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011788 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011789 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11790 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011791 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011792 }
John McCall07e91c02009-08-06 02:15:43 +000011793 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011794
Douglas Gregordd847ba2011-11-03 16:37:14 +000011795 // FIXME: This is an egregious hack to cope with cases where the scope stack
11796 // does not contain the declaration context, i.e., in an out-of-line
11797 // definition of a class.
11798 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11799 if (!DCScope) {
11800 FakeDCScope.setEntity(DC);
11801 DCScope = &FakeDCScope;
11802 }
Richard Smith114394f2013-08-09 04:35:01 +000011803
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011804 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011805 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011806 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011807 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011808
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011809 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011810
Richard Smith114394f2013-08-09 04:35:01 +000011811 // If we performed typo correction, we might have added a scope specifier
11812 // and changed the decl context.
11813 DC = ND->getDeclContext();
11814
John McCall759e32b2009-08-31 22:39:49 +000011815 // Add the function declaration to the appropriate lookup tables,
11816 // adjusting the redeclarations list as necessary. We don't
11817 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011818 //
John McCall759e32b2009-08-31 22:39:49 +000011819 // Also update the scope-based lookup if the target context's
11820 // lookup context is in lexical scope.
11821 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011822 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011823 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011824 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011825 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011826 }
John McCallaa74a0c2009-08-28 07:59:38 +000011827
11828 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011829 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011830 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011831 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011832 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011833
John McCalla0a96892012-08-10 03:15:35 +000011834 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011835 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011836 } else {
11837 if (DC->isRecord()) CheckFriendAccess(ND);
11838
John McCall2c2eb122010-10-16 06:59:13 +000011839 FunctionDecl *FD;
11840 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11841 FD = FTD->getTemplatedDecl();
11842 else
11843 FD = cast<FunctionDecl>(ND);
11844
David Majnemer502b0ed2013-06-25 23:09:30 +000011845 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11846 // default argument expression, that declaration shall be a definition
11847 // and shall be the only declaration of the function or function
11848 // template in the translation unit.
11849 if (functionDeclHasDefaultArgument(FD)) {
11850 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11851 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11852 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11853 } else if (!D.isFunctionDefinition())
11854 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11855 }
11856
John McCall2c2eb122010-10-16 06:59:13 +000011857 // Mark templated-scope function declarations as unsupported.
11858 if (FD->getNumTemplateParameterLists())
11859 FrD->setUnsupportedFriend(true);
11860 }
John McCallde3fd222010-10-12 23:13:28 +000011861
John McCall48871652010-08-21 09:40:31 +000011862 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011863}
11864
John McCall48871652010-08-21 09:40:31 +000011865void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11866 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011867
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011868 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011869 if (!Fn) {
11870 Diag(DelLoc, diag::err_deleted_non_function);
11871 return;
11872 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011873
Douglas Gregorec9fd132012-01-14 16:38:05 +000011874 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011875 // Don't consider the implicit declaration we generate for explicit
11876 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000011877 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11878 Prev->getPreviousDecl()) &&
11879 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011880 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000011881 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11882 Prev->isImplicit() ? diag::note_previous_implicit_declaration
11883 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000011884 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011885 // If the declaration wasn't the first, we delete the function anyway for
11886 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011887 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011888 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011889
11890 if (Fn->isDeleted())
11891 return;
11892
11893 // See if we're deleting a function which is already known to override a
11894 // non-deleted virtual function.
11895 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11896 bool IssuedDiagnostic = false;
11897 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11898 E = MD->end_overridden_methods();
11899 I != E; ++I) {
11900 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11901 if (!IssuedDiagnostic) {
11902 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11903 IssuedDiagnostic = true;
11904 }
11905 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11906 }
11907 }
11908 }
11909
Richard Smithb63b6ee2014-01-22 01:43:19 +000011910 // C++11 [basic.start.main]p3:
11911 // A program that defines main as deleted [...] is ill-formed.
11912 if (Fn->isMain())
11913 Diag(DelLoc, diag::err_deleted_main);
11914
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011915 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011916}
Sebastian Redl4c018662009-04-27 21:33:24 +000011917
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011918void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011919 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011920
11921 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000011922 if (MD->getParent()->isDependentType()) {
11923 MD->setDefaulted();
11924 MD->setExplicitlyDefaulted();
11925 return;
11926 }
11927
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011928 CXXSpecialMember Member = getSpecialMember(MD);
11929 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000011930 if (!MD->isInvalidDecl())
11931 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011932 return;
11933 }
11934
11935 MD->setDefaulted();
11936 MD->setExplicitlyDefaulted();
11937
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011938 // If this definition appears within the record, do the checking when
11939 // the record is complete.
11940 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000011941 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011942 // Find the uninstantiated declaration that actually had the '= default'
11943 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000011944 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011945
Richard Smith3901dfe2013-03-27 00:22:47 +000011946 // If the method was defaulted on its first declaration, we will have
11947 // already performed the checking in CheckCompletedCXXClass. Such a
11948 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011949 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011950 return;
11951
Richard Smithd3b5c9082012-07-27 04:22:15 +000011952 CheckExplicitlyDefaultedSpecialMember(MD);
11953
Richard Smithbd305122012-12-11 01:14:52 +000011954 // The exception specification is needed because we are defining the
11955 // function.
11956 ResolveExceptionSpec(DefaultLoc,
11957 MD->getType()->castAs<FunctionProtoType>());
11958
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011959 if (MD->isInvalidDecl())
11960 return;
11961
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011962 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011963 case CXXDefaultConstructor:
11964 DefineImplicitDefaultConstructor(DefaultLoc,
11965 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000011966 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011967 case CXXCopyConstructor:
11968 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011969 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011970 case CXXCopyAssignment:
11971 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000011972 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011973 case CXXDestructor:
11974 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000011975 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011976 case CXXMoveConstructor:
11977 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000011978 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011979 case CXXMoveAssignment:
11980 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011981 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011982 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000011983 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011984 }
11985 } else {
11986 Diag(DefaultLoc, diag::err_default_special_members);
11987 }
11988}
11989
Sebastian Redl4c018662009-04-27 21:33:24 +000011990static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000011991 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000011992 Stmt *SubStmt = *CI;
11993 if (!SubStmt)
11994 continue;
11995 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011996 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000011997 diag::err_return_in_constructor_handler);
11998 if (!isa<Expr>(SubStmt))
11999 SearchForReturnInStmt(Self, SubStmt);
12000 }
12001}
12002
12003void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12004 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12005 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12006 SearchForReturnInStmt(*this, Handler);
12007 }
12008}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012009
David Blaikie68f71a32013-01-18 23:03:15 +000012010bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012011 const CXXMethodDecl *Old) {
12012 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12013 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12014
12015 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12016
12017 // If the calling conventions match, everything is fine
12018 if (NewCC == OldCC)
12019 return false;
12020
Hans Wennborg2545efe2013-12-11 17:42:11 +000012021 // If the calling conventions mismatch because the new function is static,
12022 // suppress the calling convention mismatch error; the error about static
12023 // function override (err_static_overrides_virtual from
12024 // Sema::CheckFunctionDeclaration) is more clear.
12025 if (New->getStorageClass() == SC_Static)
12026 return false;
12027
Reid Kleckner78af0702013-08-27 23:08:25 +000012028 Diag(New->getLocation(),
12029 diag::err_conflicting_overriding_cc_attributes)
12030 << New->getDeclName() << New->getType() << Old->getType();
12031 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12032 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012033}
12034
Mike Stump11289f42009-09-09 15:08:12 +000012035bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012036 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012037 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12038 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012039
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012040 if (Context.hasSameType(NewTy, OldTy) ||
12041 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012042 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012043
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012044 // Check if the return types are covariant
12045 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012046
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012047 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012048 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12049 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012050 NewClassTy = NewPT->getPointeeType();
12051 OldClassTy = OldPT->getPointeeType();
12052 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012053 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12054 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12055 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12056 NewClassTy = NewRT->getPointeeType();
12057 OldClassTy = OldRT->getPointeeType();
12058 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012059 }
12060 }
Mike Stump11289f42009-09-09 15:08:12 +000012061
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012062 // The return types aren't either both pointers or references to a class type.
12063 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012064 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012065 diag::err_different_return_type_for_overriding_virtual_function)
12066 << New->getDeclName() << NewTy << OldTy;
12067 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012068
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012069 return true;
12070 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012071
Anders Carlssone60365b2009-12-31 18:34:24 +000012072 // C++ [class.virtual]p6:
12073 // If the return type of D::f differs from the return type of B::f, the
12074 // class type in the return type of D::f shall be complete at the point of
12075 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012076 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12077 if (!RT->isBeingDefined() &&
12078 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012079 diag::err_covariant_return_incomplete,
12080 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012081 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012082 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012083
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012084 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012085 // Check if the new class derives from the old class.
12086 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12087 Diag(New->getLocation(),
12088 diag::err_covariant_return_not_derived)
12089 << New->getDeclName() << NewTy << OldTy;
12090 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12091 return true;
12092 }
Mike Stump11289f42009-09-09 15:08:12 +000012093
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012094 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012095 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012096 diag::err_covariant_return_inaccessible_base,
12097 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12098 // FIXME: Should this point to the return type?
12099 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000012100 // FIXME: this note won't trigger for delayed access control
12101 // diagnostics, and it's impossible to get an undelayed error
12102 // here from access control during the original parse because
12103 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012104 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12105 return true;
12106 }
12107 }
Mike Stump11289f42009-09-09 15:08:12 +000012108
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012109 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012110 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012111 Diag(New->getLocation(),
12112 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012113 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012114 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12115 return true;
12116 };
Mike Stump11289f42009-09-09 15:08:12 +000012117
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012118
12119 // The new class type must have the same or less qualifiers as the old type.
12120 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12121 Diag(New->getLocation(),
12122 diag::err_covariant_return_type_class_type_more_qualified)
12123 << New->getDeclName() << NewTy << OldTy;
12124 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12125 return true;
12126 };
Mike Stump11289f42009-09-09 15:08:12 +000012127
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012128 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012129}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012130
Douglas Gregor21920e372009-12-01 17:24:26 +000012131/// \brief Mark the given method pure.
12132///
12133/// \param Method the method to be marked pure.
12134///
12135/// \param InitRange the source range that covers the "0" initializer.
12136bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012137 SourceLocation EndLoc = InitRange.getEnd();
12138 if (EndLoc.isValid())
12139 Method->setRangeEnd(EndLoc);
12140
Douglas Gregor21920e372009-12-01 17:24:26 +000012141 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12142 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012143 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012144 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012145
12146 if (!Method->isInvalidDecl())
12147 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12148 << Method->getDeclName() << InitRange;
12149 return true;
12150}
12151
Douglas Gregor926410d2012-02-21 02:22:07 +000012152/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012153static bool isStaticDataMember(const Decl *D) {
12154 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12155 return Var->isStaticDataMember();
12156
12157 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012158}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012159
John McCall1f4ee7b2009-12-19 09:28:58 +000012160/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12161/// an initializer for the out-of-line declaration 'Dcl'. The scope
12162/// is a fresh scope pushed for just this purpose.
12163///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012164/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12165/// static data member of class X, names should be looked up in the scope of
12166/// class X.
John McCall48871652010-08-21 09:40:31 +000012167void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012168 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012169 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012170
Richard Smitha2302242013-12-05 07:51:02 +000012171 // We will always have a nested name specifier here, but this declaration
12172 // might not be out of line if the specifier names the current namespace:
12173 // extern int n;
12174 // int ::n = 0;
12175 if (D->isOutOfLine())
12176 EnterDeclaratorContext(S, D->getDeclContext());
12177
Douglas Gregor926410d2012-02-21 02:22:07 +000012178 // If we are parsing the initializer for a static data member, push a
12179 // new expression evaluation context that is associated with this static
12180 // data member.
12181 if (isStaticDataMember(D))
12182 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012183}
12184
12185/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012186/// initializer for the out-of-line declaration 'D'.
12187void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012188 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012189 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012190
Douglas Gregor926410d2012-02-21 02:22:07 +000012191 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012192 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012193
Richard Smitha2302242013-12-05 07:51:02 +000012194 if (D->isOutOfLine())
12195 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012196}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012197
12198/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12199/// C++ if/switch/while/for statement.
12200/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012201DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012202 // C++ 6.4p2:
12203 // The declarator shall not specify a function or an array.
12204 // The type-specifier-seq shall not contain typedef and shall not declare a
12205 // new class or enumeration.
12206 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12207 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012208
12209 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012210 if (!Dcl)
12211 return true;
12212
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012213 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12214 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012215 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012216 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012217 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012218
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012219 return Dcl;
12220}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012221
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012222void Sema::LoadExternalVTableUses() {
12223 if (!ExternalSource)
12224 return;
12225
12226 SmallVector<ExternalVTableUse, 4> VTables;
12227 ExternalSource->ReadUsedVTables(VTables);
12228 SmallVector<VTableUse, 4> NewUses;
12229 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12230 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12231 = VTablesUsed.find(VTables[I].Record);
12232 // Even if a definition wasn't required before, it may be required now.
12233 if (Pos != VTablesUsed.end()) {
12234 if (!Pos->second && VTables[I].DefinitionRequired)
12235 Pos->second = true;
12236 continue;
12237 }
12238
12239 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12240 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12241 }
12242
12243 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12244}
12245
Douglas Gregor88d292c2010-05-13 16:44:06 +000012246void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12247 bool DefinitionRequired) {
12248 // Ignore any vtable uses in unevaluated operands or for classes that do
12249 // not have a vtable.
12250 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012251 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012252 return;
12253
Douglas Gregor88d292c2010-05-13 16:44:06 +000012254 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012255 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012256 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12257 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12258 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12259 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012260 // If we already had an entry, check to see if we are promoting this vtable
12261 // to required a definition. If so, we need to reappend to the VTableUses
12262 // list, since we may have already processed the first entry.
12263 if (DefinitionRequired && !Pos.first->second) {
12264 Pos.first->second = true;
12265 } else {
12266 // Otherwise, we can early exit.
12267 return;
12268 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012269 } else {
12270 // The Microsoft ABI requires that we perform the destructor body
12271 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12272 // the deleting destructor is emitted with the vtable, not with the
12273 // destructor definition as in the Itanium ABI.
12274 // If it has a definition, we do the check at that point instead.
12275 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12276 Class->hasUserDeclaredDestructor() &&
12277 !Class->getDestructor()->isDefined() &&
12278 !Class->getDestructor()->isDeleted()) {
12279 CheckDestructor(Class->getDestructor());
12280 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012281 }
12282
12283 // Local classes need to have their virtual members marked
12284 // immediately. For all other classes, we mark their virtual members
12285 // at the end of the translation unit.
12286 if (Class->isLocalClass())
12287 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012288 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012289 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012290}
12291
Douglas Gregor88d292c2010-05-13 16:44:06 +000012292bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012293 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012294 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012295 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012296
Douglas Gregor88d292c2010-05-13 16:44:06 +000012297 // Note: The VTableUses vector could grow as a result of marking
12298 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012299 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012300 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012301 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012302 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012303 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012304 if (!Class)
12305 continue;
12306
12307 SourceLocation Loc = VTableUses[I].second;
12308
Richard Smithd3b5c9082012-07-27 04:22:15 +000012309 bool DefineVTable = true;
12310
Douglas Gregor88d292c2010-05-13 16:44:06 +000012311 // If this class has a key function, but that key function is
12312 // defined in another translation unit, we don't need to emit the
12313 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012314 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012315 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012316 // The key function is in another translation unit.
12317 DefineVTable = false;
12318 TemplateSpecializationKind TSK =
12319 KeyFunction->getTemplateSpecializationKind();
12320 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12321 TSK != TSK_ImplicitInstantiation &&
12322 "Instantiations don't have key functions");
12323 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012324 } else if (!KeyFunction) {
12325 // If we have a class with no key function that is the subject
12326 // of an explicit instantiation declaration, suppress the
12327 // vtable; it will live with the explicit instantiation
12328 // definition.
12329 bool IsExplicitInstantiationDeclaration
12330 = Class->getTemplateSpecializationKind()
12331 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012332 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012333 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012334 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012335 if (TSK == TSK_ExplicitInstantiationDeclaration)
12336 IsExplicitInstantiationDeclaration = true;
12337 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12338 IsExplicitInstantiationDeclaration = false;
12339 break;
12340 }
12341 }
12342
12343 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012344 DefineVTable = false;
12345 }
12346
12347 // The exception specifications for all virtual members may be needed even
12348 // if we are not providing an authoritative form of the vtable in this TU.
12349 // We may choose to emit it available_externally anyway.
12350 if (!DefineVTable) {
12351 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12352 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012353 }
12354
12355 // Mark all of the virtual members of this class as referenced, so
12356 // that we can build a vtable. Then, tell the AST consumer that a
12357 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012358 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012359 MarkVirtualMembersReferenced(Loc, Class);
12360 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12361 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12362
12363 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012364 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012365 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012366 const FunctionDecl *KeyFunctionDef = 0;
12367 if (!KeyFunction ||
12368 (KeyFunction->hasBody(KeyFunctionDef) &&
12369 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012370 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12371 TSK_ExplicitInstantiationDefinition
12372 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12373 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012374 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012375 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012376 VTableUses.clear();
12377
Douglas Gregor97509692011-04-22 22:25:37 +000012378 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012379}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012380
Richard Smithd3b5c9082012-07-27 04:22:15 +000012381void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12382 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012383 for (const auto *I : RD->methods())
12384 if (I->isVirtual() && !I->isPure())
12385 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012386}
12387
Rafael Espindola5b334082010-03-26 00:36:59 +000012388void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12389 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012390 // Mark all functions which will appear in RD's vtable as used.
12391 CXXFinalOverriderMap FinalOverriders;
12392 RD->getFinalOverriders(FinalOverriders);
12393 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12394 E = FinalOverriders.end();
12395 I != E; ++I) {
12396 for (OverridingMethods::const_iterator OI = I->second.begin(),
12397 OE = I->second.end();
12398 OI != OE; ++OI) {
12399 assert(OI->second.size() > 0 && "no final overrider");
12400 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012401
Richard Smith4ff9ff92012-07-07 06:59:51 +000012402 // C++ [basic.def.odr]p2:
12403 // [...] A virtual member function is used if it is not pure. [...]
12404 if (!Overrider->isPure())
12405 MarkFunctionReferenced(Loc, Overrider);
12406 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012407 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012408
12409 // Only classes that have virtual bases need a VTT.
12410 if (RD->getNumVBases() == 0)
12411 return;
12412
Aaron Ballman574705e2014-03-13 15:41:46 +000012413 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012414 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012415 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012416 if (Base->getNumVBases() == 0)
12417 continue;
12418 MarkVirtualMembersReferenced(Loc, Base);
12419 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012420}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012421
12422/// SetIvarInitializers - This routine builds initialization ASTs for the
12423/// Objective-C implementation whose ivars need be initialized.
12424void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012425 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012426 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012427 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012428 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012429 CollectIvarsToConstructOrDestruct(OID, ivars);
12430 if (ivars.empty())
12431 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012432 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012433 for (unsigned i = 0; i < ivars.size(); i++) {
12434 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012435 if (Field->isInvalidDecl())
12436 continue;
12437
Alexis Hunt1d792652011-01-08 20:30:50 +000012438 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012439 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12440 InitializationKind InitKind =
12441 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012442
12443 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12444 ExprResult MemberInit =
12445 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012446 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012447 // Note, MemberInit could actually come back empty if no initialization
12448 // is required (e.g., because it would call a trivial default constructor)
12449 if (!MemberInit.get() || MemberInit.isInvalid())
12450 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012451
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012452 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012453 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12454 SourceLocation(),
12455 MemberInit.takeAs<Expr>(),
12456 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012457 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012458
12459 // Be sure that the destructor is accessible and is marked as referenced.
12460 if (const RecordType *RecordTy
12461 = Context.getBaseElementType(Field->getType())
12462 ->getAs<RecordType>()) {
12463 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012464 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012465 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012466 CheckDestructorAccess(Field->getLocation(), Destructor,
12467 PDiag(diag::err_access_dtor_ivar)
12468 << Context.getBaseElementType(Field->getType()));
12469 }
12470 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012471 }
12472 ObjCImplementation->setIvarInitializers(Context,
12473 AllToInit.data(), AllToInit.size());
12474 }
12475}
Alexis Hunt6118d662011-05-04 05:57:24 +000012476
Alexis Hunt27a761d2011-05-04 23:29:54 +000012477static
12478void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12479 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12480 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12481 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12482 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012483 if (Ctor->isInvalidDecl())
12484 return;
12485
Richard Smith802c4b72012-08-23 06:16:52 +000012486 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12487
12488 // Target may not be determinable yet, for instance if this is a dependent
12489 // call in an uninstantiated template.
12490 if (Target) {
12491 const FunctionDecl *FNTarget = 0;
12492 (void)Target->hasBody(FNTarget);
12493 Target = const_cast<CXXConstructorDecl*>(
12494 cast_or_null<CXXConstructorDecl>(FNTarget));
12495 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012496
12497 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12498 // Avoid dereferencing a null pointer here.
12499 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12500
12501 if (!Current.insert(Canonical))
12502 return;
12503
12504 // We know that beyond here, we aren't chaining into a cycle.
12505 if (!Target || !Target->isDelegatingConstructor() ||
12506 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012507 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012508 Current.clear();
12509 // We've hit a cycle.
12510 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12511 Current.count(TCanonical)) {
12512 // If we haven't diagnosed this cycle yet, do so now.
12513 if (!Invalid.count(TCanonical)) {
12514 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012515 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012516 << Ctor;
12517
Richard Smith802c4b72012-08-23 06:16:52 +000012518 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012519 if (TCanonical != Canonical)
12520 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12521
12522 CXXConstructorDecl *C = Target;
12523 while (C->getCanonicalDecl() != Canonical) {
Richard Smith802c4b72012-08-23 06:16:52 +000012524 const FunctionDecl *FNTarget = 0;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012525 (void)C->getTargetConstructor()->hasBody(FNTarget);
12526 assert(FNTarget && "Ctor cycle through bodiless function");
12527
Richard Smith802c4b72012-08-23 06:16:52 +000012528 C = const_cast<CXXConstructorDecl*>(
12529 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012530 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12531 }
12532 }
12533
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012534 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012535 Current.clear();
12536 } else {
12537 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12538 }
12539}
12540
12541
Alexis Hunt6118d662011-05-04 05:57:24 +000012542void Sema::CheckDelegatingCtorCycles() {
12543 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12544
Douglas Gregorbae31202011-07-27 21:57:17 +000012545 for (DelegatingCtorDeclsType::iterator
12546 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012547 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012548 I != E; ++I)
12549 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012550
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012551 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12552 CE = Invalid.end();
12553 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012554 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012555}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012556
Douglas Gregor3024f072012-04-16 07:05:22 +000012557namespace {
12558 /// \brief AST visitor that finds references to the 'this' expression.
12559 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12560 Sema &S;
12561
12562 public:
12563 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12564
12565 bool VisitCXXThisExpr(CXXThisExpr *E) {
12566 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12567 << E->isImplicit();
12568 return false;
12569 }
12570 };
12571}
12572
12573bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12574 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12575 if (!TSInfo)
12576 return false;
12577
12578 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012579 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012580 if (!ProtoTL)
12581 return false;
12582
12583 // C++11 [expr.prim.general]p3:
12584 // [The expression this] shall not appear before the optional
12585 // cv-qualifier-seq and it shall not appear within the declaration of a
12586 // static member function (although its type and value category are defined
12587 // within a static member function as they are within a non-static member
12588 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012589 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012590 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012591 FindCXXThisExpr Finder(*this);
12592
12593 // If the return type came after the cv-qualifier-seq, check it now.
12594 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012595 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012596 return true;
12597
12598 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012599 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12600 return true;
12601
12602 return checkThisInStaticMemberFunctionAttributes(Method);
12603}
12604
12605bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12606 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12607 if (!TSInfo)
12608 return false;
12609
12610 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012611 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012612 if (!ProtoTL)
12613 return false;
12614
David Blaikie6adc78e2013-02-18 22:06:02 +000012615 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012616 FindCXXThisExpr Finder(*this);
12617
Douglas Gregor3024f072012-04-16 07:05:22 +000012618 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012619 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012620 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012621 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012622 case EST_DynamicNone:
12623 case EST_MSAny:
12624 case EST_None:
12625 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012626
Douglas Gregor3024f072012-04-16 07:05:22 +000012627 case EST_ComputedNoexcept:
12628 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12629 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012630
Douglas Gregor3024f072012-04-16 07:05:22 +000012631 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012632 for (const auto &E : Proto->exceptions()) {
12633 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012634 return true;
12635 }
12636 break;
12637 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012638
12639 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012640}
12641
12642bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12643 FindCXXThisExpr Finder(*this);
12644
12645 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012646 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012647 // FIXME: This should be emitted by tblgen.
12648 Expr *Arg = 0;
12649 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012650 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012651 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012652 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012653 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012654 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012655 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012656 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012657 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012658 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012659 Arg = ETLF->getSuccessValue();
12660 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012661 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012662 Arg = STLF->getSuccessValue();
12663 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000012664 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012665 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012666 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012667 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012668 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012669 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012670 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012671 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012672 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12673 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12674 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012675 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012676
12677 if (Arg && !Finder.TraverseStmt(Arg))
12678 return true;
12679
12680 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12681 if (!Finder.TraverseStmt(Args[I]))
12682 return true;
12683 }
12684 }
12685
12686 return false;
12687}
12688
Douglas Gregor433e0532012-04-16 18:27:27 +000012689void
12690Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12691 ArrayRef<ParsedType> DynamicExceptions,
12692 ArrayRef<SourceRange> DynamicExceptionRanges,
12693 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012694 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012695 FunctionProtoType::ExtProtoInfo &EPI) {
12696 Exceptions.clear();
12697 EPI.ExceptionSpecType = EST;
12698 if (EST == EST_Dynamic) {
12699 Exceptions.reserve(DynamicExceptions.size());
12700 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12701 // FIXME: Preserve type source info.
12702 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12703
12704 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12705 collectUnexpandedParameterPacks(ET, Unexpanded);
12706 if (!Unexpanded.empty()) {
12707 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12708 UPPC_ExceptionType,
12709 Unexpanded);
12710 continue;
12711 }
12712
12713 // Check that the type is valid for an exception spec, and
12714 // drop it if not.
12715 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12716 Exceptions.push_back(ET);
12717 }
12718 EPI.NumExceptions = Exceptions.size();
12719 EPI.Exceptions = Exceptions.data();
12720 return;
12721 }
12722
12723 if (EST == EST_ComputedNoexcept) {
12724 // If an error occurred, there's no expression here.
12725 if (NoexceptExpr) {
12726 assert((NoexceptExpr->isTypeDependent() ||
12727 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12728 Context.BoolTy) &&
12729 "Parser should have made sure that the expression is boolean");
12730 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12731 EPI.ExceptionSpecType = EST_BasicNoexcept;
12732 return;
12733 }
12734
12735 if (!NoexceptExpr->isValueDependent())
12736 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012737 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012738 /*AllowFold*/ false).take();
12739 EPI.NoexceptExpr = NoexceptExpr;
12740 }
12741 return;
12742 }
12743}
12744
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012745/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12746Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12747 // Implicitly declared functions (e.g. copy constructors) are
12748 // __host__ __device__
12749 if (D->isImplicit())
12750 return CFT_HostDevice;
12751
12752 if (D->hasAttr<CUDAGlobalAttr>())
12753 return CFT_Global;
12754
12755 if (D->hasAttr<CUDADeviceAttr>()) {
12756 if (D->hasAttr<CUDAHostAttr>())
12757 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012758 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012759 }
12760
12761 return CFT_Host;
12762}
12763
12764bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12765 CUDAFunctionTarget CalleeTarget) {
12766 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12767 // Callable from the device only."
12768 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12769 return true;
12770
12771 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12772 // Callable from the host only."
12773 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12774 // Callable from the host only."
12775 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12776 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12777 return true;
12778
12779 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12780 return true;
12781
12782 return false;
12783}
John McCall5e77d762013-04-16 07:28:30 +000012784
12785/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12786///
12787MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12788 SourceLocation DeclStart,
12789 Declarator &D, Expr *BitWidth,
12790 InClassInitStyle InitStyle,
12791 AccessSpecifier AS,
12792 AttributeList *MSPropertyAttr) {
12793 IdentifierInfo *II = D.getIdentifier();
12794 if (!II) {
12795 Diag(DeclStart, diag::err_anonymous_property);
12796 return NULL;
12797 }
12798 SourceLocation Loc = D.getIdentifierLoc();
12799
12800 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12801 QualType T = TInfo->getType();
12802 if (getLangOpts().CPlusPlus) {
12803 CheckExtraCXXDefaultArguments(D);
12804
12805 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12806 UPPC_DataMemberType)) {
12807 D.setInvalidType();
12808 T = Context.IntTy;
12809 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12810 }
12811 }
12812
12813 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12814
12815 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12816 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12817 diag::err_invalid_thread)
12818 << DeclSpec::getSpecifierName(TSCS);
12819
12820 // Check to see if this name was declared as a member previously
12821 NamedDecl *PrevDecl = 0;
12822 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12823 LookupName(Previous, S);
12824 switch (Previous.getResultKind()) {
12825 case LookupResult::Found:
12826 case LookupResult::FoundUnresolvedValue:
12827 PrevDecl = Previous.getAsSingle<NamedDecl>();
12828 break;
12829
12830 case LookupResult::FoundOverloaded:
12831 PrevDecl = Previous.getRepresentativeDecl();
12832 break;
12833
12834 case LookupResult::NotFound:
12835 case LookupResult::NotFoundInCurrentInstantiation:
12836 case LookupResult::Ambiguous:
12837 break;
12838 }
12839
12840 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12841 // Maybe we will complain about the shadowed template parameter.
12842 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12843 // Just pretend that we didn't see the previous declaration.
12844 PrevDecl = 0;
12845 }
12846
12847 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12848 PrevDecl = 0;
12849
12850 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000012851 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000012852 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12853 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000012854 ProcessDeclAttributes(TUScope, NewPD, D);
12855 NewPD->setAccess(AS);
12856
12857 if (NewPD->isInvalidDecl())
12858 Record->setInvalidDecl();
12859
12860 if (D.getDeclSpec().isModulePrivateSpecified())
12861 NewPD->setModulePrivate();
12862
12863 if (NewPD->isInvalidDecl() && PrevDecl) {
12864 // Don't introduce NewFD into scope; there's already something
12865 // with the same name in the same scope.
12866 } else if (II) {
12867 PushOnScopeChains(NewPD, S);
12868 } else
12869 Record->addDecl(NewPD);
12870
12871 return NewPD;
12872}