blob: 28337171712c54f75006368fd79663d4264681fc [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"
Richard Trieu4fc85362012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
Reid Klecknerd60b82f2014-11-17 23:36:45 +000039#include "clang/Sema/Template.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())
David Blaikie82e95a32014-11-19 07:49:47 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000217 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;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000272 Arg = Result.getAs<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;
Benjamin Kramer3b8044c2015-03-27 13:58:31 +0000319 }
320
321 // C++11 [dcl.fct.default]p3
322 // A default argument expression [...] shall not be specified for a
323 // parameter pack.
324 if (Param->isParameterPack()) {
325 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
326 << DefaultArg->getSourceRange();
327 return;
328 }
329
Anders Carlssonf1c26952009-08-25 01:02:06 +0000330 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000331 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
332 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000333 Param->setInvalidDecl();
334 return;
335 }
Mike Stump11289f42009-09-09 15:08:12 +0000336
John McCallb268a282010-08-23 23:25:46 +0000337 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000338}
339
Douglas Gregor58354032008-12-24 00:01:03 +0000340/// ActOnParamUnparsedDefaultArgument - We've seen a default
341/// argument for a function parameter, but we can't parse it yet
342/// because we're inside a class definition. Note that this default
343/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000344void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000345 SourceLocation EqualLoc,
346 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000347 if (!param)
348 return;
Mike Stump11289f42009-09-09 15:08:12 +0000349
John McCall48871652010-08-21 09:40:31 +0000350 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000351 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000352 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000353}
354
Douglas Gregor4d87df52008-12-16 21:30:33 +0000355/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
356/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000357void Sema::ActOnParamDefaultArgumentError(Decl *param,
358 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000359 if (!param)
360 return;
Mike Stump11289f42009-09-09 15:08:12 +0000361
John McCall48871652010-08-21 09:40:31 +0000362 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000363 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000364 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000365 Param->setDefaultArg(new(Context)
Fariborz Jahanian7bd22e92014-10-01 18:03:51 +0000366 OpaqueValueExpr(EqualLoc,
367 Param->getType().getNonReferenceType(),
368 VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000369}
370
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000371/// CheckExtraCXXDefaultArguments - Check for any extra default
372/// arguments in the declarator, which is not a function declaration
373/// or definition and therefore is not permitted to have default
374/// arguments. This routine should be invoked for every declarator
375/// that is not a function declaration or definition.
376void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
377 // C++ [dcl.fct.default]p3
378 // A default argument expression shall be specified only in the
379 // parameter-declaration-clause of a function declaration or in a
380 // template-parameter (14.1). It shall not be specified for a
381 // parameter pack. If it is specified in a
382 // parameter-declaration-clause, it shall not occur within a
383 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000384 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000385 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000386 DeclaratorChunk &chunk = D.getTypeObject(i);
387 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000388 if (MightBeFunction) {
389 // This is a function declaration. It can have default arguments, but
390 // keep looking in case its return type is a function type with default
391 // arguments.
392 MightBeFunction = false;
393 continue;
394 }
Alp Tokerc5350722014-02-26 22:27:52 +0000395 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
396 ++argIdx) {
397 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000398 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000399 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
David Majnemerb3c6d522015-01-13 07:42:33 +0000400 SourceRange SR;
401 if (Toks->size() > 1)
402 SR = SourceRange((*Toks)[1].getLocation(),
403 Toks->back().getLocation());
404 else
405 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor4d87df52008-12-16 21:30:33 +0000406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
David Majnemerb3c6d522015-01-13 07:42:33 +0000407 << SR;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000408 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000409 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000410 } else if (Param->getDefaultArg()) {
411 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
412 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000413 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000414 }
415 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000416 } else if (chunk.Kind != DeclaratorChunk::Paren) {
417 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000418 }
419 }
420}
421
David Majnemer502b0ed2013-06-25 23:09:30 +0000422static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
423 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
424 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
425 if (!PVD->hasDefaultArg())
426 return false;
427 if (!PVD->hasInheritedDefaultArg())
428 return true;
429 }
430 return false;
431}
432
Craig Toppere4794282012-09-21 04:33:26 +0000433/// MergeCXXFunctionDecl - Merge two declarations of the same C++
434/// function, once we already know that they have the same
435/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
436/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000437bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
438 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000439 bool Invalid = false;
440
Richard Smithc7d48d12015-05-20 17:50:35 +0000441 // The declaration context corresponding to the scope is the semantic
442 // parent, unless this is a local function declaration, in which case
443 // it is that surrounding function.
444 DeclContext *ScopeDC = New->isLocalExternDecl()
445 ? New->getLexicalDeclContext()
446 : New->getDeclContext();
447
448 // Find the previous declaration for the purpose of default arguments.
449 FunctionDecl *PrevForDefaultArgs = Old;
450 for (/**/; PrevForDefaultArgs;
451 // Don't bother looking back past the latest decl if this is a local
452 // extern declaration; nothing else could work.
453 PrevForDefaultArgs = New->isLocalExternDecl()
454 ? nullptr
455 : PrevForDefaultArgs->getPreviousDecl()) {
456 // Ignore hidden declarations.
457 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
458 continue;
459
460 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
461 !New->isCXXClassMember()) {
462 // Ignore default arguments of old decl if they are not in
463 // the same scope and this is not an out-of-line definition of
464 // a member function.
465 continue;
466 }
467
468 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
469 // If only one of these is a local function declaration, then they are
470 // declared in different scopes, even though isDeclInScope may think
471 // they're in the same scope. (If both are local, the scope check is
472 // sufficent, and if neither is local, then they are in the same scope.)
473 continue;
474 }
475
476 // We found our guy.
477 break;
478 }
479
Chris Lattner199abbc2008-04-08 05:04:30 +0000480 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000481 // For non-template functions, default arguments can be added in
482 // later declarations of a function in the same
483 // scope. Declarations in different scopes have completely
484 // distinct sets of default arguments. That is, declarations in
485 // inner scopes do not acquire default arguments from
486 // declarations in outer scopes, and vice versa. In a given
487 // function declaration, all parameters subsequent to a
488 // parameter with a default argument shall have default
489 // arguments supplied in this or previous declarations. A
490 // default argument shall not be redefined by a later
491 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000492 //
493 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000494 // Except for member functions of class templates, the default arguments
495 // in a member function definition that appears outside of the class
496 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000497 // member function declaration in the class definition.
Richard Smithc7d48d12015-05-20 17:50:35 +0000498 for (unsigned p = 0, NumParams = PrevForDefaultArgs
499 ? PrevForDefaultArgs->getNumParams()
500 : 0;
501 p < NumParams; ++p) {
502 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
Chris Lattner199abbc2008-04-08 05:04:30 +0000503 ParmVarDecl *NewParam = New->getParamDecl(p);
504
Richard Smithc7d48d12015-05-20 17:50:35 +0000505 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
James Molloye9430032012-03-13 08:55:35 +0000506 bool NewParamHasDfl = NewParam->hasDefaultArg();
507
James Molloye9430032012-03-13 08:55:35 +0000508 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000509 unsigned DiagDefaultParamID =
510 diag::err_param_default_argument_redefinition;
511
512 // MSVC accepts that default parameters be redefined for member functions
513 // of template class. The new default parameter's value is ignored.
514 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000515 if (getLangOpts().MicrosoftExt) {
Richard Smithc7d48d12015-05-20 17:50:35 +0000516 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000517 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000518 // Merge the old default argument into the new parameter.
519 NewParam->setHasInheritedDefaultArg();
520 if (OldParam->hasUninstantiatedDefaultArg())
521 NewParam->setUninstantiatedDefaultArg(
522 OldParam->getUninstantiatedDefaultArg());
523 else
524 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000525 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000526 Invalid = false;
527 }
528 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000529
Francois Pichet8cb243a2011-04-10 04:58:30 +0000530 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
531 // hint here. Alternatively, we could walk the type-source information
532 // for NewParam to find the last source location in the type... but it
533 // isn't worth the effort right now. This is the kind of test case that
534 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000535 // int f(int);
536 // void g(int (*fp)(int) = f);
537 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000538 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000539 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000540
541 // Look for the function declaration where the default argument was
542 // actually written, which may be a declaration prior to Old.
Richard Smithc7d48d12015-05-20 17:50:35 +0000543 for (auto Older = PrevForDefaultArgs;
544 OldParam->hasInheritedDefaultArg(); /**/) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000545 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000546 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000547 }
548
Douglas Gregorc732aba2009-09-11 18:44:32 +0000549 Diag(OldParam->getLocation(), diag::note_previous_definition)
550 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000551 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000552 // Merge the old default argument into the new parameter.
553 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000554 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000555 NewParam->setHasInheritedDefaultArg();
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000556 if (OldParam->hasUnparsedDefaultArg())
557 NewParam->setUnparsedDefaultArg();
558 else if (OldParam->hasUninstantiatedDefaultArg())
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000559 NewParam->setUninstantiatedDefaultArg(
560 OldParam->getUninstantiatedDefaultArg());
561 else
John McCalle61b02b2010-05-04 01:53:42 +0000562 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000563 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000564 if (New->getDescribedFunctionTemplate()) {
565 // Paragraph 4, quoted above, only applies to non-template functions.
566 Diag(NewParam->getLocation(),
567 diag::err_param_default_argument_template_redecl)
568 << NewParam->getDefaultArgRange();
Richard Smithc7d48d12015-05-20 17:50:35 +0000569 Diag(PrevForDefaultArgs->getLocation(),
570 diag::note_template_prev_declaration)
571 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000572 } else if (New->getTemplateSpecializationKind()
573 != TSK_ImplicitInstantiation &&
574 New->getTemplateSpecializationKind() != TSK_Undeclared) {
575 // C++ [temp.expr.spec]p21:
576 // Default function arguments shall not be specified in a declaration
577 // or a definition for one of the following explicit specializations:
578 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000579 // - the explicit specialization of a member function template;
580 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000581 // template where the class template specialization to which the
582 // member function specialization belongs is implicitly
583 // instantiated.
584 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
585 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
586 << New->getDeclName()
587 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000588 } else if (New->getDeclContext()->isDependentContext()) {
589 // C++ [dcl.fct.default]p6 (DR217):
590 // Default arguments for a member function of a class template shall
591 // be specified on the initial declaration of the member function
592 // within the class template.
593 //
594 // Reading the tea leaves a bit in DR217 and its reference to DR205
595 // leads me to the conclusion that one cannot add default function
596 // arguments for an out-of-line definition of a member function of a
597 // dependent type.
598 int WhichKind = 2;
599 if (CXXRecordDecl *Record
600 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
601 if (Record->getDescribedClassTemplate())
602 WhichKind = 0;
603 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
604 WhichKind = 1;
605 else
606 WhichKind = 2;
607 }
608
609 Diag(NewParam->getLocation(),
610 diag::err_param_default_argument_member_template_redecl)
611 << WhichKind
612 << NewParam->getDefaultArgRange();
613 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000614 }
615 }
616
Richard Smith58c3cc12012-11-28 03:45:24 +0000617 // DR1344: If a default argument is added outside a class definition and that
618 // default argument makes the function a special member function, the program
619 // is ill-formed. This can only happen for constructors.
620 if (isa<CXXConstructorDecl>(New) &&
621 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
622 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
623 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
624 if (NewSM != OldSM) {
625 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
626 assert(NewParam->hasDefaultArg());
627 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
628 << NewParam->getDefaultArgRange() << NewSM;
629 Diag(Old->getLocation(), diag::note_previous_declaration);
630 }
631 }
632
David Majnemeree4f4022014-03-30 06:44:54 +0000633 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000634 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000635 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000636 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000637 if (New->isConstexpr() != Old->isConstexpr()) {
638 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
639 << New << New->isConstexpr();
640 Diag(Old->getLocation(), diag::note_previous_declaration);
641 Invalid = true;
Reid Kleckner93864172015-04-08 00:04:47 +0000642 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
643 Old->isDefined(Def)) {
David Majnemeree4f4022014-03-30 06:44:54 +0000644 // C++11 [dcl.fcn.spec]p4:
645 // If the definition of a function appears in a translation unit before its
646 // first declaration as inline, the program is ill-formed.
647 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
648 Diag(Def->getLocation(), diag::note_previous_definition);
649 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000650 }
651
David Majnemer502b0ed2013-06-25 23:09:30 +0000652 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000653 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000654 // the only declaration of the function or function template in the
655 // translation unit.
656 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
657 functionDeclHasDefaultArgument(Old)) {
658 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
659 Diag(Old->getLocation(), diag::note_previous_declaration);
660 Invalid = true;
661 }
662
Douglas Gregorf40863c2010-02-12 07:32:17 +0000663 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000664 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000665
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000666 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000667}
668
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000669/// \brief Merge the exception specifications of two variable declarations.
670///
671/// This is called when there's a redeclaration of a VarDecl. The function
672/// checks if the redeclaration might have an exception specification and
673/// validates compatibility and merges the specs if necessary.
674void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
675 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000676 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000677 return;
678
679 assert(Context.hasSameType(New->getType(), Old->getType()) &&
680 "Should only be called if types are otherwise the same.");
681
682 QualType NewType = New->getType();
683 QualType OldType = Old->getType();
684
685 // We're only interested in pointers and references to functions, as well
686 // as pointers to member functions.
687 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
688 NewType = R->getPointeeType();
689 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
690 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
691 NewType = P->getPointeeType();
692 OldType = OldType->getAs<PointerType>()->getPointeeType();
693 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
694 NewType = M->getPointeeType();
695 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
696 }
697
698 if (!NewType->isFunctionProtoType())
699 return;
700
701 // There's lots of special cases for functions. For function pointers, system
702 // libraries are hopefully not as broken so that we don't need these
703 // workarounds.
704 if (CheckEquivalentExceptionSpec(
705 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
706 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
707 New->setInvalidDecl();
708 }
709}
710
Chris Lattner199abbc2008-04-08 05:04:30 +0000711/// CheckCXXDefaultArguments - Verify that the default arguments for a
712/// function declaration are well-formed according to C++
713/// [dcl.fct.default].
714void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
715 unsigned NumParams = FD->getNumParams();
716 unsigned p;
717
718 // Find first parameter with a default argument
719 for (p = 0; p < NumParams; ++p) {
720 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000721 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000722 break;
723 }
724
Benjamin Kramerfe257592015-03-27 13:58:41 +0000725 // C++11 [dcl.fct.default]p4:
726 // In a given function declaration, each parameter subsequent to a parameter
727 // with a default argument shall have a default argument supplied in this or
728 // a previous declaration or shall be a function parameter pack. A default
729 // argument shall not be redefined by a later declaration (not even to the
730 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +0000731 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000732 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000733 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +0000734 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000735 if (Param->isInvalidDecl())
736 /* We already complained about this parameter. */;
737 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000738 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000739 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000740 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000741 else
Mike Stump11289f42009-09-09 15:08:12 +0000742 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000743 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000744
Chris Lattner199abbc2008-04-08 05:04:30 +0000745 LastMissingDefaultArg = p;
746 }
747 }
748
749 if (LastMissingDefaultArg > 0) {
750 // Some default arguments were missing. Clear out all of the
751 // default arguments up to (and including) the last missing
752 // default argument, so that we leave the function parameters
753 // in a semantically valid state.
754 for (p = 0; p <= LastMissingDefaultArg; ++p) {
755 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000756 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000757 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000758 }
759 }
760 }
761}
Douglas Gregor556877c2008-04-13 21:30:24 +0000762
Richard Smitheb3c10c2011-10-01 02:31:28 +0000763// CheckConstexprParameterTypes - Check whether a function's parameter types
764// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000765// diagnostic and return false.
766static bool CheckConstexprParameterTypes(Sema &SemaRef,
767 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000768 unsigned ArgIndex = 0;
769 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000770 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
771 e = FT->param_type_end();
772 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000773 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
774 SourceLocation ParamLoc = PD->getLocation();
775 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000776 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000777 diag::err_constexpr_non_literal_param,
778 ArgIndex+1, PD->getSourceRange(),
779 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000780 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000781 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000782 return true;
783}
784
785/// \brief Get diagnostic %select index for tag kind for
786/// record diagnostic message.
787/// WARNING: Indexes apply to particular diagnostics only!
788///
789/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000790static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000791 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000792 case TTK_Struct: return 0;
793 case TTK_Interface: return 1;
794 case TTK_Class: return 2;
795 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000796 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000797}
798
799// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
800// the requirements of a constexpr function definition or a constexpr
801// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000802// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000803//
Richard Smith3607ffe2012-02-13 03:54:03 +0000804// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
805bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000806 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
807 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000808 // C++11 [dcl.constexpr]p4:
809 // The definition of a constexpr constructor shall satisfy the following
810 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000811 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000812 const CXXRecordDecl *RD = MD->getParent();
813 if (RD->getNumVBases()) {
814 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
815 << isa<CXXConstructorDecl>(NewFD)
816 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000817 for (const auto &I : RD->vbases())
818 Diag(I.getLocStart(),
819 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000820 return false;
821 }
Richard Smith7971b692012-01-13 04:54:00 +0000822 }
823
824 if (!isa<CXXConstructorDecl>(NewFD)) {
825 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000826 // The definition of a constexpr function shall satisfy the following
827 // constraints:
828 // - it shall not be virtual;
829 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
830 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000831 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000832
Richard Smith3607ffe2012-02-13 03:54:03 +0000833 // If it's not obvious why this function is virtual, find an overridden
834 // function which uses the 'virtual' keyword.
835 const CXXMethodDecl *WrittenVirtual = Method;
836 while (!WrittenVirtual->isVirtualAsWritten())
837 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
838 if (WrittenVirtual != Method)
839 Diag(WrittenVirtual->getLocation(),
840 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000841 return false;
842 }
843
844 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000845 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000846 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000847 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000848 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000849 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000850 }
851
Richard Smith7971b692012-01-13 04:54:00 +0000852 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000853 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000854 return false;
855
Richard Smitheb3c10c2011-10-01 02:31:28 +0000856 return true;
857}
858
859/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000860/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000861///
Richard Smithd9f663b2013-04-22 15:31:51 +0000862/// \return true if the body is OK (maybe only as an extension), false if we
863/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000864static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000865 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
866 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000867 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
868 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000869 for (const auto *DclIt : DS->decls()) {
870 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000871 case Decl::StaticAssert:
872 case Decl::Using:
873 case Decl::UsingShadow:
874 case Decl::UsingDirective:
875 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000876 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000877 // - static_assert-declarations
878 // - using-declarations,
879 // - using-directives,
880 continue;
881
882 case Decl::Typedef:
883 case Decl::TypeAlias: {
884 // - typedef declarations and alias-declarations that do not define
885 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000886 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000887 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
888 // Don't allow variably-modified types in constexpr functions.
889 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
890 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
891 << TL.getSourceRange() << TL.getType()
892 << isa<CXXConstructorDecl>(Dcl);
893 return false;
894 }
895 continue;
896 }
897
898 case Decl::Enum:
899 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000900 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000901 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000902 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000903 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000904 ? diag::warn_cxx11_compat_constexpr_type_definition
905 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000906 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000907 continue;
908
Richard Smithd9f663b2013-04-22 15:31:51 +0000909 case Decl::EnumConstant:
910 case Decl::IndirectField:
911 case Decl::ParmVar:
912 // These can only appear with other declarations which are banned in
913 // C++11 and permitted in C++1y, so ignore them.
914 continue;
915
916 case Decl::Var: {
917 // C++1y [dcl.constexpr]p3 allows anything except:
918 // a definition of a variable of non-literal type or of static or
919 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000920 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000921 if (VD->isThisDeclarationADefinition()) {
922 if (VD->isStaticLocal()) {
923 SemaRef.Diag(VD->getLocation(),
924 diag::err_constexpr_local_var_static)
925 << isa<CXXConstructorDecl>(Dcl)
926 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
927 return false;
928 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000929 if (!VD->getType()->isDependentType() &&
930 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000931 VD->getLocation(), VD->getType(),
932 diag::err_constexpr_local_var_non_literal_type,
933 isa<CXXConstructorDecl>(Dcl)))
934 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000935 if (!VD->getType()->isDependentType() &&
936 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000937 SemaRef.Diag(VD->getLocation(),
938 diag::err_constexpr_local_var_no_init)
939 << isa<CXXConstructorDecl>(Dcl);
940 return false;
941 }
942 }
943 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000944 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000945 ? diag::warn_cxx11_compat_constexpr_local_var
946 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000947 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000948 continue;
949 }
950
951 case Decl::NamespaceAlias:
952 case Decl::Function:
953 // These are disallowed in C++11 and permitted in C++1y. Allow them
954 // everywhere as an extension.
955 if (!Cxx1yLoc.isValid())
956 Cxx1yLoc = DS->getLocStart();
957 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000958
959 default:
960 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
961 << isa<CXXConstructorDecl>(Dcl);
962 return false;
963 }
964 }
965
966 return true;
967}
968
969/// Check that the given field is initialized within a constexpr constructor.
970///
971/// \param Dcl The constexpr constructor being checked.
972/// \param Field The field being checked. This may be a member of an anonymous
973/// struct or union nested within the class being checked.
974/// \param Inits All declarations, including anonymous struct/union members and
975/// indirect members, for which any initialization was provided.
976/// \param Diagnosed Set to true if an error is produced.
977static void CheckConstexprCtorInitializer(Sema &SemaRef,
978 const FunctionDecl *Dcl,
979 FieldDecl *Field,
980 llvm::SmallSet<Decl*, 16> &Inits,
981 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000982 if (Field->isInvalidDecl())
983 return;
984
Douglas Gregor556e5862011-10-10 17:22:13 +0000985 if (Field->isUnnamedBitfield())
986 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000987
Richard Smithab44d5b2013-12-10 08:25:00 +0000988 // Anonymous unions with no variant members and empty anonymous structs do not
989 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
990 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000991 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000992 (Field->getType()->isUnionType()
993 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
994 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000995 return;
996
Richard Smitheb3c10c2011-10-01 02:31:28 +0000997 if (!Inits.count(Field)) {
998 if (!Diagnosed) {
999 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1000 Diagnosed = true;
1001 }
1002 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1003 } else if (Field->isAnonymousStructOrUnion()) {
1004 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001005 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001006 // If an anonymous union contains an anonymous struct of which any member
1007 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001008 if (!RD->isUnion() || Inits.count(I))
1009 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001010 }
1011}
1012
Richard Smithd9f663b2013-04-22 15:31:51 +00001013/// Check the provided statement is allowed in a constexpr function
1014/// definition.
1015static bool
1016CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00001017 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001018 SourceLocation &Cxx1yLoc) {
1019 // - its function-body shall be [...] a compound-statement that contains only
1020 switch (S->getStmtClass()) {
1021 case Stmt::NullStmtClass:
1022 // - null statements,
1023 return true;
1024
1025 case Stmt::DeclStmtClass:
1026 // - static_assert-declarations
1027 // - using-declarations,
1028 // - using-directives,
1029 // - typedef declarations and alias-declarations that do not define
1030 // classes or enumerations,
1031 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1032 return false;
1033 return true;
1034
1035 case Stmt::ReturnStmtClass:
1036 // - and exactly one return statement;
1037 if (isa<CXXConstructorDecl>(Dcl)) {
1038 // C++1y allows return statements in constexpr constructors.
1039 if (!Cxx1yLoc.isValid())
1040 Cxx1yLoc = S->getLocStart();
1041 return true;
1042 }
1043
1044 ReturnStmts.push_back(S->getLocStart());
1045 return true;
1046
1047 case Stmt::CompoundStmtClass: {
1048 // C++1y allows compound-statements.
1049 if (!Cxx1yLoc.isValid())
1050 Cxx1yLoc = S->getLocStart();
1051
1052 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001053 for (auto *BodyIt : CompStmt->body()) {
1054 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001055 Cxx1yLoc))
1056 return false;
1057 }
1058 return true;
1059 }
1060
1061 case Stmt::AttributedStmtClass:
1062 if (!Cxx1yLoc.isValid())
1063 Cxx1yLoc = S->getLocStart();
1064 return true;
1065
1066 case Stmt::IfStmtClass: {
1067 // C++1y allows if-statements.
1068 if (!Cxx1yLoc.isValid())
1069 Cxx1yLoc = S->getLocStart();
1070
1071 IfStmt *If = cast<IfStmt>(S);
1072 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1073 Cxx1yLoc))
1074 return false;
1075 if (If->getElse() &&
1076 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1077 Cxx1yLoc))
1078 return false;
1079 return true;
1080 }
1081
1082 case Stmt::WhileStmtClass:
1083 case Stmt::DoStmtClass:
1084 case Stmt::ForStmtClass:
1085 case Stmt::CXXForRangeStmtClass:
1086 case Stmt::ContinueStmtClass:
1087 // C++1y allows all of these. We don't allow them as extensions in C++11,
1088 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001089 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001090 break;
1091 if (!Cxx1yLoc.isValid())
1092 Cxx1yLoc = S->getLocStart();
1093 for (Stmt::child_range Children = S->children(); Children; ++Children)
1094 if (*Children &&
1095 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1096 Cxx1yLoc))
1097 return false;
1098 return true;
1099
1100 case Stmt::SwitchStmtClass:
1101 case Stmt::CaseStmtClass:
1102 case Stmt::DefaultStmtClass:
1103 case Stmt::BreakStmtClass:
1104 // C++1y allows switch-statements, and since they don't need variable
1105 // mutation, we can reasonably allow them in C++11 as an extension.
1106 if (!Cxx1yLoc.isValid())
1107 Cxx1yLoc = S->getLocStart();
1108 for (Stmt::child_range Children = S->children(); Children; ++Children)
1109 if (*Children &&
1110 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1111 Cxx1yLoc))
1112 return false;
1113 return true;
1114
1115 default:
1116 if (!isa<Expr>(S))
1117 break;
1118
1119 // C++1y allows expression-statements.
1120 if (!Cxx1yLoc.isValid())
1121 Cxx1yLoc = S->getLocStart();
1122 return true;
1123 }
1124
1125 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1126 << isa<CXXConstructorDecl>(Dcl);
1127 return false;
1128}
1129
Richard Smitheb3c10c2011-10-01 02:31:28 +00001130/// Check the body for the given constexpr function declaration only contains
1131/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1132///
1133/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001134bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001135 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001136 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001137 // The definition of a constexpr function shall satisfy the following
1138 // constraints: [...]
1139 // - its function-body shall be = delete, = default, or a
1140 // compound-statement
1141 //
Richard Smith74388b42012-02-04 00:33:54 +00001142 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001143 // In the definition of a constexpr constructor, [...]
1144 // - its function-body shall not be a function-try-block;
1145 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1146 << isa<CXXConstructorDecl>(Dcl);
1147 return false;
1148 }
1149
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001150 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001151
1152 // - its function-body shall be [...] a compound-statement that contains only
1153 // [... list of cases ...]
1154 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1155 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001156 for (auto *BodyIt : CompBody->body()) {
1157 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001158 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001159 }
1160
Richard Smithd9f663b2013-04-22 15:31:51 +00001161 if (Cxx1yLoc.isValid())
1162 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001163 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001164 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1165 : diag::ext_constexpr_body_invalid_stmt)
1166 << isa<CXXConstructorDecl>(Dcl);
1167
Richard Smitheb3c10c2011-10-01 02:31:28 +00001168 if (const CXXConstructorDecl *Constructor
1169 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1170 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001171 // DR1359:
1172 // - every non-variant non-static data member and base class sub-object
1173 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001174 // DR1460:
1175 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001176 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001177 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001178 if (Constructor->getNumCtorInitializers() == 0 &&
1179 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001180 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1181 return false;
1182 }
Richard Smithf368fb42011-10-10 16:38:04 +00001183 } else if (!Constructor->isDependentContext() &&
1184 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001185 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1186
1187 // Skip detailed checking if we have enough initializers, and we would
1188 // allow at most one initializer per member.
1189 bool AnyAnonStructUnionMembers = false;
1190 unsigned Fields = 0;
1191 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1192 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001193 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001194 AnyAnonStructUnionMembers = true;
1195 break;
1196 }
1197 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001198 // DR1460:
1199 // - if the class is a union-like class, but is not a union, for each of
1200 // its anonymous union members having variant members, exactly one of
1201 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001202 if (AnyAnonStructUnionMembers ||
1203 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1204 // Check initialization of non-static data members. Base classes are
1205 // always initialized so do not need to be checked. Dependent bases
1206 // might not have initializers in the member initializer list.
1207 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001208 for (const auto *I: Constructor->inits()) {
1209 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001210 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001211 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001212 Inits.insert(ID->chain_begin(), ID->chain_end());
1213 }
1214
1215 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001216 for (auto *I : RD->fields())
1217 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001218 if (Diagnosed)
1219 return false;
1220 }
1221 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001222 } else {
1223 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001224 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001225 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001226 // otherwise if there's no return statement, the function cannot
1227 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001228 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001229 (Dcl->getReturnType()->isVoidType() ||
1230 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001231 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001232 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1233 : diag::err_constexpr_body_no_return);
1234 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001235 }
1236 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001237 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001238 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001239 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1240 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001241 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1242 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001243 }
1244 }
1245
Richard Smith74388b42012-02-04 00:33:54 +00001246 // C++11 [dcl.constexpr]p5:
1247 // if no function argument values exist such that the function invocation
1248 // substitution would produce a constant expression, the program is
1249 // ill-formed; no diagnostic required.
1250 // C++11 [dcl.constexpr]p3:
1251 // - every constructor call and implicit conversion used in initializing the
1252 // return value shall be one of those allowed in a constant expression.
1253 // C++11 [dcl.constexpr]p4:
1254 // - every constructor involved in initializing non-static data members and
1255 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001256 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001257 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001258 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001259 << isa<CXXConstructorDecl>(Dcl);
1260 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1261 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001262 // Don't return false here: we allow this for compatibility in
1263 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001264 }
1265
Richard Smitheb3c10c2011-10-01 02:31:28 +00001266 return true;
1267}
1268
Douglas Gregor61956c42008-10-31 09:07:45 +00001269/// isCurrentClassName - Determine whether the identifier II is the
1270/// name of the class type currently being defined. In the case of
1271/// nested classes, this will only return true if II is the name of
1272/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001273bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1274 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001275 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001276
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001277 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001278 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001279 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001280 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1281 } else
1282 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1283
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001284 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001285 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001286 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001287}
1288
Richard Smithfb8b7b92013-10-15 00:00:26 +00001289/// \brief Determine whether the identifier II is a typo for the name of
1290/// the class type currently being defined. If so, update it to the identifier
1291/// that should have been used.
1292bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1293 assert(getLangOpts().CPlusPlus && "No class names in C!");
1294
1295 if (!getLangOpts().SpellChecking)
1296 return false;
1297
1298 CXXRecordDecl *CurDecl;
1299 if (SS && SS->isSet() && !SS->isInvalid()) {
1300 DeclContext *DC = computeDeclContext(*SS, true);
1301 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1302 } else
1303 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1304
1305 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1306 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1307 < II->getLength()) {
1308 II = CurDecl->getIdentifier();
1309 return true;
1310 }
1311
1312 return false;
1313}
1314
Douglas Gregordc974572012-11-10 07:24:09 +00001315/// \brief Determine whether the given class is a base class of the given
1316/// class, including looking at dependent bases.
1317static bool findCircularInheritance(const CXXRecordDecl *Class,
1318 const CXXRecordDecl *Current) {
1319 SmallVector<const CXXRecordDecl*, 8> Queue;
1320
1321 Class = Class->getCanonicalDecl();
1322 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001323 for (const auto &I : Current->bases()) {
1324 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001325 if (!Base)
1326 continue;
1327
1328 Base = Base->getDefinition();
1329 if (!Base)
1330 continue;
1331
1332 if (Base->getCanonicalDecl() == Class)
1333 return true;
1334
1335 Queue.push_back(Base);
1336 }
1337
1338 if (Queue.empty())
1339 return false;
1340
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001341 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001342 }
1343
1344 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001345}
1346
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001347/// \brief Perform propagation of DLL attributes from a derived class to a
1348/// templated base class for MS compatibility.
1349static void propagateDLLAttrToBaseClassTemplate(
1350 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1351 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1352 if (getDLLAttr(
1353 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1354 // If the base class template has a DLL attribute, don't try to change it.
1355 return;
1356 }
1357
1358 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1359 // If the base class is not already specialized, we can do the propagation.
1360 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1361 NewAttr->setInherited(true);
1362 BaseTemplateSpec->addAttr(NewAttr);
1363 return;
1364 }
1365
1366 bool DifferentAttribute = false;
1367 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1368 if (!SpecializationAttr->isInherited()) {
1369 // The template has previously been specialized or instantiated with an
1370 // explicit attribute. We should not try to change it.
1371 return;
1372 }
1373 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1374 // The specialization already has the right attribute.
1375 return;
1376 }
1377 DifferentAttribute = true;
1378 }
1379
1380 // The template was previously instantiated or explicitly specialized without
1381 // a dll attribute, or the template was previously instantiated with a
1382 // different inherited attribute. It's too late for us to change the
1383 // attribute, so warn that this is unsupported.
1384 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1385 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1386 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1387 if (BaseTemplateSpec->isExplicitSpecialization()) {
1388 S.Diag(BaseTemplateSpec->getLocation(),
1389 diag::note_template_class_explicit_specialization_was_here)
1390 << BaseTemplateSpec;
1391 } else {
1392 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1393 diag::note_template_class_instantiation_was_here)
1394 << BaseTemplateSpec;
1395 }
1396}
1397
Mike Stump11289f42009-09-09 15:08:12 +00001398/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001399///
1400/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1401/// and returns NULL otherwise.
1402CXXBaseSpecifier *
1403Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1404 SourceRange SpecifierRange,
1405 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001406 TypeSourceInfo *TInfo,
1407 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001408 QualType BaseType = TInfo->getType();
1409
Douglas Gregor463421d2009-03-03 04:44:36 +00001410 // C++ [class.union]p1:
1411 // A union shall not have base classes.
1412 if (Class->isUnion()) {
1413 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1414 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001415 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001416 }
1417
Douglas Gregor752a5952011-01-03 22:36:02 +00001418 if (EllipsisLoc.isValid() &&
1419 !TInfo->getType()->containsUnexpandedParameterPack()) {
1420 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1421 << TInfo->getTypeLoc().getSourceRange();
1422 EllipsisLoc = SourceLocation();
1423 }
Douglas Gregor62004702012-11-10 01:18:17 +00001424
1425 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1426
1427 if (BaseType->isDependentType()) {
1428 // Make sure that we don't have circular inheritance among our dependent
1429 // bases. For non-dependent bases, the check for completeness below handles
1430 // this.
1431 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1432 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1433 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001434 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001435 Diag(BaseLoc, diag::err_circular_inheritance)
1436 << BaseType << Context.getTypeDeclType(Class);
1437
1438 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1439 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1440 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001441
1442 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001443 }
1444 }
1445
Mike Stump11289f42009-09-09 15:08:12 +00001446 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001447 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001448 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001449 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001450
1451 // Base specifiers must be record types.
1452 if (!BaseType->isRecordType()) {
1453 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001454 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001455 }
1456
1457 // C++ [class.union]p1:
1458 // A union shall not be used as a base class.
1459 if (BaseType->isUnionType()) {
1460 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001461 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001462 }
1463
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001464 // For the MS ABI, propagate DLL attributes to base class templates.
1465 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1466 if (Attr *ClassAttr = getDLLAttr(Class)) {
1467 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1468 BaseType->getAsCXXRecordDecl())) {
1469 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1470 BaseTemplate, BaseLoc);
1471 }
1472 }
1473 }
1474
Douglas Gregor463421d2009-03-03 04:44:36 +00001475 // C++ [class.derived]p2:
1476 // The class-name in a base-specifier shall not be an incompletely
1477 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001478 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001479 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001480 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001481 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001482 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001483
Eli Friedmanc96d4962009-08-15 21:55:26 +00001484 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001485 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001486 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001487 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001488 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001489 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001490 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001491
David Majnemer9b1754d2013-11-02 12:00:36 +00001492 // A class which contains a flexible array member is not suitable for use as a
1493 // base class:
1494 // - If the layout determines that a base comes before another base,
1495 // the flexible array member would index into the subsequent base.
1496 // - If the layout determines that base comes before the derived class,
1497 // the flexible array member would index into the derived class.
1498 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1499 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1500 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001501 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001502 }
1503
Anders Carlsson65c76d32011-03-25 14:55:14 +00001504 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001505 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001506 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001507 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001508 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001509 << CXXBaseDecl->getDeclName()
1510 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001511 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1512 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001513 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001514 }
1515
John McCall3696dcb2010-08-17 07:23:57 +00001516 if (BaseDecl->isInvalidDecl())
1517 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001518
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001519 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001520 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001521 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001522 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001523}
1524
Douglas Gregor556877c2008-04-13 21:30:24 +00001525/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1526/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001527/// example:
1528/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001529/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001530BaseResult
John McCall48871652010-08-21 09:40:31 +00001531Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001532 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001533 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001534 ParsedType basetype, SourceLocation BaseLoc,
1535 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001536 if (!classdecl)
1537 return true;
1538
Douglas Gregorc40290e2009-03-09 23:48:35 +00001539 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001540 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001541 if (!Class)
1542 return true;
1543
David Majnemer5ef4fe72014-06-13 06:43:46 +00001544 // We haven't yet attached the base specifiers.
1545 Class->setIsParsingBaseSpecifiers();
1546
Richard Smith4c96e992013-02-19 23:47:15 +00001547 // We do not support any C++11 attributes on base-specifiers yet.
1548 // Diagnose any attributes we see.
1549 if (!Attributes.empty()) {
1550 for (AttributeList *Attr = Attributes.getList(); Attr;
1551 Attr = Attr->getNext()) {
1552 if (Attr->isInvalid() ||
1553 Attr->getKind() == AttributeList::IgnoredAttribute)
1554 continue;
1555 Diag(Attr->getLoc(),
1556 Attr->getKind() == AttributeList::UnknownAttribute
1557 ? diag::warn_unknown_attribute_ignored
1558 : diag::err_base_specifier_attribute)
1559 << Attr->getName();
1560 }
1561 }
1562
Craig Topperc3ec1492014-05-26 06:22:03 +00001563 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001564 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001565
Douglas Gregor752a5952011-01-03 22:36:02 +00001566 if (EllipsisLoc.isInvalid() &&
1567 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001568 UPPC_BaseType))
1569 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001570
Douglas Gregor463421d2009-03-03 04:44:36 +00001571 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001572 Virtual, Access, TInfo,
1573 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001574 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001575 else
1576 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001577
Douglas Gregor463421d2009-03-03 04:44:36 +00001578 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001579}
Douglas Gregor556877c2008-04-13 21:30:24 +00001580
Nathan Sidwell44b21742015-01-19 01:44:02 +00001581/// Use small set to collect indirect bases. As this is only used
1582/// locally, there's no need to abstract the small size parameter.
1583typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1584
1585/// \brief Recursively add the bases of Type. Don't add Type itself.
1586static void
1587NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1588 const QualType &Type)
1589{
1590 // Even though the incoming type is a base, it might not be
1591 // a class -- it could be a template parm, for instance.
1592 if (auto Rec = Type->getAs<RecordType>()) {
1593 auto Decl = Rec->getAsCXXRecordDecl();
1594
1595 // Iterate over its bases.
1596 for (const auto &BaseSpec : Decl->bases()) {
1597 QualType Base = Context.getCanonicalType(BaseSpec.getType())
1598 .getUnqualifiedType();
1599 if (Set.insert(Base).second)
1600 // If we've not already seen it, recurse.
1601 NoteIndirectBases(Context, Set, Base);
1602 }
1603 }
1604}
1605
Douglas Gregor463421d2009-03-03 04:44:36 +00001606/// \brief Performs the actual work of attaching the given base class
1607/// specifiers to a C++ class.
1608bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1609 unsigned NumBases) {
1610 if (NumBases == 0)
1611 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001612
1613 // Used to keep track of which base types we have already seen, so
1614 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001615 // that the key is always the unqualified canonical type of the base
1616 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001617 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1618
Nathan Sidwell44b21742015-01-19 01:44:02 +00001619 // Used to track indirect bases so we can see if a direct base is
1620 // ambiguous.
1621 IndirectBaseSet IndirectBaseTypes;
1622
Douglas Gregor29a92472008-10-22 17:49:05 +00001623 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001624 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001625 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001626 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001627 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001628 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001629 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001630
1631 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1632 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001633 // C++ [class.mi]p3:
1634 // A class shall not be specified as a direct base class of a
1635 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001636 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001637 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001638 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001639 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001640
1641 // Delete the duplicate base class specifier; we're going to
1642 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001643 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001644
1645 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001646 } else {
1647 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001648 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001649 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00001650
1651 // Note this base's direct & indirect bases, if there could be ambiguity.
1652 if (NumBases > 1)
1653 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1654
John McCalldb632ac2012-09-25 07:32:39 +00001655 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1656 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1657 if (Class->isInterface() &&
1658 (!RD->isInterface() ||
1659 KnownBase->getAccessSpecifier() != AS_public)) {
1660 // The Microsoft extension __interface does not permit bases that
1661 // are not themselves public interfaces.
1662 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1663 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1664 << RD->getSourceRange();
1665 Invalid = true;
1666 }
1667 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001668 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001669 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001670 }
1671 }
1672
1673 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001674 Class->setBases(Bases, NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001675
1676 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1677 // Check whether this direct base is inaccessible due to ambiguity.
1678 QualType BaseType = Bases[idx]->getType();
1679 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1680 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001681
Nathan Sidwell44b21742015-01-19 01:44:02 +00001682 if (IndirectBaseTypes.count(CanonicalBase)) {
1683 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1684 /*DetectVirtual=*/true);
1685 bool found
1686 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1687 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00001688 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00001689
1690 if (Paths.isAmbiguous(CanonicalBase))
1691 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1692 << BaseType << getAmbiguousPathsDisplayString(Paths)
1693 << Bases[idx]->getSourceRange();
1694 else
1695 assert(Bases[idx]->isVirtual());
1696 }
1697
1698 // Delete the base class specifier, since its data has been copied
1699 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001700 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001701 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001702
1703 return Invalid;
1704}
1705
1706/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1707/// class, after checking whether there are any duplicate base
1708/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001709void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001710 unsigned NumBases) {
1711 if (!ClassDecl || !Bases || !NumBases)
1712 return;
1713
1714 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001715 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001716}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001717
Douglas Gregor36d1b142009-10-06 17:59:45 +00001718/// \brief Determine whether the type \p Derived is a C++ class that is
1719/// derived from the type \p Base.
1720bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001721 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001722 return false;
John McCalle78aac42010-03-10 03:28:59 +00001723
Douglas Gregor45bb4832013-03-26 23:36:30 +00001724 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001725 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001726 return false;
1727
Douglas Gregor45bb4832013-03-26 23:36:30 +00001728 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001729 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001730 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001731
1732 // If either the base or the derived type is invalid, don't try to
1733 // check whether one is derived from the other.
1734 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1735 return false;
1736
John McCall67da35c2010-02-04 22:26:26 +00001737 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1738 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001739}
1740
1741/// \brief Determine whether the type \p Derived is a C++ class that is
1742/// derived from the type \p Base.
1743bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001744 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001745 return false;
1746
Douglas Gregor45bb4832013-03-26 23:36:30 +00001747 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001748 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001749 return false;
1750
Douglas Gregor45bb4832013-03-26 23:36:30 +00001751 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001752 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001753 return false;
1754
Douglas Gregor36d1b142009-10-06 17:59:45 +00001755 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1756}
1757
Anders Carlssona70cff62010-04-24 19:06:50 +00001758void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001759 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001760 assert(BasePathArray.empty() && "Base path array must be empty!");
1761 assert(Paths.isRecordingPaths() && "Must record paths!");
1762
1763 const CXXBasePath &Path = Paths.front();
1764
1765 // We first go backward and check if we have a virtual base.
1766 // FIXME: It would be better if CXXBasePath had the base specifier for
1767 // the nearest virtual base.
1768 unsigned Start = 0;
1769 for (unsigned I = Path.size(); I != 0; --I) {
1770 if (Path[I - 1].Base->isVirtual()) {
1771 Start = I - 1;
1772 break;
1773 }
1774 }
1775
1776 // Now add all bases.
1777 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001778 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001779}
1780
Douglas Gregor36d1b142009-10-06 17:59:45 +00001781/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1782/// conversion (where Derived and Base are class types) is
1783/// well-formed, meaning that the conversion is unambiguous (and
1784/// that all of the base classes are accessible). Returns true
1785/// and emits a diagnostic if the code is ill-formed, returns false
1786/// otherwise. Loc is the location where this routine should point to
1787/// if there is an error, and Range is the source range to highlight
1788/// if there is an error.
1789bool
1790Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001791 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001792 unsigned AmbigiousBaseConvID,
1793 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001794 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001795 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001796 // First, determine whether the path from Derived to Base is
1797 // ambiguous. This is slightly more expensive than checking whether
1798 // the Derived to Base conversion exists, because here we need to
1799 // explore multiple paths to determine if there is an ambiguity.
1800 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1801 /*DetectVirtual=*/false);
1802 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1803 assert(DerivationOkay &&
1804 "Can only be used with a derived-to-base conversion");
1805 (void)DerivationOkay;
1806
1807 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001808 if (InaccessibleBaseID) {
1809 // Check that the base class can be accessed.
1810 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1811 InaccessibleBaseID)) {
1812 case AR_inaccessible:
1813 return true;
1814 case AR_accessible:
1815 case AR_dependent:
1816 case AR_delayed:
1817 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001818 }
John McCall5b0829a2010-02-10 09:31:12 +00001819 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001820
1821 // Build a base path if necessary.
1822 if (BasePath)
1823 BuildBasePathArray(Paths, *BasePath);
1824 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001825 }
1826
David Majnemer626032f2013-06-22 06:43:58 +00001827 if (AmbigiousBaseConvID) {
1828 // We know that the derived-to-base conversion is ambiguous, and
1829 // we're going to produce a diagnostic. Perform the derived-to-base
1830 // search just one more time to compute all of the possible paths so
1831 // that we can print them out. This is more expensive than any of
1832 // the previous derived-to-base checks we've done, but at this point
1833 // performance isn't as much of an issue.
1834 Paths.clear();
1835 Paths.setRecordingPaths(true);
1836 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1837 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1838 (void)StillOkay;
1839
1840 // Build up a textual representation of the ambiguous paths, e.g.,
1841 // D -> B -> A, that will be used to illustrate the ambiguous
1842 // conversions in the diagnostic. We only print one of the paths
1843 // to each base class subobject.
1844 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1845
1846 Diag(Loc, AmbigiousBaseConvID)
1847 << Derived << Base << PathDisplayStr << Range << Name;
1848 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001849 return true;
1850}
1851
1852bool
1853Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001854 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001855 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001856 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001857 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001858 IgnoreAccess ? 0
1859 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001860 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001861 Loc, Range, DeclarationName(),
1862 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001863}
1864
1865
1866/// @brief Builds a string representing ambiguous paths from a
1867/// specific derived class to different subobjects of the same base
1868/// class.
1869///
1870/// This function builds a string that can be used in error messages
1871/// to show the different paths that one can take through the
1872/// inheritance hierarchy to go from the derived class to different
1873/// subobjects of a base class. The result looks something like this:
1874/// @code
1875/// struct D -> struct B -> struct A
1876/// struct D -> struct C -> struct A
1877/// @endcode
1878std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1879 std::string PathDisplayStr;
1880 std::set<unsigned> DisplayedPaths;
1881 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1882 Path != Paths.end(); ++Path) {
1883 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1884 // We haven't displayed a path to this particular base
1885 // class subobject yet.
1886 PathDisplayStr += "\n ";
1887 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1888 for (CXXBasePath::const_iterator Element = Path->begin();
1889 Element != Path->end(); ++Element)
1890 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1891 }
1892 }
1893
1894 return PathDisplayStr;
1895}
1896
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001897//===----------------------------------------------------------------------===//
1898// C++ class member Handling
1899//===----------------------------------------------------------------------===//
1900
Abramo Bagnarad7340582010-06-05 05:09:32 +00001901/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001902bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1903 SourceLocation ASLoc,
1904 SourceLocation ColonLoc,
1905 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001906 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001907 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001908 ASLoc, ColonLoc);
1909 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001910 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001911}
1912
Richard Smith18f07db2012-08-06 03:25:17 +00001913/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001914void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001915 if (D->isInvalidDecl())
1916 return;
1917
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001918 // We only care about "override" and "final" declarations.
1919 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1920 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001921
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001922 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001923
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001924 // We can't check dependent instance methods.
1925 if (MD && MD->isInstance() &&
1926 (MD->getParent()->hasAnyDependentBases() ||
1927 MD->getType()->isDependentType()))
1928 return;
1929
1930 if (MD && !MD->isVirtual()) {
1931 // If we have a non-virtual method, check if if hides a virtual method.
1932 // (In that case, it's most likely the method has the wrong type.)
1933 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1934 FindHiddenVirtualMethods(MD, OverloadedMethods);
1935
1936 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001937 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1938 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001939 diag::override_keyword_hides_virtual_member_function)
1940 << "override" << (OverloadedMethods.size() > 1);
1941 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001942 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001943 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001944 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1945 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001946 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001947 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1948 MD->setInvalidDecl();
1949 return;
1950 }
1951 // Fall through into the general case diagnostic.
1952 // FIXME: We might want to attempt typo correction here.
1953 }
1954
1955 if (!MD || !MD->isVirtual()) {
1956 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1957 Diag(OA->getLocation(),
1958 diag::override_keyword_only_allowed_on_virtual_member_functions)
1959 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1960 D->dropAttr<OverrideAttr>();
1961 }
1962 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1963 Diag(FA->getLocation(),
1964 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001965 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1966 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001967 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001968 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001969 return;
1970 }
Richard Smith18f07db2012-08-06 03:25:17 +00001971
Richard Smith18f07db2012-08-06 03:25:17 +00001972 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00001973 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00001974 // does not override a member function of a base class, the program is
1975 // ill-formed.
1976 bool HasOverriddenMethods =
1977 MD->begin_overridden_methods() != MD->end_overridden_methods();
1978 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1979 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1980 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001981}
1982
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001983void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1984 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1985 return;
1986 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1987 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1988 isa<CXXDestructorDecl>(MD))
1989 return;
1990
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001991 SourceLocation Loc = MD->getLocation();
1992 SourceLocation SpellingLoc = Loc;
1993 if (getSourceManager().isMacroArgExpansion(Loc))
1994 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1995 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1996 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00001997 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001998
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001999 if (MD->size_overridden_methods() > 0) {
2000 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2001 << MD->getDeclName();
2002 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2003 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2004 }
2005}
2006
Richard Smith18f07db2012-08-06 03:25:17 +00002007/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00002008/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00002009/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00002010bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2011 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00002012 FinalAttr *FA = Old->getAttr<FinalAttr>();
2013 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00002014 return false;
2015
2016 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00002017 << New->getDeclName()
2018 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00002019 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2020 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00002021}
2022
Daniel Jasper0baec5492012-06-06 08:32:04 +00002023static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00002024 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2025 // FIXME: Destruction of ObjC lifetime types has side-effects.
2026 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2027 return !RD->isCompleteDefinition() ||
2028 !RD->hasTrivialDefaultConstructor() ||
2029 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00002030 return false;
2031}
2032
John McCall5e77d762013-04-16 07:28:30 +00002033static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002034 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00002035 if (it->isDeclspecPropertyAttribute())
2036 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00002037 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00002038}
2039
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002040/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2041/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002042/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002043/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2044/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002045NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002046Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002047 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002048 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002049 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002050 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002051 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2052 DeclarationName Name = NameInfo.getName();
2053 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002054
2055 // For anonymous bitfields, the location should point to the type.
2056 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002057 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002058
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002059 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002060
John McCallb1cd7da2010-06-04 08:34:12 +00002061 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002062 assert(!DS.isFriendSpecified());
2063
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002064 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002065
John McCalldb632ac2012-09-25 07:32:39 +00002066 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2067 // The Microsoft extension __interface only permits public member functions
2068 // and prohibits constructors, destructors, operators, non-public member
2069 // functions, static methods and data members.
2070 unsigned InvalidDecl;
2071 bool ShowDeclName = true;
2072 if (!isFunc)
2073 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2074 else if (AS != AS_public)
2075 InvalidDecl = 2;
2076 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2077 InvalidDecl = 3;
2078 else switch (Name.getNameKind()) {
2079 case DeclarationName::CXXConstructorName:
2080 InvalidDecl = 4;
2081 ShowDeclName = false;
2082 break;
2083
2084 case DeclarationName::CXXDestructorName:
2085 InvalidDecl = 5;
2086 ShowDeclName = false;
2087 break;
2088
2089 case DeclarationName::CXXOperatorName:
2090 case DeclarationName::CXXConversionFunctionName:
2091 InvalidDecl = 6;
2092 break;
2093
2094 default:
2095 InvalidDecl = 0;
2096 break;
2097 }
2098
2099 if (InvalidDecl) {
2100 if (ShowDeclName)
2101 Diag(Loc, diag::err_invalid_member_in_interface)
2102 << (InvalidDecl-1) << Name;
2103 else
2104 Diag(Loc, diag::err_invalid_member_in_interface)
2105 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002106 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002107 }
2108 }
2109
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002110 // C++ 9.2p6: A member shall not be declared to have automatic storage
2111 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002112 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2113 // data members and cannot be applied to names declared const or static,
2114 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002115 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002116 case DeclSpec::SCS_unspecified:
2117 case DeclSpec::SCS_typedef:
2118 case DeclSpec::SCS_static:
2119 break;
2120 case DeclSpec::SCS_mutable:
2121 if (isFunc) {
2122 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002123
Richard Smithb4a9e862013-04-12 22:46:28 +00002124 // FIXME: It would be nicer if the keyword was ignored only for this
2125 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002126 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002127 }
2128 break;
2129 default:
2130 Diag(DS.getStorageClassSpecLoc(),
2131 diag::err_storageclass_invalid_for_member);
2132 D.getMutableDeclSpec().ClearStorageClassSpecs();
2133 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002134 }
2135
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002136 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2137 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002138 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002139
David Blaikie35506f82013-01-30 01:22:18 +00002140 if (DS.isConstexprSpecified() && isInstField) {
2141 SemaDiagnosticBuilder B =
2142 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2143 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2144 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002145 B << 0 << 0;
2146 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2147 B << FixItHint::CreateRemoval(ConstexprLoc);
2148 else {
2149 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2150 D.getMutableDeclSpec().ClearConstexprSpec();
2151 const char *PrevSpec;
2152 unsigned DiagID;
2153 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2154 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2155 (void)Failed;
2156 assert(!Failed && "Making a constexpr member const shouldn't fail");
2157 }
David Blaikie35506f82013-01-30 01:22:18 +00002158 } else {
2159 B << 1;
2160 const char *PrevSpec;
2161 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002162 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002163 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2164 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002165 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002166 "This is the only DeclSpec that should fail to be applied");
2167 B << 1;
2168 } else {
2169 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2170 isInstField = false;
2171 }
2172 }
2173 }
2174
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002175 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002176 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002177 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002178
2179 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002180 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002181 Diag(Loc, diag::err_bad_variable_name)
2182 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002183 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002184 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002185
Benjamin Kramer365082d2012-05-19 16:34:46 +00002186 IdentifierInfo *II = Name.getAsIdentifierInfo();
2187
Douglas Gregor7c26c042011-09-21 14:40:46 +00002188 // Member field could not be with "template" keyword.
2189 // So TemplateParameterLists should be empty in this case.
2190 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002191 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002192 if (TemplateParams->size()) {
2193 // There is no such thing as a member field template.
2194 Diag(D.getIdentifierLoc(), diag::err_template_member)
2195 << II
2196 << SourceRange(TemplateParams->getTemplateLoc(),
2197 TemplateParams->getRAngleLoc());
2198 } else {
2199 // There is an extraneous 'template<>' for this member.
2200 Diag(TemplateParams->getTemplateLoc(),
2201 diag::err_template_member_noparams)
2202 << II
2203 << SourceRange(TemplateParams->getTemplateLoc(),
2204 TemplateParams->getRAngleLoc());
2205 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002206 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002207 }
2208
Douglas Gregora007d362010-10-13 22:19:53 +00002209 if (SS.isSet() && !SS.isInvalid()) {
2210 // The user provided a superfluous scope specifier inside a class
2211 // definition:
2212 //
2213 // class X {
2214 // int X::member;
2215 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002216 if (DeclContext *DC = computeDeclContext(SS, false))
2217 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002218 else
2219 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2220 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002221
Douglas Gregora007d362010-10-13 22:19:53 +00002222 SS.clear();
2223 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002224
John McCall5e77d762013-04-16 07:28:30 +00002225 AttributeList *MSPropertyAttr =
2226 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002227 if (MSPropertyAttr) {
2228 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2229 BitWidth, InitStyle, AS, MSPropertyAttr);
2230 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002231 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002232 isInstField = false;
2233 } else {
2234 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2235 BitWidth, InitStyle, AS);
2236 assert(Member && "HandleField never returns null");
2237 }
2238 } else {
Nico Webera089c7c2015-01-16 21:09:43 +00002239 assert(InitStyle == ICIS_NoInit ||
2240 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002241
2242 Member = HandleDeclarator(S, D, TemplateParameterLists);
2243 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002244 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002245
2246 // Non-instance-fields can't have a bitfield.
2247 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002248 if (Member->isInvalidDecl()) {
2249 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002250 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002251 // C++ 9.6p3: A bit-field shall not be a static member.
2252 // "static member 'A' cannot be a bit-field"
2253 Diag(Loc, diag::err_static_not_bitfield)
2254 << Name << BitWidth->getSourceRange();
2255 } else if (isa<TypedefDecl>(Member)) {
2256 // "typedef member 'x' cannot be a bit-field"
2257 Diag(Loc, diag::err_typedef_not_bitfield)
2258 << Name << BitWidth->getSourceRange();
2259 } else {
2260 // A function typedef ("typedef int f(); f a;").
2261 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2262 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002263 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002264 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002265 }
Mike Stump11289f42009-09-09 15:08:12 +00002266
Craig Topperc3ec1492014-05-26 06:22:03 +00002267 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002268 Member->setInvalidDecl();
2269 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002270
2271 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002272
Larisse Voufo39a1e502013-08-06 01:03:05 +00002273 // If we have declared a member function template or static data member
2274 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002275 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2276 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002277 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2278 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002279 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002280
Richard Smith18f07db2012-08-06 03:25:17 +00002281 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002282 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002283 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002284 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2285 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002286
Douglas Gregorf2f08062011-03-08 17:10:18 +00002287 if (VS.getLastLocation().isValid()) {
2288 // Update the end location of a method that has a virt-specifiers.
2289 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2290 MD->setRangeEnd(VS.getLastLocation());
2291 }
Richard Smith18f07db2012-08-06 03:25:17 +00002292
Anders Carlssonc87f8612011-01-20 06:29:02 +00002293 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002294
Douglas Gregor92751d42008-11-17 22:58:34 +00002295 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002296
Daniel Jasper0baec5492012-06-06 08:32:04 +00002297 if (isInstField) {
2298 FieldDecl *FD = cast<FieldDecl>(Member);
2299 FieldCollector->Add(FD);
2300
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002301 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002302 // Remember all explicit private FieldDecls that have a name, no side
2303 // effects and are not part of a dependent type declaration.
2304 if (!FD->isImplicit() && FD->getDeclName() &&
2305 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002306 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002307 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002308 !InitializationHasSideEffects(*FD))
2309 UnusedPrivateFields.insert(FD);
2310 }
2311 }
2312
John McCall48871652010-08-21 09:40:31 +00002313 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002314}
2315
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002316namespace {
2317 class UninitializedFieldVisitor
2318 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2319 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002320 // List of Decls to generate a warning on. Also remove Decls that become
2321 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002322 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00002323 // List of base classes of the record. Classes are removed after their
2324 // initializers.
2325 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00002326 // Vector of decls to be removed from the Decl set prior to visiting the
2327 // nodes. These Decls may have been initialized in the prior initializer.
2328 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002329 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002330 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00002331 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00002332 // InitList is true, special case initialization of FieldDecls matching
2333 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002334 bool InitList;
2335 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002336 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2337
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002338 public:
2339 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002340 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00002341 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2342 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2343 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2344 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002345
Richard Trieufa1d0a72014-10-17 20:56:10 +00002346 // Returns true if the use of ME is not an uninitialized use.
2347 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2348 bool CheckReferenceOnly) {
2349 llvm::SmallVector<FieldDecl*, 4> Fields;
2350 bool ReferenceField = false;
2351 while (ME) {
2352 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2353 if (!FD)
2354 return false;
2355 Fields.push_back(FD);
2356 if (FD->getType()->isReferenceType())
2357 ReferenceField = true;
2358 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2359 }
2360
2361 // Binding a reference to an unintialized field is not an
2362 // uninitialized use.
2363 if (CheckReferenceOnly && !ReferenceField)
2364 return true;
2365
2366 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2367 // Discard the first field since it is the field decl that is being
2368 // initialized.
2369 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2370 UsedFieldIndex.push_back((*I)->getFieldIndex());
2371 }
2372
2373 for (auto UsedIter = UsedFieldIndex.begin(),
2374 UsedEnd = UsedFieldIndex.end(),
2375 OrigIter = InitFieldIndex.begin(),
2376 OrigEnd = InitFieldIndex.end();
2377 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2378 if (*UsedIter < *OrigIter)
2379 return true;
2380 if (*UsedIter > *OrigIter)
2381 break;
2382 }
2383
2384 return false;
2385 }
2386
Richard Trieu2d779b92014-10-01 03:44:58 +00002387 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2388 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002389 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2390 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002391
Richard Trieu1bc22c12013-09-13 03:20:53 +00002392 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2393 // or union.
2394 MemberExpr *FieldME = ME;
2395
Richard Trieu2d779b92014-10-01 03:44:58 +00002396 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2397
Richard Trieu1bc22c12013-09-13 03:20:53 +00002398 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00002399 while (MemberExpr *SubME =
2400 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002401
Richard Trieufa1d0a72014-10-17 20:56:10 +00002402 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002403 return;
2404
Richard Trieufa1d0a72014-10-17 20:56:10 +00002405 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002406 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00002407 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002408
Richard Trieu2d779b92014-10-01 03:44:58 +00002409 if (!FieldME->getType().isPODType(S.Context))
2410 AllPODFields = false;
2411
Richard Trieu3630c392014-11-21 03:10:30 +00002412 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00002413 }
2414
Richard Trieu3630c392014-11-21 03:10:30 +00002415 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00002416 return;
2417
Richard Trieu2d779b92014-10-01 03:44:58 +00002418 if (AddressOf && AllPODFields)
2419 return;
2420
Richard Trieu406e65c2013-09-20 03:03:06 +00002421 ValueDecl* FoundVD = FieldME->getMemberDecl();
2422
Richard Trieu3630c392014-11-21 03:10:30 +00002423 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2424 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2425 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2426 }
2427
2428 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2429 QualType T = BaseCast->getType();
2430 if (T->isPointerType() &&
2431 BaseClasses.count(T->getPointeeType())) {
2432 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2433 << T->getPointeeType() << FoundVD;
2434 }
2435 }
2436 }
2437
Richard Trieuef64e942013-10-25 00:56:00 +00002438 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002439 return;
2440
Richard Trieuef64e942013-10-25 00:56:00 +00002441 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002442
Richard Trieufa1d0a72014-10-17 20:56:10 +00002443 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2444 // Special checking for initializer lists.
2445 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2446 return;
2447 }
2448 } else {
2449 // Prevent double warnings on use of unbounded references.
2450 if (CheckReferenceOnly && !IsReference)
2451 return;
2452 }
Richard Trieuef64e942013-10-25 00:56:00 +00002453
2454 unsigned diag = IsReference
2455 ? diag::warn_reference_field_is_uninit
2456 : diag::warn_field_is_uninit;
2457 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2458 if (Constructor)
2459 S.Diag(Constructor->getLocation(),
2460 diag::note_uninit_in_this_constructor)
2461 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2462
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002463 }
2464
Richard Trieu2d779b92014-10-01 03:44:58 +00002465 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002466 E = E->IgnoreParens();
2467
2468 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002469 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2470 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002471 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002472 }
2473
2474 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002475 Visit(CO->getCond());
2476 HandleValue(CO->getTrueExpr(), AddressOf);
2477 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002478 return;
2479 }
2480
2481 if (BinaryConditionalOperator *BCO =
2482 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002483 Visit(BCO->getCond());
2484 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002485 return;
2486 }
2487
Richard Trieuabf6ec42014-08-27 22:15:10 +00002488 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002489 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00002490 return;
2491 }
2492
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002493 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2494 switch (BO->getOpcode()) {
2495 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00002496 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002497 case(BO_PtrMemD):
2498 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00002499 HandleValue(BO->getLHS(), AddressOf);
2500 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002501 return;
2502 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00002503 Visit(BO->getLHS());
2504 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002505 return;
2506 }
2507 }
Richard Trieu2d779b92014-10-01 03:44:58 +00002508
2509 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002510 }
2511
Richard Trieufa1d0a72014-10-17 20:56:10 +00002512 void CheckInitListExpr(InitListExpr *ILE) {
2513 InitFieldIndex.push_back(0);
2514 for (auto Child : ILE->children()) {
2515 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2516 CheckInitListExpr(SubList);
2517 } else {
2518 Visit(Child);
2519 }
2520 ++InitFieldIndex.back();
2521 }
2522 InitFieldIndex.pop_back();
2523 }
2524
Richard Trieu8d08a272014-08-28 03:23:47 +00002525 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002526 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002527 // Remove Decls that may have been initialized in the previous
2528 // initializer.
2529 for (ValueDecl* VD : DeclsToRemove)
2530 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00002531 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00002532
Richard Trieu8d08a272014-08-28 03:23:47 +00002533 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002534 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2535
2536 if (ILE && Field) {
2537 InitList = true;
2538 InitListFieldDecl = Field;
2539 InitFieldIndex.clear();
2540 CheckInitListExpr(ILE);
2541 } else {
2542 InitList = false;
2543 Visit(E);
2544 }
2545
Richard Trieu8d08a272014-08-28 03:23:47 +00002546 if (Field)
2547 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00002548 if (BaseClass)
2549 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00002550 }
2551
Richard Trieu1bc22c12013-09-13 03:20:53 +00002552 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002553 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00002554 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002555 }
2556
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002557 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002558 if (E->getCastKind() == CK_LValueToRValue) {
2559 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2560 return;
2561 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002562
2563 Inherited::VisitImplicitCastExpr(E);
2564 }
2565
Richard Trieu1bc22c12013-09-13 03:20:53 +00002566 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002567 if (E->getConstructor()->isCopyConstructor()) {
2568 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00002569 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2570 if (ILE->getNumInits() == 1)
2571 ArgExpr = ILE->getInit(0);
2572 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2573 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00002574 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00002575 HandleValue(ArgExpr, false /*AddressOf*/);
2576 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00002577 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002578 Inherited::VisitCXXConstructExpr(E);
2579 }
2580
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002581 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2582 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00002583 if (isa<MemberExpr>(Callee)) {
2584 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00002585 for (auto Arg : E->arguments())
2586 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00002587 return;
2588 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002589
2590 Inherited::VisitCXXMemberCallExpr(E);
2591 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002592
Richard Trieu11fd0792014-08-26 04:30:55 +00002593 void VisitCallExpr(CallExpr *E) {
2594 // Treat std::move as a use.
2595 if (E->getNumArgs() == 1) {
2596 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00002597 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2598 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002599 HandleValue(E->getArg(0), false /*AddressOf*/);
2600 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00002601 }
2602 }
2603 }
2604
2605 Inherited::VisitCallExpr(E);
2606 }
2607
Richard Trieud4a01362014-10-31 21:10:22 +00002608 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2609 Expr *Callee = E->getCallee();
2610
2611 if (isa<UnresolvedLookupExpr>(Callee))
2612 return Inherited::VisitCXXOperatorCallExpr(E);
2613
2614 Visit(Callee);
2615 for (auto Arg : E->arguments())
2616 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2617 }
2618
Richard Trieu406e65c2013-09-20 03:03:06 +00002619 void VisitBinaryOperator(BinaryOperator *E) {
2620 // If a field assignment is detected, remove the field from the
2621 // uninitiailized field set.
2622 if (E->getOpcode() == BO_Assign)
2623 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2624 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002625 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002626 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002627
Richard Trieu52b8b602014-09-25 01:15:40 +00002628 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002629 HandleValue(E->getLHS(), false /*AddressOf*/);
2630 Visit(E->getRHS());
2631 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00002632 }
2633
Richard Trieu406e65c2013-09-20 03:03:06 +00002634 Inherited::VisitBinaryOperator(E);
2635 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002636
2637 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002638 if (E->isIncrementDecrementOp()) {
2639 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2640 return;
2641 }
2642 if (E->getOpcode() == UO_AddrOf) {
2643 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2644 HandleValue(ME->getBase(), true /*AddressOf*/);
2645 return;
2646 }
2647 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002648
2649 Inherited::VisitUnaryOperator(E);
2650 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002651 };
Richard Trieuef64e942013-10-25 00:56:00 +00002652
2653 // Diagnose value-uses of fields to initialize themselves, e.g.
2654 // foo(foo)
2655 // where foo is not also a parameter to the constructor.
2656 // Also diagnose across field uninitialized use such as
2657 // x(y), y(x)
2658 // TODO: implement -Wuninitialized and fold this into that framework.
2659 static void DiagnoseUninitializedFields(
2660 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2661
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002662 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2663 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002664 return;
2665 }
2666
2667 if (Constructor->isInvalidDecl())
2668 return;
2669
2670 const CXXRecordDecl *RD = Constructor->getParent();
2671
Richard Trieu353a4b42014-10-22 05:21:59 +00002672 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00002673 return;
2674
Richard Trieuef64e942013-10-25 00:56:00 +00002675 // Holds fields that are uninitialized.
2676 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2677
2678 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002679 for (auto *I : RD->decls()) {
2680 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002681 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002682 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002683 UninitializedFields.insert(IFD->getAnonField());
2684 }
2685 }
2686
Richard Trieu3630c392014-11-21 03:10:30 +00002687 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2688 for (auto I : RD->bases())
2689 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2690
2691 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002692 return;
2693
2694 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00002695 UninitializedFields,
2696 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00002697
Aaron Ballman0ad78302014-03-13 17:34:31 +00002698 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00002699 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002700 break;
2701
Aaron Ballman0ad78302014-03-13 17:34:31 +00002702 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002703 if (!InitExpr)
2704 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002705
Richard Trieu8d08a272014-08-28 03:23:47 +00002706 if (CXXDefaultInitExpr *Default =
2707 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2708 InitExpr = Default->getExpr();
2709 if (!InitExpr)
2710 continue;
2711 // In class initializers will point to the constructor.
2712 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002713 FieldInit->getAnyMember(),
2714 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002715 } else {
2716 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00002717 FieldInit->getAnyMember(),
2718 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002719 }
Richard Trieuef64e942013-10-25 00:56:00 +00002720 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002721 }
2722} // namespace
2723
Richard Smith74108172014-01-17 03:11:34 +00002724/// \brief Enter a new C++ default initializer scope. After calling this, the
2725/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2726/// parsing or instantiating the initializer failed.
2727void Sema::ActOnStartCXXInClassMemberInitializer() {
2728 // Create a synthetic function scope to represent the call to the constructor
2729 // that notionally surrounds a use of this initializer.
2730 PushFunctionScope();
2731}
2732
2733/// \brief This is invoked after parsing an in-class initializer for a
2734/// non-static C++ class member, and after instantiating an in-class initializer
2735/// in a class template. Such actions are deferred until the class is complete.
2736void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2737 SourceLocation InitLoc,
2738 Expr *InitExpr) {
2739 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002740 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002741
David Majnemer87ff66c2014-12-13 11:34:16 +00002742 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2743 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00002744 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002745
2746 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00002747 D->setInvalidDecl();
2748 if (FD)
2749 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002750 return;
2751 }
2752
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002753 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2754 FD->setInvalidDecl();
2755 FD->removeInClassInitializer();
2756 return;
2757 }
2758
Richard Smith938f40b2011-06-11 17:19:42 +00002759 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002760 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002761 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002762 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002763 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002764 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002765 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2766 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002767 if (Init.isInvalid()) {
2768 FD->setInvalidDecl();
2769 return;
2770 }
Richard Smith938f40b2011-06-11 17:19:42 +00002771 }
2772
Richard Smith945f8d32013-01-14 22:39:08 +00002773 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002774 // The initialization of each base and member constitutes a
2775 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002776 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002777 if (Init.isInvalid()) {
2778 FD->setInvalidDecl();
2779 return;
2780 }
2781
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002782 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002783
2784 FD->setInClassInitializer(InitExpr);
2785}
2786
Douglas Gregor15e77a22009-12-31 09:10:24 +00002787/// \brief Find the direct and/or virtual base specifiers that
2788/// correspond to the given base type, for use in base initialization
2789/// within a constructor.
2790static bool FindBaseInitializer(Sema &SemaRef,
2791 CXXRecordDecl *ClassDecl,
2792 QualType BaseType,
2793 const CXXBaseSpecifier *&DirectBaseSpec,
2794 const CXXBaseSpecifier *&VirtualBaseSpec) {
2795 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002796 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002797 for (const auto &Base : ClassDecl->bases()) {
2798 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002799 // We found a direct base of this type. That's what we're
2800 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002801 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002802 break;
2803 }
2804 }
2805
2806 // Check for a virtual base class.
2807 // FIXME: We might be able to short-circuit this if we know in advance that
2808 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002809 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002810 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2811 // We haven't found a base yet; search the class hierarchy for a
2812 // virtual base class.
2813 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2814 /*DetectVirtual=*/false);
2815 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2816 BaseType, Paths)) {
2817 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2818 Path != Paths.end(); ++Path) {
2819 if (Path->back().Base->isVirtual()) {
2820 VirtualBaseSpec = Path->back().Base;
2821 break;
2822 }
2823 }
2824 }
2825 }
2826
2827 return DirectBaseSpec || VirtualBaseSpec;
2828}
2829
Sebastian Redla74948d2011-09-24 17:48:25 +00002830/// \brief Handle a C++ member initializer using braced-init-list syntax.
2831MemInitResult
2832Sema::ActOnMemInitializer(Decl *ConstructorD,
2833 Scope *S,
2834 CXXScopeSpec &SS,
2835 IdentifierInfo *MemberOrBase,
2836 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002837 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002838 SourceLocation IdLoc,
2839 Expr *InitList,
2840 SourceLocation EllipsisLoc) {
2841 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002842 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002843 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002844}
2845
2846/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002847MemInitResult
John McCall48871652010-08-21 09:40:31 +00002848Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002849 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002850 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002851 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002852 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002853 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002854 SourceLocation IdLoc,
2855 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002856 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002857 SourceLocation RParenLoc,
2858 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002859 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002860 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002861 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002862 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002863}
2864
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002865namespace {
2866
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002867// Callback to only accept typo corrections that can be a valid C++ member
2868// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002869class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002870public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002871 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2872 : ClassDecl(ClassDecl) {}
2873
Craig Toppera798a9d2014-03-02 09:32:10 +00002874 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002875 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2876 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2877 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002878 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002879 }
2880 return false;
2881 }
2882
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002883private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002884 CXXRecordDecl *ClassDecl;
2885};
2886
2887}
2888
Sebastian Redla74948d2011-09-24 17:48:25 +00002889/// \brief Handle a C++ member initializer.
2890MemInitResult
2891Sema::BuildMemInitializer(Decl *ConstructorD,
2892 Scope *S,
2893 CXXScopeSpec &SS,
2894 IdentifierInfo *MemberOrBase,
2895 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002896 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002897 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002898 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002899 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00002900 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2901 if (!Res.isUsable())
2902 return true;
2903 Init = Res.get();
2904
Douglas Gregor71a57182009-06-22 23:20:33 +00002905 if (!ConstructorD)
2906 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002907
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002908 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002909
2910 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002911 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002912 if (!Constructor) {
2913 // The user wrote a constructor initializer on a function that is
2914 // not a C++ constructor. Ignore the error for now, because we may
2915 // have more member initializers coming; we'll diagnose it just
2916 // once in ActOnMemInitializers.
2917 return true;
2918 }
2919
2920 CXXRecordDecl *ClassDecl = Constructor->getParent();
2921
2922 // C++ [class.base.init]p2:
2923 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002924 // constructor's class and, if not found in that scope, are looked
2925 // up in the scope containing the constructor's definition.
2926 // [Note: if the constructor's class contains a member with the
2927 // same name as a direct or virtual base class of the class, a
2928 // mem-initializer-id naming the member or base class and composed
2929 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002930 // mem-initializer-id for the hidden base class may be specified
2931 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002932 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002933 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00002934 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002935 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002936 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002937 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2938 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002939 if (EllipsisLoc.isValid())
2940 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002941 << MemberOrBase
2942 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002943
Sebastian Redla9351792012-02-11 23:51:47 +00002944 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002945 }
Francois Pichetd583da02010-12-04 09:14:42 +00002946 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002947 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002948 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002949 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002950 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002951
2952 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002953 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002954 } else if (DS.getTypeSpecType() == TST_decltype) {
2955 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002956 } else {
2957 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2958 LookupParsedName(R, S, &SS);
2959
2960 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2961 if (!TyD) {
2962 if (R.isAmbiguous()) return true;
2963
John McCallda6841b2010-04-09 19:01:14 +00002964 // We don't want access-control diagnostics here.
2965 R.suppressDiagnostics();
2966
Douglas Gregora3b624a2010-01-19 06:46:48 +00002967 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2968 bool NotUnknownSpecialization = false;
2969 DeclContext *DC = computeDeclContext(SS, false);
2970 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2971 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2972
2973 if (!NotUnknownSpecialization) {
2974 // When the scope specifier can refer to a member of an unknown
2975 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002976 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2977 SS.getWithLocInContext(Context),
2978 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002979 if (BaseType.isNull())
2980 return true;
2981
Douglas Gregora3b624a2010-01-19 06:46:48 +00002982 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002983 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002984 }
2985 }
2986
Douglas Gregor15e77a22009-12-31 09:10:24 +00002987 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002988 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00002989 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002990 (Corr = CorrectTypo(
2991 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2992 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2993 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002994 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002995 // We have found a non-static data member with a similar
2996 // name to what was typed; complain and initialize that
2997 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002998 diagnoseTypo(Corr,
2999 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3000 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00003001 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003002 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003003 const CXXBaseSpecifier *DirectBaseSpec;
3004 const CXXBaseSpecifier *VirtualBaseSpec;
3005 if (FindBaseInitializer(*this, ClassDecl,
3006 Context.getTypeDeclType(Type),
3007 DirectBaseSpec, VirtualBaseSpec)) {
3008 // We have found a direct or virtual base class with a
3009 // similar name to what was typed; complain and initialize
3010 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00003011 diagnoseTypo(Corr,
3012 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3013 << MemberOrBase << false,
3014 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00003015
Richard Smithf9b15102013-08-17 00:46:16 +00003016 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3017 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003018 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00003019 diag::note_base_class_specified_here)
3020 << BaseSpec->getType()
3021 << BaseSpec->getSourceRange();
3022
Douglas Gregor15e77a22009-12-31 09:10:24 +00003023 TyD = Type;
3024 }
3025 }
3026 }
3027
Douglas Gregora3b624a2010-01-19 06:46:48 +00003028 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003029 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00003030 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00003031 return true;
3032 }
John McCallb5a0d312009-12-21 10:41:20 +00003033 }
3034
Douglas Gregora3b624a2010-01-19 06:46:48 +00003035 if (BaseType.isNull()) {
3036 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00003037 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Aaron Ballman4a979672014-01-03 13:56:08 +00003038 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00003039 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00003040 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3041 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00003042 }
3043 }
Mike Stump11289f42009-09-09 15:08:12 +00003044
John McCallbcd03502009-12-07 02:54:59 +00003045 if (!TInfo)
3046 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003047
Sebastian Redla9351792012-02-11 23:51:47 +00003048 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003049}
3050
Chandler Carruth599deef2011-09-03 01:14:15 +00003051/// Checks a member initializer expression for cases where reference (or
3052/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003053static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3054 Expr *Init,
3055 SourceLocation IdLoc) {
3056 QualType MemberTy = Member->getType();
3057
3058 // We only handle pointers and references currently.
3059 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3060 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3061 return;
3062
3063 const bool IsPointer = MemberTy->isPointerType();
3064 if (IsPointer) {
3065 if (const UnaryOperator *Op
3066 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3067 // The only case we're worried about with pointers requires taking the
3068 // address.
3069 if (Op->getOpcode() != UO_AddrOf)
3070 return;
3071
3072 Init = Op->getSubExpr();
3073 } else {
3074 // We only handle address-of expression initializers for pointers.
3075 return;
3076 }
3077 }
3078
Richard Smithe3b28bc2013-06-12 21:51:50 +00003079 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003080 // We only warn when referring to a non-reference parameter declaration.
3081 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3082 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003083 return;
3084
3085 S.Diag(Init->getExprLoc(),
3086 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3087 : diag::warn_bind_ref_member_to_parameter)
3088 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003089 } else {
3090 // Other initializers are fine.
3091 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003092 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003093
3094 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3095 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003096}
3097
John McCallfaf5fb42010-08-26 23:41:50 +00003098MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003099Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003100 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003101 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3102 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3103 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003104 "Member must be a FieldDecl or IndirectFieldDecl");
3105
Sebastian Redla9351792012-02-11 23:51:47 +00003106 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003107 return true;
3108
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003109 if (Member->isInvalidDecl())
3110 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003111
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003112 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003113 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003114 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003115 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003116 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003117 } else {
3118 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003119 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003120 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003121
Sebastian Redla9351792012-02-11 23:51:47 +00003122 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003123
Sebastian Redla9351792012-02-11 23:51:47 +00003124 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003125 // Can't check initialization for a member of dependent type or when
3126 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003127 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003128 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003129 bool InitList = false;
3130 if (isa<InitListExpr>(Init)) {
3131 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003132 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003133 }
3134
Chandler Carruthd44c3102010-12-06 09:23:57 +00003135 // Initialize the member.
3136 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003137 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3138 : InitializedEntity::InitializeMember(IndirectMember,
3139 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003140 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003141 InitList ? InitializationKind::CreateDirectList(IdLoc)
3142 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3143 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003144
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003145 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003146 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3147 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003148 if (MemberInit.isInvalid())
3149 return true;
3150
Richard Smith736a9472013-06-12 20:42:33 +00003151 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3152
Richard Smith945f8d32013-01-14 22:39:08 +00003153 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003154 // The initialization of each base and member constitutes a
3155 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003156 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003157 if (MemberInit.isInvalid())
3158 return true;
3159
Richard Smithd59b8322012-12-19 01:39:02 +00003160 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003161 }
3162
Chandler Carruthd44c3102010-12-06 09:23:57 +00003163 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003164 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3165 InitRange.getBegin(), Init,
3166 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003167 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003168 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3169 InitRange.getBegin(), Init,
3170 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003171 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003172}
3173
John McCallfaf5fb42010-08-26 23:41:50 +00003174MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003175Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003176 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003177 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003178 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003179 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003180 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003181 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003182
Sebastian Redl0501c632012-02-12 16:37:36 +00003183 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003184 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003185 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3186 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003187 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003188 }
3189
Sebastian Redla9351792012-02-11 23:51:47 +00003190 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003191 // Initialize the object.
3192 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3193 QualType(ClassDecl->getTypeForDecl(), 0));
3194 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003195 InitList ? InitializationKind::CreateDirectList(NameLoc)
3196 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3197 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003198 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003199 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003200 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003201 if (DelegationInit.isInvalid())
3202 return true;
3203
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003204 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3205 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003206
Richard Smith945f8d32013-01-14 22:39:08 +00003207 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003208 // The initialization of each base and member constitutes a
3209 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003210 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3211 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003212 if (DelegationInit.isInvalid())
3213 return true;
3214
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003215 // If we are in a dependent context, template instantiation will
3216 // perform this type-checking again. Just save the arguments that we
3217 // received in a ParenListExpr.
3218 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3219 // of the information that we have about the base
3220 // initializer. However, deconstructing the ASTs is a dicey process,
3221 // and this approach is far more likely to get the corner cases right.
3222 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003223 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003224
Sebastian Redla9351792012-02-11 23:51:47 +00003225 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003226 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003227 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003228}
3229
3230MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003231Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003232 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003233 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003234 SourceLocation BaseLoc
3235 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003236
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003237 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3238 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3239 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3240
3241 // C++ [class.base.init]p2:
3242 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003243 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003244 // of that class, the mem-initializer is ill-formed. A
3245 // mem-initializer-list can initialize a base class using any
3246 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003247 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003248
Sebastian Redla9351792012-02-11 23:51:47 +00003249 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003250 if (EllipsisLoc.isValid()) {
3251 // This is a pack expansion.
3252 if (!BaseType->containsUnexpandedParameterPack()) {
3253 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003254 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003255
Douglas Gregor44e7df62011-01-04 00:32:56 +00003256 EllipsisLoc = SourceLocation();
3257 }
3258 } else {
3259 // Check for any unexpanded parameter packs.
3260 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3261 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003262
Sebastian Redla9351792012-02-11 23:51:47 +00003263 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003264 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003265 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003266
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003267 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003268 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3269 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003270 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003271 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3272 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003273 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003274
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003275 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3276 VirtualBaseSpec);
3277
3278 // C++ [base.class.init]p2:
3279 // Unless the mem-initializer-id names a nonstatic data member of the
3280 // constructor's class or a direct or virtual base of that class, the
3281 // mem-initializer is ill-formed.
3282 if (!DirectBaseSpec && !VirtualBaseSpec) {
3283 // If the class has any dependent bases, then it's possible that
3284 // one of those types will resolve to the same type as
3285 // BaseType. Therefore, just treat this as a dependent base
3286 // class initialization. FIXME: Should we try to check the
3287 // initialization anyway? It seems odd.
3288 if (ClassDecl->hasAnyDependentBases())
3289 Dependent = true;
3290 else
3291 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3292 << BaseType << Context.getTypeDeclType(ClassDecl)
3293 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3294 }
3295 }
3296
3297 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003298 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003299
Sebastian Redla74948d2011-09-24 17:48:25 +00003300 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3301 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003302 InitRange.getBegin(), Init,
3303 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003304 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003305
3306 // C++ [base.class.init]p2:
3307 // If a mem-initializer-id is ambiguous because it designates both
3308 // a direct non-virtual base class and an inherited virtual base
3309 // class, the mem-initializer is ill-formed.
3310 if (DirectBaseSpec && VirtualBaseSpec)
3311 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003312 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003313
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003314 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003315 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003316 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003317
3318 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003319 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003320 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003321 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003322 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003323 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003324 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003325
3326 InitializedEntity BaseEntity =
3327 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3328 InitializationKind Kind =
3329 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3330 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3331 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003332 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003333 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003334 if (BaseInit.isInvalid())
3335 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003336
Richard Smith945f8d32013-01-14 22:39:08 +00003337 // C++11 [class.base.init]p7:
3338 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003339 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003340 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003341 if (BaseInit.isInvalid())
3342 return true;
3343
3344 // If we are in a dependent context, template instantiation will
3345 // perform this type-checking again. Just save the arguments that we
3346 // received in a ParenListExpr.
3347 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3348 // of the information that we have about the base
3349 // initializer. However, deconstructing the ASTs is a dicey process,
3350 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003351 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003352 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003353
Alexis Hunt1d792652011-01-08 20:30:50 +00003354 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003355 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003356 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003357 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003358 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003359}
3360
Sebastian Redl22653ba2011-08-30 19:58:05 +00003361// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003362static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3363 if (T.isNull()) T = E->getType();
3364 QualType TargetType = SemaRef.BuildReferenceType(
3365 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003366 SourceLocation ExprLoc = E->getLocStart();
3367 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3368 TargetType, ExprLoc);
3369
3370 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3371 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003372 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003373}
3374
Anders Carlsson1b00e242010-04-23 03:10:23 +00003375/// ImplicitInitializerKind - How an implicit base or member initializer should
3376/// initialize its base or member.
3377enum ImplicitInitializerKind {
3378 IIK_Default,
3379 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003380 IIK_Move,
3381 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003382};
3383
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003384static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003385BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003386 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003387 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003388 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003389 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003390 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003391 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3392 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003393
John McCalldadc5752010-08-24 06:29:42 +00003394 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003395
3396 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003397 case IIK_Inherit: {
3398 const CXXRecordDecl *Inherited =
3399 Constructor->getInheritedConstructor()->getParent();
3400 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3401 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3402 // C++11 [class.inhctor]p8:
3403 // Each expression in the expression-list is of the form
3404 // static_cast<T&&>(p), where p is the name of the corresponding
3405 // constructor parameter and T is the declared type of p.
3406 SmallVector<Expr*, 16> Args;
3407 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3408 ParmVarDecl *PD = Constructor->getParamDecl(I);
3409 ExprResult ArgExpr =
3410 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3411 VK_LValue, SourceLocation());
3412 if (ArgExpr.isInvalid())
3413 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003414 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003415 }
3416
3417 InitializationKind InitKind = InitializationKind::CreateDirect(
3418 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003419 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003420 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3421 break;
3422 }
3423 }
3424 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003425 case IIK_Default: {
3426 InitializationKind InitKind
3427 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003428 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3429 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003430 break;
3431 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003432
Sebastian Redl22653ba2011-08-30 19:58:05 +00003433 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003434 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003435 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003436 ParmVarDecl *Param = Constructor->getParamDecl(0);
3437 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003438
Anders Carlsson1b00e242010-04-23 03:10:23 +00003439 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003440 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003441 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003442 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003443 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003444
Eli Friedmanfa0df832012-02-02 03:46:19 +00003445 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3446
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003447 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003448 QualType ArgTy =
3449 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3450 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003451
Sebastian Redl22653ba2011-08-30 19:58:05 +00003452 if (Moving) {
3453 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3454 }
3455
John McCallcf142162010-08-07 06:22:56 +00003456 CXXCastPath BasePath;
3457 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003458 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3459 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003460 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003461 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003462
Anders Carlsson1b00e242010-04-23 03:10:23 +00003463 InitializationKind InitKind
3464 = InitializationKind::CreateDirect(Constructor->getLocation(),
3465 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003466 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3467 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003468 break;
3469 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003470 }
John McCallb268a282010-08-23 23:25:46 +00003471
Douglas Gregora40433a2010-12-07 00:41:46 +00003472 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003473 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003474 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003475
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003476 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003477 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003478 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3479 SourceLocation()),
3480 BaseSpec->isVirtual(),
3481 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003482 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003483 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003484 SourceLocation());
3485
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003486 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003487}
3488
Sebastian Redl22653ba2011-08-30 19:58:05 +00003489static bool RefersToRValueRef(Expr *MemRef) {
3490 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3491 return Referenced->getType()->isRValueReferenceType();
3492}
3493
Anders Carlsson3c1db572010-04-23 02:15:47 +00003494static bool
3495BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003496 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003497 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003498 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003499 if (Field->isInvalidDecl())
3500 return true;
3501
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003502 SourceLocation Loc = Constructor->getLocation();
3503
Sebastian Redl22653ba2011-08-30 19:58:05 +00003504 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3505 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003506 ParmVarDecl *Param = Constructor->getParamDecl(0);
3507 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003508
3509 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003510 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3511 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003512
Anders Carlsson423f5d82010-04-23 16:04:08 +00003513 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003514 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003515 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003516 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003517
Eli Friedmanfa0df832012-02-02 03:46:19 +00003518 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3519
Sebastian Redl22653ba2011-08-30 19:58:05 +00003520 if (Moving) {
3521 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3522 }
3523
Douglas Gregor94f9a482010-05-05 05:51:00 +00003524 // Build a reference to this field within the parameter.
3525 CXXScopeSpec SS;
3526 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3527 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003528 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3529 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003530 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003531 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003532 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003533 ParamType, Loc,
3534 /*IsArrow=*/false,
3535 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003536 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003537 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003538 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003539 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003540 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003541 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003542
3543 // C++11 [class.copy]p15:
3544 // - if a member m has rvalue reference type T&&, it is direct-initialized
3545 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003546 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003547 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003548 }
3549
Douglas Gregor94f9a482010-05-05 05:51:00 +00003550 // When the field we are copying is an array, create index variables for
3551 // each dimension of the array. We use these index variables to subscript
3552 // the source array, and other clients (e.g., CodeGen) will perform the
3553 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003554 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003555 QualType BaseType = Field->getType();
3556 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003557 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003558 while (const ConstantArrayType *Array
3559 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003560 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003561 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003562 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003563 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003564 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003565 llvm::raw_svector_ostream OS(Str);
3566 OS << "__i" << IndexVariables.size();
3567 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3568 }
3569 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003570 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003571 IterationVarName, SizeType,
3572 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003573 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003574 IndexVariables.push_back(IterationVar);
3575
3576 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003577 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003578 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003579 assert(!IterationVarRef.isInvalid() &&
3580 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003581 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003582 assert(!IterationVarRef.isInvalid() &&
3583 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003584
Douglas Gregor94f9a482010-05-05 05:51:00 +00003585 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003586 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3587 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003588 Loc);
3589 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003590 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003591
Douglas Gregor94f9a482010-05-05 05:51:00 +00003592 BaseType = Array->getElementType();
3593 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003594
3595 // The array subscript expression is an lvalue, which is wrong for moving.
3596 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003597 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003598
Douglas Gregor94f9a482010-05-05 05:51:00 +00003599 // Construct the entity that we will be initializing. For an array, this
3600 // will be first element in the array, which may require several levels
3601 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003602 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003603 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003604 if (Indirect)
3605 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3606 else
3607 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003608 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3609 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3610 0,
3611 Entities.back()));
3612
3613 // Direct-initialize to use the copy constructor.
3614 InitializationKind InitKind =
3615 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3616
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003617 Expr *CtorArgE = CtorArg.getAs<Expr>();
Nico Weber3b00fdc2015-03-07 19:52:39 +00003618 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3619 CtorArgE);
3620
John McCalldadc5752010-08-24 06:29:42 +00003621 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003622 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003623 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003624 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003625 if (MemberInit.isInvalid())
3626 return true;
3627
Douglas Gregor493627b2011-08-10 15:22:55 +00003628 if (Indirect) {
3629 assert(IndexVariables.size() == 0 &&
3630 "Indirect field improperly initialized");
3631 CXXMemberInit
3632 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3633 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003634 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003635 Loc);
3636 } else
3637 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003638 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003639 Loc,
3640 IndexVariables.data(),
3641 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003642 return false;
3643 }
3644
Richard Smithc2bc61b2013-03-18 21:12:30 +00003645 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3646 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003647
Anders Carlsson3c1db572010-04-23 02:15:47 +00003648 QualType FieldBaseElementType =
3649 SemaRef.Context.getBaseElementType(Field->getType());
3650
Anders Carlsson3c1db572010-04-23 02:15:47 +00003651 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003652 InitializedEntity InitEntity
3653 = Indirect? InitializedEntity::InitializeMember(Indirect)
3654 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003655 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003656 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003657
3658 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3659 ExprResult MemberInit =
3660 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003661
Douglas Gregora40433a2010-12-07 00:41:46 +00003662 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003663 if (MemberInit.isInvalid())
3664 return true;
3665
Douglas Gregor493627b2011-08-10 15:22:55 +00003666 if (Indirect)
3667 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3668 Indirect, Loc,
3669 Loc,
3670 MemberInit.get(),
3671 Loc);
3672 else
3673 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3674 Field, Loc, Loc,
3675 MemberInit.get(),
3676 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003677 return false;
3678 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003679
Alexis Hunt8b455182011-05-17 00:19:05 +00003680 if (!Field->getParent()->isUnion()) {
3681 if (FieldBaseElementType->isReferenceType()) {
3682 SemaRef.Diag(Constructor->getLocation(),
3683 diag::err_uninitialized_member_in_ctor)
3684 << (int)Constructor->isImplicit()
3685 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3686 << 0 << Field->getDeclName();
3687 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3688 return true;
3689 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003690
Alexis Hunt8b455182011-05-17 00:19:05 +00003691 if (FieldBaseElementType.isConstQualified()) {
3692 SemaRef.Diag(Constructor->getLocation(),
3693 diag::err_uninitialized_member_in_ctor)
3694 << (int)Constructor->isImplicit()
3695 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3696 << 1 << Field->getDeclName();
3697 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3698 return true;
3699 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003700 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003701
David Blaikiebbafb8a2012-03-11 07:00:24 +00003702 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003703 FieldBaseElementType->isObjCRetainableType() &&
3704 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3705 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003706 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003707 // Default-initialize Objective-C pointers to NULL.
3708 CXXMemberInit
3709 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3710 Loc, Loc,
3711 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3712 Loc);
3713 return false;
3714 }
3715
Anders Carlsson3c1db572010-04-23 02:15:47 +00003716 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003717 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003718 return false;
3719}
John McCallbc83b3f2010-05-20 23:23:51 +00003720
3721namespace {
3722struct BaseAndFieldInfo {
3723 Sema &S;
3724 CXXConstructorDecl *Ctor;
3725 bool AnyErrorsInInits;
3726 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003727 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003728 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003729 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003730
3731 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3732 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003733 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3734 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003735 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003736 else if (Generated && Ctor->isMoveConstructor())
3737 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003738 else if (Ctor->getInheritedConstructor())
3739 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003740 else
3741 IIK = IIK_Default;
3742 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003743
3744 bool isImplicitCopyOrMove() const {
3745 switch (IIK) {
3746 case IIK_Copy:
3747 case IIK_Move:
3748 return true;
3749
3750 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003751 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003752 return false;
3753 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003754
3755 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003756 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003757
3758 bool addFieldInitializer(CXXCtorInitializer *Init) {
3759 AllToInit.push_back(Init);
3760
3761 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003762 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003763 S.UnusedPrivateFields.remove(Init->getAnyMember());
3764
3765 return false;
3766 }
John McCallbc83b3f2010-05-20 23:23:51 +00003767
Richard Smithab44d5b2013-12-10 08:25:00 +00003768 bool isInactiveUnionMember(FieldDecl *Field) {
3769 RecordDecl *Record = Field->getParent();
3770 if (!Record->isUnion())
3771 return false;
3772
Richard Smith8d183852013-12-10 20:56:03 +00003773 if (FieldDecl *Active =
3774 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003775 return Active != Field->getCanonicalDecl();
3776
3777 // In an implicit copy or move constructor, ignore any in-class initializer.
3778 if (isImplicitCopyOrMove())
3779 return true;
3780
3781 // If there's no explicit initialization, the field is active only if it
3782 // has an in-class initializer...
3783 if (Field->hasInClassInitializer())
3784 return false;
3785 // ... or it's an anonymous struct or union whose class has an in-class
3786 // initializer.
3787 if (!Field->isAnonymousStructOrUnion())
3788 return true;
3789 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3790 return !FieldRD->hasInClassInitializer();
3791 }
3792
3793 /// \brief Determine whether the given field is, or is within, a union member
3794 /// that is inactive (because there was an initializer given for a different
3795 /// member of the union, or because the union was not initialized at all).
3796 bool isWithinInactiveUnionMember(FieldDecl *Field,
3797 IndirectFieldDecl *Indirect) {
3798 if (!Indirect)
3799 return isInactiveUnionMember(Field);
3800
Aaron Ballman29c94602014-03-07 18:36:15 +00003801 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003802 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003803 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003804 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003805 }
3806 return false;
3807 }
3808};
Richard Smithc94ec842011-09-19 13:34:43 +00003809}
3810
Douglas Gregor10f939c2011-11-02 23:04:16 +00003811/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3812/// array type.
3813static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3814 if (T->isIncompleteArrayType())
3815 return true;
3816
3817 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3818 if (!ArrayT->getSize())
3819 return true;
3820
3821 T = ArrayT->getElementType();
3822 }
3823
3824 return false;
3825}
3826
Richard Smith938f40b2011-06-11 17:19:42 +00003827static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003828 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003829 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003830 if (Field->isInvalidDecl())
3831 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003832
Chandler Carruth139e9622010-06-30 02:59:29 +00003833 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003834 if (CXXCtorInitializer *Init =
3835 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003836 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003837
Richard Smithab44d5b2013-12-10 08:25:00 +00003838 // C++11 [class.base.init]p8:
3839 // if the entity is a non-static data member that has a
3840 // brace-or-equal-initializer and either
3841 // -- the constructor's class is a union and no other variant member of that
3842 // union is designated by a mem-initializer-id or
3843 // -- the constructor's class is not a union, and, if the entity is a member
3844 // of an anonymous union, no other member of that union is designated by
3845 // a mem-initializer-id,
3846 // the entity is initialized as specified in [dcl.init].
3847 //
3848 // We also apply the same rules to handle anonymous structs within anonymous
3849 // unions.
3850 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3851 return false;
3852
Douglas Gregor7db3e952011-11-28 20:03:15 +00003853 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003854 ExprResult DIE =
3855 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3856 if (DIE.isInvalid())
3857 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00003858 CXXCtorInitializer *Init;
3859 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003860 Init = new (SemaRef.Context)
3861 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3862 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00003863 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003864 Init = new (SemaRef.Context)
3865 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3866 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003867 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003868 }
3869
Douglas Gregor10f939c2011-11-02 23:04:16 +00003870 // Don't initialize incomplete or zero-length arrays.
3871 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3872 return false;
3873
John McCallbc83b3f2010-05-20 23:23:51 +00003874 // Don't try to build an implicit initializer if there were semantic
3875 // errors in any of the initializers (and therefore we might be
3876 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003877 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003878 return false;
3879
Craig Topperc3ec1492014-05-26 06:22:03 +00003880 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003881 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3882 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003883 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003884
Richard Smith0a8cfc72012-08-07 21:30:42 +00003885 if (!Init)
3886 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003887
Richard Smith0a8cfc72012-08-07 21:30:42 +00003888 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003889}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003890
3891bool
3892Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3893 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003894 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003895 Constructor->setNumCtorInitializers(1);
3896 CXXCtorInitializer **initializer =
3897 new (Context) CXXCtorInitializer*[1];
3898 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3899 Constructor->setCtorInitializers(initializer);
3900
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003901 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003902 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003903 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3904 }
3905
Alexis Hunte2622992011-05-05 00:05:47 +00003906 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003907
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003908 DiagnoseUninitializedFields(*this, Constructor);
3909
Alexis Hunt61bc1732011-05-01 07:04:31 +00003910 return false;
3911}
Douglas Gregor493627b2011-08-10 15:22:55 +00003912
David Blaikie3fc2f912013-01-17 05:26:25 +00003913bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3914 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003915 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003916 // Just store the initializers as written, they will be checked during
3917 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003918 if (!Initializers.empty()) {
3919 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003920 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003921 new (Context) CXXCtorInitializer*[Initializers.size()];
3922 memcpy(baseOrMemberInitializers, Initializers.data(),
3923 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003924 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003925 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003926
3927 // Let template instantiation know whether we had errors.
3928 if (AnyErrors)
3929 Constructor->setInvalidDecl();
3930
Anders Carlssondb0a9652010-04-02 06:26:44 +00003931 return false;
3932 }
3933
John McCallbc83b3f2010-05-20 23:23:51 +00003934 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003935
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003936 // We need to build the initializer AST according to order of construction
3937 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003938 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003939 if (!ClassDecl)
3940 return true;
3941
Eli Friedman9cf6b592009-11-09 19:20:36 +00003942 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003943
David Blaikie3fc2f912013-01-17 05:26:25 +00003944 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003945 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003946
Anders Carlssondb0a9652010-04-02 06:26:44 +00003947 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003948 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003949 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003950 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003951
3952 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003953 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003954 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003955 if (FD && FD->getParent()->isUnion())
3956 Info.ActiveUnionMember.insert(std::make_pair(
3957 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3958 }
3959 } else if (FieldDecl *FD = Member->getMember()) {
3960 if (FD->getParent()->isUnion())
3961 Info.ActiveUnionMember.insert(std::make_pair(
3962 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3963 }
3964 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003965 }
3966
Anders Carlsson43c64af2010-04-21 19:52:01 +00003967 // Keep track of the direct virtual bases.
3968 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003969 for (auto &I : ClassDecl->bases()) {
3970 if (I.isVirtual())
3971 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003972 }
3973
Anders Carlssondb0a9652010-04-02 06:26:44 +00003974 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003975 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003976 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003977 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003978 // [class.base.init]p7, per DR257:
3979 // A mem-initializer where the mem-initializer-id names a virtual base
3980 // class is ignored during execution of a constructor of any class that
3981 // is not the most derived class.
3982 if (ClassDecl->isAbstract()) {
3983 // FIXME: Provide a fixit to remove the base specifier. This requires
3984 // tracking the location of the associated comma for a base specifier.
3985 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003986 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003987 DiagnoseAbstractType(ClassDecl);
3988 }
3989
John McCallbc83b3f2010-05-20 23:23:51 +00003990 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003991 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3992 // [class.base.init]p8, per DR257:
3993 // If a given [...] base class is not named by a mem-initializer-id
3994 // [...] and the entity is not a virtual base class of an abstract
3995 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003996 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003997 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003998 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003999 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004000 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004001 HadError = true;
4002 continue;
4003 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004004
John McCallbc83b3f2010-05-20 23:23:51 +00004005 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004006 }
4007 }
Mike Stump11289f42009-09-09 15:08:12 +00004008
John McCallbc83b3f2010-05-20 23:23:51 +00004009 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004010 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004011 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00004012 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00004013 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004014
Alexis Hunt1d792652011-01-08 20:30:50 +00004015 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00004016 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00004017 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004018 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004019 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004020 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00004021 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004022 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004023 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004024 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00004025 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00004026
John McCallbc83b3f2010-05-20 23:23:51 +00004027 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004028 }
4029 }
Mike Stump11289f42009-09-09 15:08:12 +00004030
John McCallbc83b3f2010-05-20 23:23:51 +00004031 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00004032 for (auto *Mem : ClassDecl->decls()) {
4033 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004034 // C++ [class.bit]p2:
4035 // A declaration for a bit-field that omits the identifier declares an
4036 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4037 // initialized.
4038 if (F->isUnnamedBitfield())
4039 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004040
Sebastian Redl22653ba2011-08-30 19:58:05 +00004041 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004042 // handle anonymous struct/union fields based on their individual
4043 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004044 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004045 continue;
4046
4047 if (CollectFieldInitializer(*this, Info, F))
4048 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004049 continue;
4050 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004051
4052 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004053 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004054 continue;
4055
Aaron Ballman629afae2014-03-07 19:56:05 +00004056 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004057 if (F->getType()->isIncompleteArrayType()) {
4058 assert(ClassDecl->hasFlexibleArrayMember() &&
4059 "Incomplete array type is not valid");
4060 continue;
4061 }
4062
Douglas Gregor493627b2011-08-10 15:22:55 +00004063 // Initialize each field of an anonymous struct individually.
4064 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4065 HadError = true;
4066
4067 continue;
4068 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004069 }
Mike Stump11289f42009-09-09 15:08:12 +00004070
David Blaikie3fc2f912013-01-17 05:26:25 +00004071 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004072 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004073 Constructor->setNumCtorInitializers(NumInitializers);
4074 CXXCtorInitializer **baseOrMemberInitializers =
4075 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004076 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004077 NumInitializers * sizeof(CXXCtorInitializer*));
4078 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004079
John McCalla6309952010-03-16 21:39:52 +00004080 // Constructors implicitly reference the base and member
4081 // destructors.
4082 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4083 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004084 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004085
4086 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004087}
4088
David Blaikieb61b8152013-01-17 08:49:22 +00004089static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004090 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004091 const RecordDecl *RD = RT->getDecl();
4092 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004093 for (auto *Field : RD->fields())
4094 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004095 return;
4096 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004097 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004098 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004099}
4100
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004101static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4102 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004103}
4104
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004105static const void *GetKeyForMember(ASTContext &Context,
4106 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004107 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004108 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004109
Richard Smithcd45dbc2014-04-19 03:48:30 +00004110 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004111}
4112
David Blaikie3fc2f912013-01-17 05:26:25 +00004113static void DiagnoseBaseOrMemInitializerOrder(
4114 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4115 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004116 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004117 return;
Mike Stump11289f42009-09-09 15:08:12 +00004118
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004119 // Don't check initializers order unless the warning is enabled at the
4120 // location of at least one initializer.
4121 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004122 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004123 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004124 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4125 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004126 ShouldCheckOrder = true;
4127 break;
4128 }
4129 }
4130 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004131 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004132
John McCallbb7b6582010-04-10 07:37:23 +00004133 // Build the list of bases and members in the order that they'll
4134 // actually be initialized. The explicit initializers should be in
4135 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004136 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004137
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004138 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4139
John McCallbb7b6582010-04-10 07:37:23 +00004140 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004141 for (const auto &VBase : ClassDecl->vbases())
4142 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004143
John McCallbb7b6582010-04-10 07:37:23 +00004144 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004145 for (const auto &Base : ClassDecl->bases()) {
4146 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004147 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004148 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004149 }
Mike Stump11289f42009-09-09 15:08:12 +00004150
John McCallbb7b6582010-04-10 07:37:23 +00004151 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004152 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004153 if (Field->isUnnamedBitfield())
4154 continue;
4155
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004156 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004157 }
4158
John McCallbb7b6582010-04-10 07:37:23 +00004159 unsigned NumIdealInits = IdealInitKeys.size();
4160 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004161
Craig Topperc3ec1492014-05-26 06:22:03 +00004162 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004163 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004164 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004165 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004166
4167 // Scan forward to try to find this initializer in the idealized
4168 // initializers list.
4169 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4170 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004171 break;
John McCallbb7b6582010-04-10 07:37:23 +00004172
4173 // If we didn't find this initializer, it must be because we
4174 // scanned past it on a previous iteration. That can only
4175 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004176 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004177 Sema::SemaDiagnosticBuilder D =
4178 SemaRef.Diag(PrevInit->getSourceLocation(),
4179 diag::warn_initializer_out_of_order);
4180
Francois Pichetd583da02010-12-04 09:14:42 +00004181 if (PrevInit->isAnyMemberInitializer())
4182 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004183 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004184 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004185
Francois Pichetd583da02010-12-04 09:14:42 +00004186 if (Init->isAnyMemberInitializer())
4187 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004188 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004189 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004190
4191 // Move back to the initializer's location in the ideal list.
4192 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4193 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004194 break;
John McCallbb7b6582010-04-10 07:37:23 +00004195
4196 assert(IdealIndex != NumIdealInits &&
4197 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004198 }
John McCallbb7b6582010-04-10 07:37:23 +00004199
4200 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004201 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004202}
4203
John McCall23eebd92010-04-10 09:28:51 +00004204namespace {
4205bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004206 CXXCtorInitializer *Init,
4207 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004208 if (!PrevInit) {
4209 PrevInit = Init;
4210 return false;
4211 }
4212
Douglas Gregorea306a12013-03-25 23:28:23 +00004213 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004214 S.Diag(Init->getSourceLocation(),
4215 diag::err_multiple_mem_initialization)
4216 << Field->getDeclName()
4217 << Init->getSourceRange();
4218 else {
John McCall424cec92011-01-19 06:33:43 +00004219 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004220 assert(BaseClass && "neither field nor base");
4221 S.Diag(Init->getSourceLocation(),
4222 diag::err_multiple_base_initialization)
4223 << QualType(BaseClass, 0)
4224 << Init->getSourceRange();
4225 }
4226 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4227 << 0 << PrevInit->getSourceRange();
4228
4229 return true;
4230}
4231
Alexis Hunt1d792652011-01-08 20:30:50 +00004232typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004233typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4234
4235bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004236 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004237 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004238 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004239 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004240 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004241
4242 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004243 if (Parent->isUnion()) {
4244 UnionEntry &En = Unions[Parent];
4245 if (En.first && En.first != Child) {
4246 S.Diag(Init->getSourceLocation(),
4247 diag::err_multiple_mem_union_initialization)
4248 << Field->getDeclName()
4249 << Init->getSourceRange();
4250 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4251 << 0 << En.second->getSourceRange();
4252 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004253 }
4254 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004255 En.first = Child;
4256 En.second = Init;
4257 }
David Blaikie0f65d592011-11-17 06:01:57 +00004258 if (!Parent->isAnonymousStructOrUnion())
4259 return false;
John McCall23eebd92010-04-10 09:28:51 +00004260 }
4261
4262 Child = Parent;
4263 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004264 }
John McCall23eebd92010-04-10 09:28:51 +00004265
4266 return false;
4267}
4268}
4269
Anders Carlssone857b292010-04-02 03:37:03 +00004270/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004271void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004272 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004273 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004274 bool AnyErrors) {
4275 if (!ConstructorDecl)
4276 return;
4277
4278 AdjustDeclIfTemplate(ConstructorDecl);
4279
4280 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004281 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004282
4283 if (!Constructor) {
4284 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4285 return;
4286 }
4287
John McCall23eebd92010-04-10 09:28:51 +00004288 // Mapping for the duplicate initializers check.
4289 // For member initializers, this is keyed with a FieldDecl*.
4290 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004291 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004292
4293 // Mapping for the inconsistent anonymous-union initializers check.
4294 RedundantUnionMap MemberUnions;
4295
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004296 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004297 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004298 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004299
Abramo Bagnara341d7832010-05-26 18:09:23 +00004300 // Set the source order index.
4301 Init->setSourceOrder(i);
4302
Francois Pichetd583da02010-12-04 09:14:42 +00004303 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004304 const void *Key = GetKeyForMember(Context, Init);
4305 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004306 CheckRedundantUnionInit(*this, Init, MemberUnions))
4307 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004308 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004309 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004310 if (CheckRedundantInit(*this, Init, Members[Key]))
4311 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004312 } else {
4313 assert(Init->isDelegatingInitializer());
4314 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004315 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004316 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004317 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004318 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004319 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004320 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004321 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004322 // Return immediately as the initializer is set.
4323 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004324 }
Anders Carlssone857b292010-04-02 03:37:03 +00004325 }
4326
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004327 if (HadError)
4328 return;
4329
David Blaikie3fc2f912013-01-17 05:26:25 +00004330 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004331
David Blaikie3fc2f912013-01-17 05:26:25 +00004332 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004333
Richard Trieuef64e942013-10-25 00:56:00 +00004334 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004335}
4336
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004337void
John McCalla6309952010-03-16 21:39:52 +00004338Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4339 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004340 // Ignore dependent contexts. Also ignore unions, since their members never
4341 // have destructors implicitly called.
4342 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004343 return;
John McCall1064d7e2010-03-16 05:22:47 +00004344
4345 // FIXME: all the access-control diagnostics are positioned on the
4346 // field/base declaration. That's probably good; that said, the
4347 // user might reasonably want to know why the destructor is being
4348 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004349
Anders Carlssondee9a302009-11-17 04:44:12 +00004350 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004351 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004352 if (Field->isInvalidDecl())
4353 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004354
4355 // Don't destroy incomplete or zero-length arrays.
4356 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4357 continue;
4358
Anders Carlssondee9a302009-11-17 04:44:12 +00004359 QualType FieldType = Context.getBaseElementType(Field->getType());
4360
4361 const RecordType* RT = FieldType->getAs<RecordType>();
4362 if (!RT)
4363 continue;
4364
4365 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004366 if (FieldClassDecl->isInvalidDecl())
4367 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004368 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004369 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004370 // The destructor for an implicit anonymous union member is never invoked.
4371 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4372 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004373
Douglas Gregore71edda2010-07-01 22:47:18 +00004374 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004375 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004376 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004377 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004378 << Field->getDeclName()
4379 << FieldType);
4380
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004381 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004382 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004383 }
4384
John McCall1064d7e2010-03-16 05:22:47 +00004385 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4386
Anders Carlssondee9a302009-11-17 04:44:12 +00004387 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004388 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004389 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004390 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004391
4392 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004393 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004394 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004395
John McCall1064d7e2010-03-16 05:22:47 +00004396 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004397 // If our base class is invalid, we probably can't get its dtor anyway.
4398 if (BaseClassDecl->isInvalidDecl())
4399 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004400 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004401 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004402
Douglas Gregore71edda2010-07-01 22:47:18 +00004403 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004404 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004405
4406 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004407 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004408 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004409 << Base.getType()
4410 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004411 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004412
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004413 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004414 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004415 }
4416
4417 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004418 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004419 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004420 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004421
4422 // Ignore direct virtual bases.
4423 if (DirectVirtualBases.count(RT))
4424 continue;
4425
John McCall1064d7e2010-03-16 05:22:47 +00004426 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004427 // If our base class is invalid, we probably can't get its dtor anyway.
4428 if (BaseClassDecl->isInvalidDecl())
4429 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004430 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004431 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004432
Douglas Gregore71edda2010-07-01 22:47:18 +00004433 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004434 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004435 if (CheckDestructorAccess(
4436 ClassDecl->getLocation(), Dtor,
4437 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004438 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004439 Context.getTypeDeclType(ClassDecl)) ==
4440 AR_accessible) {
4441 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004442 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004443 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004444 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004445 }
John McCall1064d7e2010-03-16 05:22:47 +00004446
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004447 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004448 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004449 }
4450}
4451
John McCall48871652010-08-21 09:40:31 +00004452void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004453 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004454 return;
Mike Stump11289f42009-09-09 15:08:12 +00004455
Mike Stump11289f42009-09-09 15:08:12 +00004456 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004457 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004458 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004459 DiagnoseUninitializedFields(*this, Constructor);
4460 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004461}
4462
Mike Stump11289f42009-09-09 15:08:12 +00004463bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004464 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004465 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4466 unsigned DiagID;
4467 AbstractDiagSelID SelID;
4468
4469 public:
4470 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4471 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004472
Craig Toppera798a9d2014-03-02 09:32:10 +00004473 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004474 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004475 if (SelID == -1)
4476 S.Diag(Loc, DiagID) << T;
4477 else
4478 S.Diag(Loc, DiagID) << SelID << T;
4479 }
4480 } Diagnoser(DiagID, SelID);
4481
4482 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004483}
4484
Anders Carlssoneabf7702009-08-27 00:13:57 +00004485bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004486 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004487 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004488 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004489
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004490 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004491 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004492
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004493 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004494 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004495 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004496 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004497
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004498 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004499 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004500 }
Mike Stump11289f42009-09-09 15:08:12 +00004501
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004502 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004503 if (!RT)
4504 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004505
John McCall67da35c2010-02-04 22:26:26 +00004506 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004507
John McCall02db245d2010-08-18 09:41:07 +00004508 // We can't answer whether something is abstract until it has a
4509 // definition. If it's currently being defined, we'll walk back
4510 // over all the declarations when we have a full definition.
4511 const CXXRecordDecl *Def = RD->getDefinition();
4512 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004513 return false;
4514
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004515 if (!RD->isAbstract())
4516 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004517
Douglas Gregorae298422012-05-04 17:09:59 +00004518 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004519 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004520
John McCall02db245d2010-08-18 09:41:07 +00004521 return true;
4522}
4523
4524void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4525 // Check if we've already emitted the list of pure virtual functions
4526 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004527 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004528 return;
Mike Stump11289f42009-09-09 15:08:12 +00004529
Richard Smithbc46e432013-07-22 02:56:56 +00004530 // If the diagnostic is suppressed, don't emit the notes. We're only
4531 // going to emit them once, so try to attach them to a diagnostic we're
4532 // actually going to show.
4533 if (Diags.isLastDiagnosticIgnored())
4534 return;
4535
Douglas Gregor4165bd62010-03-23 23:47:56 +00004536 CXXFinalOverriderMap FinalOverriders;
4537 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004538
Anders Carlssona2f74f32010-06-03 01:00:02 +00004539 // Keep a set of seen pure methods so we won't diagnose the same method
4540 // more than once.
4541 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4542
Douglas Gregor4165bd62010-03-23 23:47:56 +00004543 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4544 MEnd = FinalOverriders.end();
4545 M != MEnd;
4546 ++M) {
4547 for (OverridingMethods::iterator SO = M->second.begin(),
4548 SOEnd = M->second.end();
4549 SO != SOEnd; ++SO) {
4550 // C++ [class.abstract]p4:
4551 // A class is abstract if it contains or inherits at least one
4552 // pure virtual function for which the final overrider is pure
4553 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004554
Douglas Gregor4165bd62010-03-23 23:47:56 +00004555 //
4556 if (SO->second.size() != 1)
4557 continue;
4558
4559 if (!SO->second.front().Method->isPure())
4560 continue;
4561
David Blaikie82e95a32014-11-19 07:49:47 +00004562 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00004563 continue;
4564
Douglas Gregor4165bd62010-03-23 23:47:56 +00004565 Diag(SO->second.front().Method->getLocation(),
4566 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004567 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004568 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004569 }
4570
4571 if (!PureVirtualClassDiagSet)
4572 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4573 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004574}
4575
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004576namespace {
John McCall02db245d2010-08-18 09:41:07 +00004577struct AbstractUsageInfo {
4578 Sema &S;
4579 CXXRecordDecl *Record;
4580 CanQualType AbstractType;
4581 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004582
John McCall02db245d2010-08-18 09:41:07 +00004583 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4584 : S(S), Record(Record),
4585 AbstractType(S.Context.getCanonicalType(
4586 S.Context.getTypeDeclType(Record))),
4587 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004588
John McCall02db245d2010-08-18 09:41:07 +00004589 void DiagnoseAbstractType() {
4590 if (Invalid) return;
4591 S.DiagnoseAbstractType(Record);
4592 Invalid = true;
4593 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004594
John McCall02db245d2010-08-18 09:41:07 +00004595 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4596};
4597
4598struct CheckAbstractUsage {
4599 AbstractUsageInfo &Info;
4600 const NamedDecl *Ctx;
4601
4602 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4603 : Info(Info), Ctx(Ctx) {}
4604
4605 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4606 switch (TL.getTypeLocClass()) {
4607#define ABSTRACT_TYPELOC(CLASS, PARENT)
4608#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004609 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004610#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004611 }
John McCall02db245d2010-08-18 09:41:07 +00004612 }
Mike Stump11289f42009-09-09 15:08:12 +00004613
John McCall02db245d2010-08-18 09:41:07 +00004614 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004615 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004616 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4617 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004618 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004619
4620 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004621 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004622 }
John McCall02db245d2010-08-18 09:41:07 +00004623 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004624
John McCall02db245d2010-08-18 09:41:07 +00004625 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4626 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4627 }
Mike Stump11289f42009-09-09 15:08:12 +00004628
John McCall02db245d2010-08-18 09:41:07 +00004629 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4630 // Visit the type parameters from a permissive context.
4631 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4632 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4633 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4634 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4635 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4636 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004637 }
John McCall02db245d2010-08-18 09:41:07 +00004638 }
Mike Stump11289f42009-09-09 15:08:12 +00004639
John McCall02db245d2010-08-18 09:41:07 +00004640 // Visit pointee types from a permissive context.
4641#define CheckPolymorphic(Type) \
4642 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4643 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4644 }
4645 CheckPolymorphic(PointerTypeLoc)
4646 CheckPolymorphic(ReferenceTypeLoc)
4647 CheckPolymorphic(MemberPointerTypeLoc)
4648 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004649 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004650
John McCall02db245d2010-08-18 09:41:07 +00004651 /// Handle all the types we haven't given a more specific
4652 /// implementation for above.
4653 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4654 // Every other kind of type that we haven't called out already
4655 // that has an inner type is either (1) sugar or (2) contains that
4656 // inner type in some way as a subobject.
4657 if (TypeLoc Next = TL.getNextTypeLoc())
4658 return Visit(Next, Sel);
4659
4660 // If there's no inner type and we're in a permissive context,
4661 // don't diagnose.
4662 if (Sel == Sema::AbstractNone) return;
4663
4664 // Check whether the type matches the abstract type.
4665 QualType T = TL.getType();
4666 if (T->isArrayType()) {
4667 Sel = Sema::AbstractArrayType;
4668 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004669 }
John McCall02db245d2010-08-18 09:41:07 +00004670 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4671 if (CT != Info.AbstractType) return;
4672
4673 // It matched; do some magic.
4674 if (Sel == Sema::AbstractArrayType) {
4675 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4676 << T << TL.getSourceRange();
4677 } else {
4678 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4679 << Sel << T << TL.getSourceRange();
4680 }
4681 Info.DiagnoseAbstractType();
4682 }
4683};
4684
4685void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4686 Sema::AbstractDiagSelID Sel) {
4687 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4688}
4689
4690}
4691
4692/// Check for invalid uses of an abstract type in a method declaration.
4693static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4694 CXXMethodDecl *MD) {
4695 // No need to do the check on definitions, which require that
4696 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004697 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004698 return;
4699
4700 // For safety's sake, just ignore it if we don't have type source
4701 // information. This should never happen for non-implicit methods,
4702 // but...
4703 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4704 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4705}
4706
4707/// Check for invalid uses of an abstract type within a class definition.
4708static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4709 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004710 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004711 if (D->isImplicit()) continue;
4712
4713 // Methods and method templates.
4714 if (isa<CXXMethodDecl>(D)) {
4715 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4716 } else if (isa<FunctionTemplateDecl>(D)) {
4717 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4718 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4719
4720 // Fields and static variables.
4721 } else if (isa<FieldDecl>(D)) {
4722 FieldDecl *FD = cast<FieldDecl>(D);
4723 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4724 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4725 } else if (isa<VarDecl>(D)) {
4726 VarDecl *VD = cast<VarDecl>(D);
4727 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4728 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4729
4730 // Nested classes and class templates.
4731 } else if (isa<CXXRecordDecl>(D)) {
4732 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4733 } else if (isa<ClassTemplateDecl>(D)) {
4734 CheckAbstractClassUsage(Info,
4735 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4736 }
4737 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004738}
4739
Hans Wennborg853ae942014-05-30 16:59:42 +00004740/// \brief Check class-level dllimport/dllexport attribute.
4741static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4742 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004743
4744 // MSVC inherits DLL attributes to partial class template specializations.
4745 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4746 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4747 if (Attr *TemplateAttr =
4748 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4749 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4750 A->setInherited(true);
4751 ClassAttr = A;
4752 }
4753 }
4754 }
4755
Hans Wennborg853ae942014-05-30 16:59:42 +00004756 if (!ClassAttr)
4757 return;
4758
Hans Wennborg8313c762014-11-03 16:09:16 +00004759 if (!Class->isExternallyVisible()) {
4760 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4761 << Class << ClassAttr;
4762 return;
4763 }
4764
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004765 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4766 !ClassAttr->isInherited()) {
4767 // Diagnose dll attributes on members of class with dll attribute.
4768 for (Decl *Member : Class->decls()) {
4769 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4770 continue;
4771 InheritableAttr *MemberAttr = getDLLAttr(Member);
4772 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4773 continue;
4774
4775 S.Diag(MemberAttr->getLocation(),
4776 diag::err_attribute_dll_member_of_dll_class)
4777 << MemberAttr << ClassAttr;
4778 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4779 Member->setInvalidDecl();
4780 }
4781 }
4782
4783 if (Class->getDescribedClassTemplate())
4784 // Don't inherit dll attribute until the template is instantiated.
4785 return;
4786
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004787 // The class is either imported or exported.
4788 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4789 const bool ClassImported = !ClassExported;
Hans Wennborg853ae942014-05-30 16:59:42 +00004790
Hans Wennborgfd76d912015-01-15 21:18:30 +00004791 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4792
4793 // Don't dllexport explicit class template instantiation declarations.
4794 if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) {
4795 Class->dropAttr<DLLExportAttr>();
4796 return;
4797 }
4798
Hans Wennborg853ae942014-05-30 16:59:42 +00004799 // Force declaration of implicit members so they can inherit the attribute.
4800 S.ForceDeclarationOfImplicitMembers(Class);
4801
4802 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4803 // seem to be true in practice?
4804
Hans Wennborg853ae942014-05-30 16:59:42 +00004805 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004806 VarDecl *VD = dyn_cast<VarDecl>(Member);
4807 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4808
4809 // Only methods and static fields inherit the attributes.
4810 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004811 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004812
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004813 if (MD) {
4814 // Don't process deleted methods.
4815 if (MD->isDeleted())
4816 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004817
David Majnemer30f058a2015-05-11 03:00:22 +00004818 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00004819 // MinGW does not import or export inline methods.
David Majnemer30f058a2015-05-11 03:00:22 +00004820 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4821 continue;
4822
4823 // MSVC versions before 2015 don't export the move assignment operators,
4824 // so don't attempt to import them if we have a definition.
4825 if (ClassImported && MD->isMoveAssignmentOperator() &&
David Majnemerb710a932015-05-11 03:57:49 +00004826 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00004827 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004828 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00004829 }
4830
Hans Wennborg287231c2015-04-22 04:05:17 +00004831 if (!cast<NamedDecl>(Member)->isExternallyVisible())
4832 continue;
4833
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004834 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004835 auto *NewAttr =
4836 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4837 NewAttr->setInherited(true);
4838 Member->addAttr(NewAttr);
4839 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004840
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004841 if (MD && ClassExported) {
4842 if (MD->isUserProvided()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004843 // Instantiate non-default class member functions ...
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004844
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004845 // .. except for certain kinds of template specializations.
4846 if (TSK == TSK_ExplicitInstantiationDeclaration)
4847 continue;
4848 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4849 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004850
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004851 S.MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg45810b42014-12-16 01:15:01 +00004852
4853 // The function will be passed to the consumer when its definition is
4854 // encountered.
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004855 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4856 MD->isCopyAssignmentOperator() ||
4857 MD->isMoveAssignmentOperator()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004858 // Synthesize and instantiate non-trivial implicit methods, explicitly
4859 // defaulted methods, and the copy and move assignment operators. The
4860 // latter are exported even if they are trivial, because the address of
4861 // an operator can be taken and should compare equal accross libraries.
Hans Wennborg58703732015-02-21 01:07:24 +00004862 DiagnosticErrorTrap Trap(S.Diags);
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004863 S.MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg58703732015-02-21 01:07:24 +00004864 if (Trap.hasErrorOccurred()) {
4865 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4866 << Class->getName() << !S.getLangOpts().CPlusPlus11;
4867 break;
4868 }
Hans Wennborg45810b42014-12-16 01:15:01 +00004869
4870 // There is no later point when we will see the definition of this
4871 // function, so pass it to the consumer now.
4872 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
Hans Wennborg853ae942014-05-30 16:59:42 +00004873 }
4874 }
4875 }
4876}
4877
Douglas Gregorc99f1552009-12-03 18:33:45 +00004878/// \brief Perform semantic checks on a class definition that has been
4879/// completing, introducing implicitly-declared members, checking for
4880/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004881void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004882 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004883 return;
4884
John McCall02db245d2010-08-18 09:41:07 +00004885 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4886 AbstractUsageInfo Info(*this, Record);
4887 CheckAbstractClassUsage(Info, Record);
4888 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004889
4890 // If this is not an aggregate type and has no user-declared constructor,
4891 // complain about any non-static data members of reference or const scalar
4892 // type, since they will never get initializers.
4893 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004894 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4895 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004896 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004897 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004898 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004899 continue;
4900
Douglas Gregor454a5b62010-04-15 00:00:53 +00004901 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004902 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004903 if (!Complained) {
4904 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4905 << Record->getTagKind() << Record;
4906 Complained = true;
4907 }
4908
4909 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4910 << F->getType()->isReferenceType()
4911 << F->getDeclName();
4912 }
4913 }
4914 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004915
Douglas Gregor36c22a22010-10-15 13:21:21 +00004916 if (Record->getIdentifier()) {
4917 // C++ [class.mem]p13:
4918 // If T is the name of a class, then each of the following shall have a
4919 // name different from T:
4920 // - every member of every anonymous union that is a member of class T.
4921 //
4922 // C++ [class.mem]p14:
4923 // In addition, if class T has a user-declared constructor (12.1), every
4924 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004925 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4926 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4927 ++I) {
4928 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004929 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4930 isa<IndirectFieldDecl>(D)) {
4931 Diag(D->getLocation(), diag::err_member_name_of_class)
4932 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004933 break;
4934 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004935 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004936 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004937
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004938 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004939 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004940 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004941 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4942 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004943 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4944 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4945 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004946
David Majnemera5433082013-10-18 00:33:31 +00004947 if (Record->isAbstract()) {
4948 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4949 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4950 << FA->isSpelledAsSealed();
4951 DiagnoseAbstractType(Record);
4952 }
David Blaikie348df502012-09-21 03:21:07 +00004953 }
4954
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004955 bool HasMethodWithOverrideControl = false,
4956 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004957 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004958 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004959 // See if a method overloads virtual methods in a base
4960 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004961 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004962 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004963 if (M->hasAttr<OverrideAttr>())
4964 HasMethodWithOverrideControl = true;
4965 else if (M->size_overridden_methods() > 0)
4966 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00004967 // Check whether the explicitly-defaulted special members are valid.
4968 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004969 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004970
4971 // For an explicitly defaulted or deleted special member, we defer
4972 // determining triviality until the class is complete. That time is now!
4973 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004974 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004975 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004976 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004977
4978 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004979 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004980 }
4981 }
4982 }
4983 }
4984
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004985 if (HasMethodWithOverrideControl &&
4986 HasOverridingMethodWithoutOverrideControl) {
4987 // At least one method has the 'override' control declared.
4988 // Diagnose all other overridden methods which do not have 'override' specified on them.
4989 for (auto *M : Record->methods())
4990 DiagnoseAbsenceOfOverrideControl(M);
4991 }
Sebastian Redl08905022011-02-05 19:23:19 +00004992
John McCall95833f32014-02-27 20:30:49 +00004993 // ms_struct is a request to use the same ABI rules as MSVC. Check
4994 // whether this class uses any C++ features that are implemented
4995 // completely differently in MSVC, and if so, emit a diagnostic.
4996 // That diagnostic defaults to an error, but we allow projects to
4997 // map it down to a warning (or ignore it). It's a fairly common
4998 // practice among users of the ms_struct pragma to mass-annotate
4999 // headers, sweeping up a bunch of types that the project doesn't
5000 // really rely on MSVC-compatible layout for. We must therefore
5001 // support "ms_struct except for C++ stuff" as a secondary ABI.
5002 if (Record->isMsStruct(Context) &&
5003 (Record->isPolymorphic() || Record->getNumBases())) {
5004 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005005 }
5006
Richard Smithc2bc61b2013-03-18 21:12:30 +00005007 // Declare inheriting constructors. We do this eagerly here because:
5008 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00005009 // constructors from different classes.
5010 // - The lazy declaration of the other implicit constructors is so as to not
5011 // waste space and performance on classes that are not meant to be
5012 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00005013 // have inheriting constructors.
5014 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00005015
5016 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005017}
5018
Richard Smith41c35d62013-11-27 03:39:20 +00005019/// Look up the special member function that would be called by a special
5020/// member function for a subobject of class type.
5021///
5022/// \param Class The class type of the subobject.
5023/// \param CSM The kind of special member function.
5024/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5025/// \param ConstRHS True if this is a copy operation with a const object
5026/// on its RHS, that is, if the argument to the outer special member
5027/// function is 'const' and this is not a field marked 'mutable'.
5028static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5029 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5030 unsigned FieldQuals, bool ConstRHS) {
5031 unsigned LHSQuals = 0;
5032 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5033 LHSQuals = FieldQuals;
5034
5035 unsigned RHSQuals = FieldQuals;
5036 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5037 RHSQuals = 0;
5038 else if (ConstRHS)
5039 RHSQuals |= Qualifiers::Const;
5040
5041 return S.LookupSpecialMember(Class, CSM,
5042 RHSQuals & Qualifiers::Const,
5043 RHSQuals & Qualifiers::Volatile,
5044 false,
5045 LHSQuals & Qualifiers::Const,
5046 LHSQuals & Qualifiers::Volatile);
5047}
5048
Richard Smithb5800092012-06-10 05:43:50 +00005049/// Is the special member function which would be selected to perform the
5050/// specified operation on the specified class type a constexpr constructor?
5051static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5052 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00005053 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00005054 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005055 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005056 if (!SMOR || !SMOR->getMethod())
5057 // A constructor we wouldn't select can't be "involved in initializing"
5058 // anything.
5059 return true;
5060 return SMOR->getMethod()->isConstexpr();
5061}
5062
5063/// Determine whether the specified special member function would be constexpr
5064/// if it were implicitly defined.
5065static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5066 Sema::CXXSpecialMember CSM,
5067 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005068 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005069 return false;
5070
5071 // C++11 [dcl.constexpr]p4:
5072 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005073 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005074 switch (CSM) {
5075 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005076 // Since default constructor lookup is essentially trivial (and cannot
5077 // involve, for instance, template instantiation), we compute whether a
5078 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5079 //
5080 // This is important for performance; we need to know whether the default
5081 // constructor is constexpr to determine whether the type is a literal type.
5082 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5083
Richard Smithb5800092012-06-10 05:43:50 +00005084 case Sema::CXXCopyConstructor:
5085 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005086 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005087 break;
5088
5089 case Sema::CXXCopyAssignment:
5090 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005091 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005092 return false;
5093 // In C++1y, we need to perform overload resolution.
5094 Ctor = false;
5095 break;
5096
Richard Smithb5800092012-06-10 05:43:50 +00005097 case Sema::CXXDestructor:
5098 case Sema::CXXInvalid:
5099 return false;
5100 }
5101
5102 // -- if the class is a non-empty union, or for each non-empty anonymous
5103 // union member of a non-union class, exactly one non-static data member
5104 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005105 //
5106 // If we squint, this is guaranteed, since exactly one non-static data member
5107 // will be initialized (if the constructor isn't deleted), we just don't know
5108 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00005109 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00005110 return true;
Richard Smithb5800092012-06-10 05:43:50 +00005111
5112 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00005113 if (Ctor && ClassDecl->getNumVBases())
5114 return false;
5115
5116 // C++1y [class.copy]p26:
5117 // -- [the class] is a literal type, and
5118 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00005119 return false;
5120
5121 // -- every constructor involved in initializing [...] base class
5122 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00005123 // -- the assignment operator selected to copy/move each direct base
5124 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00005125 for (const auto &B : ClassDecl->bases()) {
5126 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00005127 if (!BaseType) continue;
5128
5129 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005130 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00005131 return false;
5132 }
5133
5134 // -- every constructor involved in initializing non-static data members
5135 // [...] shall be a constexpr constructor;
5136 // -- every non-static data member and base class sub-object shall be
5137 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005138 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005139 // thereof), the assignment operator selected to copy/move that member is
5140 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005141 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005142 if (F->isInvalidDecl())
5143 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005144 QualType BaseType = S.Context.getBaseElementType(F->getType());
5145 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005146 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005147 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5148 BaseType.getCVRQualifiers(),
5149 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005150 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005151 }
5152 }
5153
5154 // All OK, it's constexpr!
5155 return true;
5156}
5157
Richard Smithd3b5c9082012-07-27 04:22:15 +00005158static Sema::ImplicitExceptionSpecification
5159computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5160 switch (S.getSpecialMember(MD)) {
5161 case Sema::CXXDefaultConstructor:
5162 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5163 case Sema::CXXCopyConstructor:
5164 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5165 case Sema::CXXCopyAssignment:
5166 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5167 case Sema::CXXMoveConstructor:
5168 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5169 case Sema::CXXMoveAssignment:
5170 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5171 case Sema::CXXDestructor:
5172 return S.ComputeDefaultedDtorExceptionSpec(MD);
5173 case Sema::CXXInvalid:
5174 break;
5175 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00005176 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5177 "only special members have implicit exception specs");
5178 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00005179}
5180
Reid Kleckner78af0702013-08-27 23:08:25 +00005181static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5182 CXXMethodDecl *MD) {
5183 FunctionProtoType::ExtProtoInfo EPI;
5184
5185 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00005186 EPI.ExceptionSpec.Type = EST_Unevaluated;
5187 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00005188
5189 // Set the calling convention to the default for C++ instance methods.
5190 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5191 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5192 /*IsCXXMethod=*/true));
5193 return EPI;
5194}
5195
Richard Smithd3b5c9082012-07-27 04:22:15 +00005196void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5197 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5198 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5199 return;
5200
Richard Smith7f782272012-07-30 23:48:14 +00005201 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00005202 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00005203
Richard Smith7f782272012-07-30 23:48:14 +00005204 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00005205 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00005206
5207 // A user-provided destructor can be defined outside the class. When that
5208 // happens, be sure to update the exception specification on both
5209 // declarations.
5210 const FunctionProtoType *CanonicalFPT =
5211 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5212 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00005213 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00005214}
5215
Richard Smithb9e90b12012-05-15 04:39:51 +00005216void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5217 CXXRecordDecl *RD = MD->getParent();
5218 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005219
Richard Smithb9e90b12012-05-15 04:39:51 +00005220 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5221 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00005222
5223 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00005224 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00005225 bool First = MD == MD->getCanonicalDecl();
5226
5227 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005228
5229 // C++11 [dcl.fct.def.default]p1:
5230 // A function that is explicitly defaulted shall
5231 // -- be a special member function (checked elsewhere),
5232 // -- have the same type (except for ref-qualifiers, and except that a
5233 // copy operation can take a non-const reference) as an implicit
5234 // declaration, and
5235 // -- not have default arguments.
5236 unsigned ExpectedParams = 1;
5237 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5238 ExpectedParams = 0;
5239 if (MD->getNumParams() != ExpectedParams) {
5240 // This also checks for default arguments: a copy or move constructor with a
5241 // default argument is classified as a default constructor, and assignment
5242 // operations and destructors can't have default arguments.
5243 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5244 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00005245 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00005246 } else if (MD->isVariadic()) {
5247 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5248 << CSM << MD->getSourceRange();
5249 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00005250 }
5251
Richard Smithb9e90b12012-05-15 04:39:51 +00005252 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00005253
Richard Smithb5800092012-06-10 05:43:50 +00005254 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005255 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00005256 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00005257 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00005258 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00005259
Richard Smithb9e90b12012-05-15 04:39:51 +00005260 QualType ReturnType = Context.VoidTy;
5261 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5262 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00005263 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00005264 QualType ExpectedReturnType =
5265 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5266 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5267 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5268 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5269 HadError = true;
5270 }
5271
5272 // A defaulted special member cannot have cv-qualifiers.
5273 if (Type->getTypeQuals()) {
5274 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005275 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00005276 HadError = true;
5277 }
5278 }
5279
5280 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00005281 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00005282 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005283 if (ExpectedParams && ArgType->isReferenceType()) {
5284 // Argument must be reference to possibly-const T.
5285 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00005286 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00005287
5288 if (ReferentType.isVolatileQualified()) {
5289 Diag(MD->getLocation(),
5290 diag::err_defaulted_special_member_volatile_param) << CSM;
5291 HadError = true;
5292 }
5293
Richard Smithb5800092012-06-10 05:43:50 +00005294 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005295 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5296 Diag(MD->getLocation(),
5297 diag::err_defaulted_special_member_copy_const_param)
5298 << (CSM == CXXCopyAssignment);
5299 // FIXME: Explain why this special member can't be const.
5300 } else {
5301 Diag(MD->getLocation(),
5302 diag::err_defaulted_special_member_move_const_param)
5303 << (CSM == CXXMoveAssignment);
5304 }
5305 HadError = true;
5306 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005307 } else if (ExpectedParams) {
5308 // A copy assignment operator can take its argument by value, but a
5309 // defaulted one cannot.
5310 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005311 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005312 HadError = true;
5313 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005314
Richard Smithcc36f692011-12-22 02:22:31 +00005315 // C++11 [dcl.fct.def.default]p2:
5316 // An explicitly-defaulted function may be declared constexpr only if it
5317 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005318 // Do not apply this rule to members of class templates, since core issue 1358
5319 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005320 // functions which cannot be constexpr (for non-constructors in C++11 and for
5321 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005322 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5323 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005324 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005325 : isa<CXXConstructorDecl>(MD)) &&
5326 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005327 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5328 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005329 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005330 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005331 }
Richard Smithbd305122012-12-11 01:14:52 +00005332
Richard Smithcc36f692011-12-22 02:22:31 +00005333 // and may have an explicit exception-specification only if it is compatible
5334 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005335 if (Type->hasExceptionSpec()) {
5336 // Delay the check if this is the first declaration of the special member,
5337 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005338 if (First) {
5339 // If the exception specification needs to be instantiated, do so now,
5340 // before we clobber it with an EST_Unevaluated specification below.
5341 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5342 InstantiateExceptionSpec(MD->getLocStart(), MD);
5343 Type = MD->getType()->getAs<FunctionProtoType>();
5344 }
Richard Smithbd305122012-12-11 01:14:52 +00005345 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005346 } else
Richard Smithbd305122012-12-11 01:14:52 +00005347 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5348 }
Richard Smithcc36f692011-12-22 02:22:31 +00005349
5350 // If a function is explicitly defaulted on its first declaration,
5351 if (First) {
5352 // -- it is implicitly considered to be constexpr if the implicit
5353 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005354 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005355
Richard Smithb9e90b12012-05-15 04:39:51 +00005356 // -- it is implicitly considered to have the same exception-specification
5357 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005358 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005359 EPI.ExceptionSpec.Type = EST_Unevaluated;
5360 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005361 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005362 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005363 ExpectedParams),
5364 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005365 }
5366
Richard Smithb9e90b12012-05-15 04:39:51 +00005367 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005368 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005369 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005370 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005371 // C++11 [dcl.fct.def.default]p4:
5372 // [For a] user-provided explicitly-defaulted function [...] if such a
5373 // function is implicitly defined as deleted, the program is ill-formed.
5374 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005375 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005376 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005377 }
5378 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005379
Richard Smithb9e90b12012-05-15 04:39:51 +00005380 if (HadError)
5381 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005382}
5383
Richard Smithbd305122012-12-11 01:14:52 +00005384/// Check whether the exception specification provided for an
5385/// explicitly-defaulted special member matches the exception specification
5386/// that would have been generated for an implicit special member, per
5387/// C++11 [dcl.fct.def.default]p2.
5388void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5389 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00005390 // If the exception specification was explicitly specified but hadn't been
5391 // parsed when the method was defaulted, grab it now.
5392 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5393 SpecifiedType =
5394 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5395
Richard Smithbd305122012-12-11 01:14:52 +00005396 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005397 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5398 /*IsCXXMethod=*/true);
5399 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005400 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5401 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005402 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005403 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005404
5405 // Ensure that it matches.
5406 CheckEquivalentExceptionSpec(
5407 PDiag(diag::err_incorrect_defaulted_exception_spec)
5408 << getSpecialMember(MD), PDiag(),
5409 ImplicitType, SourceLocation(),
5410 SpecifiedType, MD->getLocation());
5411}
5412
Alp Tokerae3a9442013-10-18 05:54:19 +00005413void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00005414 decltype(DelayedExceptionSpecChecks) Checks;
5415 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005416
Richard Smith88f45492014-11-22 03:09:05 +00005417 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00005418 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5419
5420 // Perform any deferred checking of exception specifications for virtual
5421 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00005422 for (auto &Check : Checks)
5423 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00005424
5425 // Check that any explicitly-defaulted methods have exception specifications
5426 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00005427 for (auto &Spec : Specs)
5428 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00005429}
5430
Richard Smithd951a1d2012-02-18 02:02:13 +00005431namespace {
5432struct SpecialMemberDeletionInfo {
5433 Sema &S;
5434 CXXMethodDecl *MD;
5435 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005436 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005437
5438 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005439 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005440 SourceLocation Loc;
5441
5442 bool AllFieldsAreConst;
5443
5444 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005445 Sema::CXXSpecialMember CSM, bool Diagnose)
5446 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005447 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005448 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005449 AllFieldsAreConst(true) {
5450 switch (CSM) {
5451 case Sema::CXXDefaultConstructor:
5452 case Sema::CXXCopyConstructor:
5453 IsConstructor = true;
5454 break;
5455 case Sema::CXXMoveConstructor:
5456 IsConstructor = true;
5457 IsMove = true;
5458 break;
5459 case Sema::CXXCopyAssignment:
5460 IsAssignment = true;
5461 break;
5462 case Sema::CXXMoveAssignment:
5463 IsAssignment = true;
5464 IsMove = true;
5465 break;
5466 case Sema::CXXDestructor:
5467 break;
5468 case Sema::CXXInvalid:
5469 llvm_unreachable("invalid special member kind");
5470 }
5471
5472 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005473 if (const ReferenceType *RT =
5474 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5475 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005476 }
5477 }
5478
5479 bool inUnion() const { return MD->getParent()->isUnion(); }
5480
5481 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005482 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005483 unsigned Quals, bool IsMutable) {
5484 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5485 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005486 }
5487
Richard Smith852265f2012-03-30 20:53:28 +00005488 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005489
Richard Smith852265f2012-03-30 20:53:28 +00005490 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005491 bool shouldDeleteForField(FieldDecl *FD);
5492 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005493
Richard Smithaf136f82012-07-18 03:51:16 +00005494 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5495 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005496 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5497 Sema::SpecialMemberOverloadResult *SMOR,
5498 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005499
5500 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005501};
5502}
5503
John McCalld4274212012-04-09 20:53:23 +00005504/// Is the given special member inaccessible when used on the given
5505/// sub-object.
5506bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5507 CXXMethodDecl *target) {
5508 /// If we're operating on a base class, the object type is the
5509 /// type of this special member.
5510 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005511 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005512 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5513 objectTy = S.Context.getTypeDeclType(MD->getParent());
5514 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5515
5516 // If we're operating on a field, the object type is the type of the field.
5517 } else {
5518 objectTy = S.Context.getTypeDeclType(target->getParent());
5519 }
5520
5521 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5522}
5523
Richard Smith852265f2012-03-30 20:53:28 +00005524/// Check whether we should delete a special member due to the implicit
5525/// definition containing a call to a special member of a subobject.
5526bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5527 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5528 bool IsDtorCallInCtor) {
5529 CXXMethodDecl *Decl = SMOR->getMethod();
5530 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5531
5532 int DiagKind = -1;
5533
5534 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5535 DiagKind = !Decl ? 0 : 1;
5536 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5537 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005538 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005539 DiagKind = 3;
5540 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5541 !Decl->isTrivial()) {
5542 // A member of a union must have a trivial corresponding special member.
5543 // As a weird special case, a destructor call from a union's constructor
5544 // must be accessible and non-deleted, but need not be trivial. Such a
5545 // destructor is never actually called, but is semantically checked as
5546 // if it were.
5547 DiagKind = 4;
5548 }
5549
5550 if (DiagKind == -1)
5551 return false;
5552
5553 if (Diagnose) {
5554 if (Field) {
5555 S.Diag(Field->getLocation(),
5556 diag::note_deleted_special_member_class_subobject)
5557 << CSM << MD->getParent() << /*IsField*/true
5558 << Field << DiagKind << IsDtorCallInCtor;
5559 } else {
5560 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5561 S.Diag(Base->getLocStart(),
5562 diag::note_deleted_special_member_class_subobject)
5563 << CSM << MD->getParent() << /*IsField*/false
5564 << Base->getType() << DiagKind << IsDtorCallInCtor;
5565 }
5566
5567 if (DiagKind == 1)
5568 S.NoteDeletedFunction(Decl);
5569 // FIXME: Explain inaccessibility if DiagKind == 3.
5570 }
5571
5572 return true;
5573}
5574
Richard Smith921bd202012-02-26 09:11:52 +00005575/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005576/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005577bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005578 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005579 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005580 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005581
5582 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005583 // -- any direct or virtual base class, or non-static data member with no
5584 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005585 // either M has no default constructor or overload resolution as applied
5586 // to M's default constructor results in an ambiguity or in a function
5587 // that is deleted or inaccessible
5588 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5589 // -- a direct or virtual base class B that cannot be copied/moved because
5590 // overload resolution, as applied to B's corresponding special member,
5591 // results in an ambiguity or a function that is deleted or inaccessible
5592 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005593 // C++11 [class.dtor]p5:
5594 // -- any direct or virtual base class [...] has a type with a destructor
5595 // that is deleted or inaccessible
5596 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005597 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005598 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5599 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005600 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005601
Richard Smith852265f2012-03-30 20:53:28 +00005602 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5603 // -- any direct or virtual base class or non-static data member has a
5604 // type with a destructor that is deleted or inaccessible
5605 if (IsConstructor) {
5606 Sema::SpecialMemberOverloadResult *SMOR =
5607 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5608 false, false, false, false, false);
5609 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5610 return true;
5611 }
5612
Richard Smith921bd202012-02-26 09:11:52 +00005613 return false;
5614}
5615
5616/// Check whether we should delete a special member function due to the class
5617/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005618bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005619 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005620 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005621}
5622
5623/// Check whether we should delete a special member function due to the class
5624/// having a particular non-static data member.
5625bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5626 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5627 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5628
5629 if (CSM == Sema::CXXDefaultConstructor) {
5630 // For a default constructor, all references must be initialized in-class
5631 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005632 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5633 if (Diagnose)
5634 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5635 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005636 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005637 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005638 // C++11 [class.ctor]p5: any non-variant non-static data member of
5639 // const-qualified type (or array thereof) with no
5640 // brace-or-equal-initializer does not have a user-provided default
5641 // constructor.
5642 if (!inUnion() && FieldType.isConstQualified() &&
5643 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005644 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5645 if (Diagnose)
5646 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005647 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005648 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005649 }
5650
5651 if (inUnion() && !FieldType.isConstQualified())
5652 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005653 } else if (CSM == Sema::CXXCopyConstructor) {
5654 // For a copy constructor, data members must not be of rvalue reference
5655 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005656 if (FieldType->isRValueReferenceType()) {
5657 if (Diagnose)
5658 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5659 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005660 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005661 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005662 } else if (IsAssignment) {
5663 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005664 if (FieldType->isReferenceType()) {
5665 if (Diagnose)
5666 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5667 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005668 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005669 }
5670 if (!FieldRecord && FieldType.isConstQualified()) {
5671 // C++11 [class.copy]p23:
5672 // -- a non-static data member of const non-class type (or array thereof)
5673 if (Diagnose)
5674 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005675 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005676 return true;
5677 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005678 }
5679
5680 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005681 // Some additional restrictions exist on the variant members.
5682 if (!inUnion() && FieldRecord->isUnion() &&
5683 FieldRecord->isAnonymousStructOrUnion()) {
5684 bool AllVariantFieldsAreConst = true;
5685
Richard Smith5704fe82012-03-29 19:00:10 +00005686 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005687 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005688 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005689
5690 if (!UnionFieldType.isConstQualified())
5691 AllVariantFieldsAreConst = false;
5692
Richard Smith921bd202012-02-26 09:11:52 +00005693 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5694 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005695 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005696 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005697 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005698 }
5699
5700 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005701 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005702 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005703 if (Diagnose)
5704 S.Diag(FieldRecord->getLocation(),
5705 diag::note_deleted_default_ctor_all_const)
5706 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005707 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005708 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005709
Richard Smith5704fe82012-03-29 19:00:10 +00005710 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005711 // This is technically non-conformant, but sanity demands it.
5712 return false;
5713 }
5714
Richard Smithaf136f82012-07-18 03:51:16 +00005715 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5716 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005717 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005718 }
5719
5720 return false;
5721}
5722
5723/// C++11 [class.ctor] p5:
5724/// A defaulted default constructor for a class X is defined as deleted if
5725/// X is a union and all of its variant members are of const-qualified type.
5726bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005727 // This is a silly definition, because it gives an empty union a deleted
5728 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005729 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005730 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005731 if (Diagnose)
5732 S.Diag(MD->getParent()->getLocation(),
5733 diag::note_deleted_default_ctor_all_const)
5734 << MD->getParent() << /*not anonymous union*/0;
5735 return true;
5736 }
5737 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005738}
5739
5740/// Determine whether a defaulted special member function should be defined as
5741/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5742/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005743bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5744 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005745 if (MD->isInvalidDecl())
5746 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005747 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005748 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005749 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005750 return false;
5751
Richard Smithd951a1d2012-02-18 02:02:13 +00005752 // C++11 [expr.lambda.prim]p19:
5753 // The closure type associated with a lambda-expression has a
5754 // deleted (8.4.3) default constructor and a deleted copy
5755 // assignment operator.
5756 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005757 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5758 if (Diagnose)
5759 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005760 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005761 }
5762
Richard Smith6f1e2c62012-04-02 20:59:25 +00005763 // For an anonymous struct or union, the copy and assignment special members
5764 // will never be used, so skip the check. For an anonymous union declared at
5765 // namespace scope, the constructor and destructor are used.
5766 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5767 RD->isAnonymousStructOrUnion())
5768 return false;
5769
Richard Smith852265f2012-03-30 20:53:28 +00005770 // C++11 [class.copy]p7, p18:
5771 // If the class definition declares a move constructor or move assignment
5772 // operator, an implicitly declared copy constructor or copy assignment
5773 // operator is defined as deleted.
5774 if (MD->isImplicit() &&
5775 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005776 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005777
5778 // In Microsoft mode, a user-declared move only causes the deletion of the
5779 // corresponding copy operation, not both copy operations.
5780 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005781 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005782 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005783
5784 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005785 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005786 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005787 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005788 break;
5789 }
5790 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005791 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005792 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005793 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005794 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005795
5796 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005797 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005798 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005799 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005800 break;
5801 }
5802 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005803 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005804 }
5805
5806 if (UserDeclaredMove) {
5807 Diag(UserDeclaredMove->getLocation(),
5808 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005809 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005810 << UserDeclaredMove->isMoveAssignmentOperator();
5811 return true;
5812 }
5813 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005814
Richard Smith6f1e2c62012-04-02 20:59:25 +00005815 // Do access control from the special member function
5816 ContextRAII MethodContext(*this, MD);
5817
Richard Smith921bd202012-02-26 09:11:52 +00005818 // C++11 [class.dtor]p5:
5819 // -- for a virtual destructor, lookup of the non-array deallocation function
5820 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005821 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005822 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005823 DeclarationName Name =
5824 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5825 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005826 OperatorDelete, false)) {
5827 if (Diagnose)
5828 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005829 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005830 }
Richard Smith921bd202012-02-26 09:11:52 +00005831 }
5832
Richard Smith852265f2012-03-30 20:53:28 +00005833 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005834
Aaron Ballman574705e2014-03-13 15:41:46 +00005835 for (auto &BI : RD->bases())
5836 if (!BI.isVirtual() &&
5837 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005838 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005839
Richard Smithd1627032013-07-22 18:06:23 +00005840 // Per DR1611, do not consider virtual bases of constructors of abstract
5841 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005842 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005843 for (auto &BI : RD->vbases())
5844 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005845 return true;
5846 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005847
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005848 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005849 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005850 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005851 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005852
Richard Smithd951a1d2012-02-18 02:02:13 +00005853 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005854 return true;
5855
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005856 if (getLangOpts().CUDA) {
5857 // We should delete the special member in CUDA mode if target inference
5858 // failed.
5859 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5860 Diagnose);
5861 }
5862
Alexis Huntea6f0322011-05-11 22:34:38 +00005863 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005864}
5865
Richard Smith92f241f2012-12-08 02:53:02 +00005866/// Perform lookup for a special member of the specified kind, and determine
5867/// whether it is trivial. If the triviality can be determined without the
5868/// lookup, skip it. This is intended for use when determining whether a
5869/// special member of a containing object is trivial, and thus does not ever
5870/// perform overload resolution for default constructors.
5871///
5872/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5873/// member that was most likely to be intended to be trivial, if any.
5874static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5875 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005876 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005877 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005878 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005879
5880 switch (CSM) {
5881 case Sema::CXXInvalid:
5882 llvm_unreachable("not a special member");
5883
5884 case Sema::CXXDefaultConstructor:
5885 // C++11 [class.ctor]p5:
5886 // A default constructor is trivial if:
5887 // - all the [direct subobjects] have trivial default constructors
5888 //
5889 // Note, no overload resolution is performed in this case.
5890 if (RD->hasTrivialDefaultConstructor())
5891 return true;
5892
5893 if (Selected) {
5894 // If there's a default constructor which could have been trivial, dig it
5895 // out. Otherwise, if there's any user-provided default constructor, point
5896 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005897 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005898 if (RD->needsImplicitDefaultConstructor())
5899 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005900 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005901 if (!CI->isDefaultConstructor())
5902 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005903 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005904 if (!DefCtor->isUserProvided())
5905 break;
5906 }
5907
5908 *Selected = DefCtor;
5909 }
5910
5911 return false;
5912
5913 case Sema::CXXDestructor:
5914 // C++11 [class.dtor]p5:
5915 // A destructor is trivial if:
5916 // - all the direct [subobjects] have trivial destructors
5917 if (RD->hasTrivialDestructor())
5918 return true;
5919
5920 if (Selected) {
5921 if (RD->needsImplicitDestructor())
5922 S.DeclareImplicitDestructor(RD);
5923 *Selected = RD->getDestructor();
5924 }
5925
5926 return false;
5927
5928 case Sema::CXXCopyConstructor:
5929 // C++11 [class.copy]p12:
5930 // A copy constructor is trivial if:
5931 // - the constructor selected to copy each direct [subobject] is trivial
5932 if (RD->hasTrivialCopyConstructor()) {
5933 if (Quals == Qualifiers::Const)
5934 // We must either select the trivial copy constructor or reach an
5935 // ambiguity; no need to actually perform overload resolution.
5936 return true;
5937 } else if (!Selected) {
5938 return false;
5939 }
5940 // In C++98, we are not supposed to perform overload resolution here, but we
5941 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5942 // cases like B as having a non-trivial copy constructor:
5943 // struct A { template<typename T> A(T&); };
5944 // struct B { mutable A a; };
5945 goto NeedOverloadResolution;
5946
5947 case Sema::CXXCopyAssignment:
5948 // C++11 [class.copy]p25:
5949 // A copy assignment operator is trivial if:
5950 // - the assignment operator selected to copy each direct [subobject] is
5951 // trivial
5952 if (RD->hasTrivialCopyAssignment()) {
5953 if (Quals == Qualifiers::Const)
5954 return true;
5955 } else if (!Selected) {
5956 return false;
5957 }
5958 // In C++98, we are not supposed to perform overload resolution here, but we
5959 // treat that as a language defect.
5960 goto NeedOverloadResolution;
5961
5962 case Sema::CXXMoveConstructor:
5963 case Sema::CXXMoveAssignment:
5964 NeedOverloadResolution:
5965 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005966 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005967
5968 // The standard doesn't describe how to behave if the lookup is ambiguous.
5969 // We treat it as not making the member non-trivial, just like the standard
5970 // mandates for the default constructor. This should rarely matter, because
5971 // the member will also be deleted.
5972 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5973 return true;
5974
5975 if (!SMOR->getMethod()) {
5976 assert(SMOR->getKind() ==
5977 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5978 return false;
5979 }
5980
5981 // We deliberately don't check if we found a deleted special member. We're
5982 // not supposed to!
5983 if (Selected)
5984 *Selected = SMOR->getMethod();
5985 return SMOR->getMethod()->isTrivial();
5986 }
5987
5988 llvm_unreachable("unknown special method kind");
5989}
5990
Benjamin Kramer3e350262013-02-15 12:30:38 +00005991static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005992 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005993 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005994 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005995
5996 // Look for constructor templates.
5997 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5998 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5999 if (CXXConstructorDecl *CD =
6000 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6001 return CD;
6002 }
6003
Craig Topperc3ec1492014-05-26 06:22:03 +00006004 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006005}
6006
6007/// The kind of subobject we are checking for triviality. The values of this
6008/// enumeration are used in diagnostics.
6009enum TrivialSubobjectKind {
6010 /// The subobject is a base class.
6011 TSK_BaseClass,
6012 /// The subobject is a non-static data member.
6013 TSK_Field,
6014 /// The object is actually the complete object.
6015 TSK_CompleteObject
6016};
6017
6018/// Check whether the special member selected for a given type would be trivial.
6019static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00006020 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00006021 Sema::CXXSpecialMember CSM,
6022 TrivialSubobjectKind Kind,
6023 bool Diagnose) {
6024 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6025 if (!SubRD)
6026 return true;
6027
6028 CXXMethodDecl *Selected;
6029 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006030 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00006031 return true;
6032
6033 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00006034 if (ConstRHS)
6035 SubType.addConst();
6036
Richard Smith92f241f2012-12-08 02:53:02 +00006037 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6038 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6039 << Kind << SubType.getUnqualifiedType();
6040 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6041 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6042 } else if (!Selected)
6043 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6044 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6045 else if (Selected->isUserProvided()) {
6046 if (Kind == TSK_CompleteObject)
6047 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6048 << Kind << SubType.getUnqualifiedType() << CSM;
6049 else {
6050 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6051 << Kind << SubType.getUnqualifiedType() << CSM;
6052 S.Diag(Selected->getLocation(), diag::note_declared_at);
6053 }
6054 } else {
6055 if (Kind != TSK_CompleteObject)
6056 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6057 << Kind << SubType.getUnqualifiedType() << CSM;
6058
6059 // Explain why the defaulted or deleted special member isn't trivial.
6060 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6061 }
6062 }
6063
6064 return false;
6065}
6066
6067/// Check whether the members of a class type allow a special member to be
6068/// trivial.
6069static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6070 Sema::CXXSpecialMember CSM,
6071 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006072 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006073 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6074 continue;
6075
6076 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6077
6078 // Pretend anonymous struct or union members are members of this class.
6079 if (FI->isAnonymousStructOrUnion()) {
6080 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6081 CSM, ConstArg, Diagnose))
6082 return false;
6083 continue;
6084 }
6085
6086 // C++11 [class.ctor]p5:
6087 // A default constructor is trivial if [...]
6088 // -- no non-static data member of its class has a
6089 // brace-or-equal-initializer
6090 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6091 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006092 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00006093 return false;
6094 }
6095
6096 // Objective C ARC 4.3.5:
6097 // [...] nontrivally ownership-qualified types are [...] not trivially
6098 // default constructible, copy constructible, move constructible, copy
6099 // assignable, move assignable, or destructible [...]
6100 if (S.getLangOpts().ObjCAutoRefCount &&
6101 FieldType.hasNonTrivialObjCLifetime()) {
6102 if (Diagnose)
6103 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6104 << RD << FieldType.getObjCLifetime();
6105 return false;
6106 }
6107
Richard Smith41c35d62013-11-27 03:39:20 +00006108 bool ConstRHS = ConstArg && !FI->isMutable();
6109 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6110 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006111 return false;
6112 }
6113
6114 return true;
6115}
6116
6117/// Diagnose why the specified class does not have a trivial special member of
6118/// the given kind.
6119void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6120 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00006121
Richard Smith41c35d62013-11-27 03:39:20 +00006122 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6123 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00006124 TSK_CompleteObject, /*Diagnose*/true);
6125}
6126
6127/// Determine whether a defaulted or deleted special member function is trivial,
6128/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6129/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6130bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6131 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00006132 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6133
6134 CXXRecordDecl *RD = MD->getParent();
6135
6136 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006137
Richard Smith2002bfe2013-11-04 02:02:27 +00006138 // C++11 [class.copy]p12, p25: [DR1593]
6139 // A [special member] is trivial if [...] its parameter-type-list is
6140 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00006141 switch (CSM) {
6142 case CXXDefaultConstructor:
6143 case CXXDestructor:
6144 // Trivial default constructors and destructors cannot have parameters.
6145 break;
6146
6147 case CXXCopyConstructor:
6148 case CXXCopyAssignment: {
6149 // Trivial copy operations always have const, non-volatile parameter types.
6150 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00006151 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006152 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6153 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6154 if (Diagnose)
6155 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6156 << Param0->getSourceRange() << Param0->getType()
6157 << Context.getLValueReferenceType(
6158 Context.getRecordType(RD).withConst());
6159 return false;
6160 }
6161 break;
6162 }
6163
6164 case CXXMoveConstructor:
6165 case CXXMoveAssignment: {
6166 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00006167 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006168 const RValueReferenceType *RT =
6169 Param0->getType()->getAs<RValueReferenceType>();
6170 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6171 if (Diagnose)
6172 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6173 << Param0->getSourceRange() << Param0->getType()
6174 << Context.getRValueReferenceType(Context.getRecordType(RD));
6175 return false;
6176 }
6177 break;
6178 }
6179
6180 case CXXInvalid:
6181 llvm_unreachable("not a special member");
6182 }
6183
Richard Smith92f241f2012-12-08 02:53:02 +00006184 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6185 if (Diagnose)
6186 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6187 diag::note_nontrivial_default_arg)
6188 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6189 return false;
6190 }
6191 if (MD->isVariadic()) {
6192 if (Diagnose)
6193 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6194 return false;
6195 }
6196
6197 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6198 // A copy/move [constructor or assignment operator] is trivial if
6199 // -- the [member] selected to copy/move each direct base class subobject
6200 // is trivial
6201 //
6202 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6203 // A [default constructor or destructor] is trivial if
6204 // -- all the direct base classes have trivial [default constructors or
6205 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00006206 for (const auto &BI : RD->bases())
6207 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00006208 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006209 return false;
6210
6211 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6212 // A copy/move [constructor or assignment operator] for a class X is
6213 // trivial if
6214 // -- for each non-static data member of X that is of class type (or array
6215 // thereof), the constructor selected to copy/move that member is
6216 // trivial
6217 //
6218 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6219 // A [default constructor or destructor] is trivial if
6220 // -- for all of the non-static data members of its class that are of class
6221 // type (or array thereof), each such class has a trivial [default
6222 // constructor or destructor]
6223 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6224 return false;
6225
6226 // C++11 [class.dtor]p5:
6227 // A destructor is trivial if [...]
6228 // -- the destructor is not virtual
6229 if (CSM == CXXDestructor && MD->isVirtual()) {
6230 if (Diagnose)
6231 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6232 return false;
6233 }
6234
6235 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6236 // A [special member] for class X is trivial if [...]
6237 // -- class X has no virtual functions and no virtual base classes
6238 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6239 if (!Diagnose)
6240 return false;
6241
6242 if (RD->getNumVBases()) {
6243 // Check for virtual bases. We already know that the corresponding
6244 // member in all bases is trivial, so vbases must all be direct.
6245 CXXBaseSpecifier &BS = *RD->vbases_begin();
6246 assert(BS.isVirtual());
6247 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6248 return false;
6249 }
6250
6251 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006252 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006253 if (MI->isVirtual()) {
6254 SourceLocation MLoc = MI->getLocStart();
6255 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6256 return false;
6257 }
6258 }
6259
6260 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6261 }
6262
6263 // Looks like it's trivial!
6264 return true;
6265}
6266
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006267/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00006268namespace {
6269 struct FindHiddenVirtualMethodData {
6270 Sema *S;
6271 CXXMethodDecl *Method;
6272 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006273 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00006274 };
6275}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006276
David Blaikie282c92a2012-10-19 00:53:08 +00006277/// \brief Check whether any most overriden method from MD in Methods
6278static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006279 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006280 if (MD->size_overridden_methods() == 0)
6281 return Methods.count(MD->getCanonicalDecl());
6282 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6283 E = MD->end_overridden_methods();
6284 I != E; ++I)
6285 if (CheckMostOverridenMethods(*I, Methods))
6286 return true;
6287 return false;
6288}
6289
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006290/// \brief Member lookup function that determines whether a given C++
6291/// method overloads virtual methods in a base class without overriding any,
6292/// to be used with CXXRecordDecl::lookupInBases().
6293static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6294 CXXBasePath &Path,
6295 void *UserData) {
6296 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6297
6298 FindHiddenVirtualMethodData &Data
6299 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6300
6301 DeclarationName Name = Data.Method->getDeclName();
6302 assert(Name.getNameKind() == DeclarationName::Identifier);
6303
6304 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006305 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006306 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006307 !Path.Decls.empty();
6308 Path.Decls = Path.Decls.slice(1)) {
6309 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006310 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00006311 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006312 foundSameNameMethod = true;
6313 // Interested only in hidden virtual methods.
6314 if (!MD->isVirtual())
6315 continue;
6316 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00006317 // don't warn about the other overloaded methods. Clang deviates from GCC
6318 // by only diagnosing overloads of inherited virtual functions that do not
6319 // override any other virtual functions in the base. GCC's
6320 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6321 // function from a base class. These cases may be better served by a
6322 // warning (not specific to virtual functions) on call sites when the call
6323 // would select a different function from the base class, were it visible.
6324 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006325 if (!Data.S->IsOverload(Data.Method, MD, false))
6326 return true;
6327 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00006328 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006329 overloadedMethods.push_back(MD);
6330 }
6331 }
6332
6333 if (foundSameNameMethod)
6334 Data.OverloadedMethods.append(overloadedMethods.begin(),
6335 overloadedMethods.end());
6336 return foundSameNameMethod;
6337}
6338
David Blaikie282c92a2012-10-19 00:53:08 +00006339/// \brief Add the most overriden methods from MD to Methods
6340static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006341 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006342 if (MD->size_overridden_methods() == 0)
6343 Methods.insert(MD->getCanonicalDecl());
6344 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6345 E = MD->end_overridden_methods();
6346 I != E; ++I)
6347 AddMostOverridenMethods(*I, Methods);
6348}
6349
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006350/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006351/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006352void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6353 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006354 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006355 return;
6356
6357 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6358 /*bool RecordPaths=*/false,
6359 /*bool DetectVirtual=*/false);
6360 FindHiddenVirtualMethodData Data;
6361 Data.Method = MD;
6362 Data.S = this;
6363
6364 // Keep the base methods that were overriden or introduced in the subclass
6365 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006366 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006367 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6368 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6369 NamedDecl *ND = *I;
6370 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006371 ND = shad->getTargetDecl();
6372 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6373 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006374 }
6375
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006376 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6377 OverloadedMethods = Data.OverloadedMethods;
6378}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006379
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006380void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6381 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6382 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6383 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6384 PartialDiagnostic PD = PDiag(
6385 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6386 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6387 Diag(overloadedMD->getLocation(), PD);
6388 }
6389}
6390
6391/// \brief Diagnose methods which overload virtual methods in a base class
6392/// without overriding any.
6393void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6394 if (MD->isInvalidDecl())
6395 return;
6396
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006397 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006398 return;
6399
6400 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6401 FindHiddenVirtualMethods(MD, OverloadedMethods);
6402 if (!OverloadedMethods.empty()) {
6403 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6404 << MD << (OverloadedMethods.size() > 1);
6405
6406 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006407 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006408}
6409
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006410void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006411 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006412 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006413 SourceLocation RBrac,
6414 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006415 if (!TagDecl)
6416 return;
Mike Stump11289f42009-09-09 15:08:12 +00006417
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006418 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006419
Rafael Espindola06e1b132012-07-12 04:32:30 +00006420 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6421 if (l->getKind() != AttributeList::AT_Visibility)
6422 continue;
6423 l->setInvalid();
6424 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6425 l->getName();
6426 }
6427
David Blaikie751c5582011-09-22 02:58:26 +00006428 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006429 // strict aliasing violation!
6430 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006431 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006432
Douglas Gregor0be31a22010-07-02 17:43:08 +00006433 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006434 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006435}
6436
Douglas Gregor05379422008-11-03 17:51:48 +00006437/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6438/// special functions, such as the default constructor, copy
6439/// constructor, or destructor, to the given C++ class (C++
6440/// [special]p1). This routine can only be executed just before the
6441/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006442void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006443 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006444 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006445
Richard Smith6b02d462012-12-08 08:32:28 +00006446 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006447 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006448
Richard Smith6b02d462012-12-08 08:32:28 +00006449 // If the properties or semantics of the copy constructor couldn't be
6450 // determined while the class was being declared, force a declaration
6451 // of it now.
6452 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6453 DeclareImplicitCopyConstructor(ClassDecl);
6454 }
6455
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006456 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006457 ++ASTContext::NumImplicitMoveConstructors;
6458
Richard Smith6b02d462012-12-08 08:32:28 +00006459 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6460 DeclareImplicitMoveConstructor(ClassDecl);
6461 }
6462
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006463 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6464 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006465
6466 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006467 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006468 // it shows up in the right place in the vtable and that we diagnose
6469 // problems with the implicit exception specification.
6470 if (ClassDecl->isDynamicClass() ||
6471 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006472 DeclareImplicitCopyAssignment(ClassDecl);
6473 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006474
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006475 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006476 ++ASTContext::NumImplicitMoveAssignmentOperators;
6477
6478 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006479 if (ClassDecl->isDynamicClass() ||
6480 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006481 DeclareImplicitMoveAssignment(ClassDecl);
6482 }
6483
Douglas Gregor7454c562010-07-02 20:37:36 +00006484 if (!ClassDecl->hasUserDeclaredDestructor()) {
6485 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006486
6487 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006488 // have to declare the destructor immediately. This ensures that, e.g., it
6489 // shows up in the right place in the vtable and that we diagnose problems
6490 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006491 if (ClassDecl->isDynamicClass() ||
6492 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006493 DeclareImplicitDestructor(ClassDecl);
6494 }
Douglas Gregor05379422008-11-03 17:51:48 +00006495}
6496
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006497unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006498 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006499 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006500
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006501 // The order of template parameters is not important here. All names
6502 // get added to the same scope.
6503 SmallVector<TemplateParameterList *, 4> ParameterLists;
6504
6505 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6506 D = TD->getTemplatedDecl();
6507
6508 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6509 ParameterLists.push_back(PSD->getTemplateParameters());
6510
6511 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6512 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6513 ParameterLists.push_back(DD->getTemplateParameterList(i));
6514
6515 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6516 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6517 ParameterLists.push_back(FTD->getTemplateParameters());
6518 }
6519 }
6520
6521 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6522 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6523 ParameterLists.push_back(TD->getTemplateParameterList(i));
6524
6525 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6526 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6527 ParameterLists.push_back(CTD->getTemplateParameters());
6528 }
6529 }
6530
6531 unsigned Count = 0;
6532 for (TemplateParameterList *Params : ParameterLists) {
6533 if (Params->size() > 0)
6534 // Ignore explicit specializations; they don't contribute to the template
6535 // depth.
6536 ++Count;
6537 for (NamedDecl *Param : *Params) {
6538 if (Param->getDeclName()) {
6539 S->AddDecl(Param);
6540 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006541 }
6542 }
6543 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006544
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006545 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006546}
6547
John McCall48871652010-08-21 09:40:31 +00006548void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006549 if (!RecordD) return;
6550 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006551 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006552 PushDeclContext(S, Record);
6553}
6554
John McCall48871652010-08-21 09:40:31 +00006555void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006556 if (!RecordD) return;
6557 PopDeclContext();
6558}
6559
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006560/// This is used to implement the constant expression evaluation part of the
6561/// attribute enable_if extension. There is nothing in standard C++ which would
6562/// require reentering parameters.
6563void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6564 if (!Param)
6565 return;
6566
6567 S->AddDecl(Param);
6568 if (Param->getDeclName())
6569 IdResolver.AddDecl(Param);
6570}
6571
Douglas Gregor4d87df52008-12-16 21:30:33 +00006572/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6573/// parsing a top-level (non-nested) C++ class, and we are now
6574/// parsing those parts of the given Method declaration that could
6575/// not be parsed earlier (C++ [class.mem]p2), such as default
6576/// arguments. This action should enter the scope of the given
6577/// Method declaration as if we had just parsed the qualified method
6578/// name. However, it should not bring the parameters into scope;
6579/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006580void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006581}
6582
6583/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6584/// C++ method declaration. We're (re-)introducing the given
6585/// function parameter into scope for use in parsing later parts of
6586/// the method declaration. For example, we could see an
6587/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006588void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006589 if (!ParamD)
6590 return;
Mike Stump11289f42009-09-09 15:08:12 +00006591
John McCall48871652010-08-21 09:40:31 +00006592 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006593
6594 // If this parameter has an unparsed default argument, clear it out
6595 // to make way for the parsed default argument.
6596 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006597 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006598
John McCall48871652010-08-21 09:40:31 +00006599 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006600 if (Param->getDeclName())
6601 IdResolver.AddDecl(Param);
6602}
6603
6604/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6605/// processing the delayed method declaration for Method. The method
6606/// declaration is now considered finished. There may be a separate
6607/// ActOnStartOfFunctionDef action later (not necessarily
6608/// immediately!) for this method, if it was also defined inside the
6609/// class body.
John McCall48871652010-08-21 09:40:31 +00006610void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006611 if (!MethodD)
6612 return;
Mike Stump11289f42009-09-09 15:08:12 +00006613
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006614 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006615
John McCall48871652010-08-21 09:40:31 +00006616 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006617
6618 // Now that we have our default arguments, check the constructor
6619 // again. It could produce additional diagnostics or affect whether
6620 // the class has implicitly-declared destructors, among other
6621 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006622 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6623 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006624
6625 // Check the default arguments, which we may have added.
6626 if (!Method->isInvalidDecl())
6627 CheckCXXDefaultArguments(Method);
6628}
6629
Douglas Gregor831c93f2008-11-05 20:51:48 +00006630/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006631/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006632/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006633/// emit diagnostics and set the invalid bit to true. In any case, the type
6634/// will be updated to reflect a well-formed type for the constructor and
6635/// returned.
6636QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006637 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006638 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006639
6640 // C++ [class.ctor]p3:
6641 // A constructor shall not be virtual (10.3) or static (9.4). A
6642 // constructor can be invoked for a const, volatile or const
6643 // volatile object. A constructor shall not be declared const,
6644 // volatile, or const volatile (9.3.2).
6645 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006646 if (!D.isInvalidType())
6647 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6648 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6649 << SourceRange(D.getIdentifierLoc());
6650 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006651 }
John McCall8e7d6562010-08-26 03:08:43 +00006652 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006653 if (!D.isInvalidType())
6654 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6655 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6656 << SourceRange(D.getIdentifierLoc());
6657 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006658 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006659 }
Mike Stump11289f42009-09-09 15:08:12 +00006660
David Majnemer03f705f2014-07-08 18:18:04 +00006661 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6662 diagnoseIgnoredQualifiers(
6663 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6664 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6665 D.getDeclSpec().getRestrictSpecLoc(),
6666 D.getDeclSpec().getAtomicSpecLoc());
6667 D.setInvalidType();
6668 }
6669
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006670 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006671 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006672 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006673 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6674 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006675 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006676 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6677 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006678 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006679 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6680 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006681 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006682 }
Mike Stump11289f42009-09-09 15:08:12 +00006683
Douglas Gregordb9d6642011-01-26 05:01:58 +00006684 // C++0x [class.ctor]p4:
6685 // A constructor shall not be declared with a ref-qualifier.
6686 if (FTI.hasRefQualifier()) {
6687 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6688 << FTI.RefQualifierIsLValueRef
6689 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6690 D.setInvalidType();
6691 }
6692
Douglas Gregor831c93f2008-11-05 20:51:48 +00006693 // Rebuild the function type "R" without any type qualifiers (in
6694 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006695 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006696 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006697 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006698 return R;
6699
6700 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6701 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006702 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006703
6704 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006705}
6706
Douglas Gregor4d87df52008-12-16 21:30:33 +00006707/// CheckConstructor - Checks a fully-formed constructor for
6708/// well-formedness, issuing any diagnostics required. Returns true if
6709/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006710void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006711 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006712 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6713 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006714 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006715
6716 // C++ [class.copy]p3:
6717 // A declaration of a constructor for a class X is ill-formed if
6718 // its first parameter is of type (optionally cv-qualified) X and
6719 // either there are no other parameters or else all other
6720 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006721 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006722 ((Constructor->getNumParams() == 1) ||
6723 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006724 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6725 Constructor->getTemplateSpecializationKind()
6726 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006727 QualType ParamType = Constructor->getParamDecl(0)->getType();
6728 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6729 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006730 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006731 const char *ConstRef
6732 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6733 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006734 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006735 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006736
6737 // FIXME: Rather that making the constructor invalid, we should endeavor
6738 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006739 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006740 }
6741 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006742}
6743
John McCalldeb646e2010-08-04 01:04:25 +00006744/// CheckDestructor - Checks a fully-formed destructor definition for
6745/// well-formedness, issuing any diagnostics required. Returns true
6746/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006747bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006748 CXXRecordDecl *RD = Destructor->getParent();
6749
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006750 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006751 SourceLocation Loc;
6752
6753 if (!Destructor->isImplicit())
6754 Loc = Destructor->getLocation();
6755 else
6756 Loc = RD->getLocation();
6757
6758 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006759 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006760 DeclarationName Name =
6761 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006762 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006763 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006764 // If there's no class-specific operator delete, look up the global
6765 // non-array delete.
6766 if (!OperatorDelete)
6767 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006768
Eli Friedmanfa0df832012-02-02 03:46:19 +00006769 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006770
6771 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006772 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006773
6774 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006775}
6776
Douglas Gregor831c93f2008-11-05 20:51:48 +00006777/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6778/// the well-formednes of the destructor declarator @p D with type @p
6779/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006780/// emit diagnostics and set the declarator to invalid. Even if this happens,
6781/// will be updated to reflect a well-formed type for the destructor and
6782/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006783QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006784 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006785 // C++ [class.dtor]p1:
6786 // [...] A typedef-name that names a class is a class-name
6787 // (7.1.3); however, a typedef-name that names a class shall not
6788 // be used as the identifier in the declarator for a destructor
6789 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006790 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006791 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006792 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006793 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006794 else if (const TemplateSpecializationType *TST =
6795 DeclaratorType->getAs<TemplateSpecializationType>())
6796 if (TST->isTypeAlias())
6797 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6798 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006799
6800 // C++ [class.dtor]p2:
6801 // A destructor is used to destroy objects of its class type. A
6802 // destructor takes no parameters, and no return type can be
6803 // specified for it (not even void). The address of a destructor
6804 // shall not be taken. A destructor shall not be static. A
6805 // destructor can be invoked for a const, volatile or const
6806 // volatile object. A destructor shall not be declared const,
6807 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006808 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006809 if (!D.isInvalidType())
6810 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6811 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006812 << SourceRange(D.getIdentifierLoc())
6813 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6814
John McCall8e7d6562010-08-26 03:08:43 +00006815 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006816 }
David Majnemer03f705f2014-07-08 18:18:04 +00006817 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006818 // Destructors don't have return types, but the parser will
6819 // happily parse something like:
6820 //
6821 // class X {
6822 // float ~X();
6823 // };
6824 //
6825 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006826 if (D.getDeclSpec().hasTypeSpecifier())
6827 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6828 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6829 << SourceRange(D.getIdentifierLoc());
6830 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6831 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6832 SourceLocation(),
6833 D.getDeclSpec().getConstSpecLoc(),
6834 D.getDeclSpec().getVolatileSpecLoc(),
6835 D.getDeclSpec().getRestrictSpecLoc(),
6836 D.getDeclSpec().getAtomicSpecLoc());
6837 D.setInvalidType();
6838 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006839 }
Mike Stump11289f42009-09-09 15:08:12 +00006840
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006841 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006842 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006843 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006844 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6845 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006846 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006847 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6848 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006849 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006850 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6851 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006852 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006853 }
6854
Douglas Gregordb9d6642011-01-26 05:01:58 +00006855 // C++0x [class.dtor]p2:
6856 // A destructor shall not be declared with a ref-qualifier.
6857 if (FTI.hasRefQualifier()) {
6858 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6859 << FTI.RefQualifierIsLValueRef
6860 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6861 D.setInvalidType();
6862 }
6863
Douglas Gregor831c93f2008-11-05 20:51:48 +00006864 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006865 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006866 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6867
6868 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006869 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006870 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006871 }
6872
Mike Stump11289f42009-09-09 15:08:12 +00006873 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006874 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006875 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006876 D.setInvalidType();
6877 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006878
6879 // Rebuild the function type "R" without any type qualifiers or
6880 // parameters (in case any of the errors above fired) and with
6881 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006882 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006883 if (!D.isInvalidType())
6884 return R;
6885
Douglas Gregor95755162010-07-01 05:10:53 +00006886 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006887 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6888 EPI.Variadic = false;
6889 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006890 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006891 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006892}
6893
Richard Smitha865a162014-12-19 02:07:47 +00006894static void extendLeft(SourceRange &R, const SourceRange &Before) {
6895 if (Before.isInvalid())
6896 return;
6897 R.setBegin(Before.getBegin());
6898 if (R.getEnd().isInvalid())
6899 R.setEnd(Before.getEnd());
6900}
6901
6902static void extendRight(SourceRange &R, const SourceRange &After) {
6903 if (After.isInvalid())
6904 return;
6905 if (R.getBegin().isInvalid())
6906 R.setBegin(After.getBegin());
6907 R.setEnd(After.getEnd());
6908}
6909
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006910/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6911/// well-formednes of the conversion function declarator @p D with
6912/// type @p R. If there are any errors in the declarator, this routine
6913/// will emit diagnostics and return true. Otherwise, it will return
6914/// false. Either way, the type @p R will be updated to reflect a
6915/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006916void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006917 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006918 // C++ [class.conv.fct]p1:
6919 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006920 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006921 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006922 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006923 if (!D.isInvalidType())
6924 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006925 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6926 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006927 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006928 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006929 }
John McCall212fa2e2010-04-13 00:04:31 +00006930
Richard Smitha865a162014-12-19 02:07:47 +00006931 TypeSourceInfo *ConvTSI = nullptr;
6932 QualType ConvType =
6933 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00006934
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006935 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006936 // Conversion functions don't have return types, but the parser will
6937 // happily parse something like:
6938 //
6939 // class X {
6940 // float operator bool();
6941 // };
6942 //
6943 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006944 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6945 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6946 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006947 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006948 }
6949
John McCall212fa2e2010-04-13 00:04:31 +00006950 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6951
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006952 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006953 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006954 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6955
6956 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006957 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006958 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006959 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006960 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006961 D.setInvalidType();
6962 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006963
John McCall212fa2e2010-04-13 00:04:31 +00006964 // Diagnose "&operator bool()" and other such nonsense. This
6965 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006966 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00006967 bool NeedsTypedef = false;
6968 SourceRange Before, After;
6969
6970 // Walk the chunks and extract information on them for our diagnostic.
6971 bool PastFunctionChunk = false;
6972 for (auto &Chunk : D.type_objects()) {
6973 switch (Chunk.Kind) {
6974 case DeclaratorChunk::Function:
6975 if (!PastFunctionChunk) {
6976 if (Chunk.Fun.HasTrailingReturnType) {
6977 TypeSourceInfo *TRT = nullptr;
6978 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6979 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6980 }
6981 PastFunctionChunk = true;
6982 break;
6983 }
6984 // Fall through.
6985 case DeclaratorChunk::Array:
6986 NeedsTypedef = true;
6987 extendRight(After, Chunk.getSourceRange());
6988 break;
6989
6990 case DeclaratorChunk::Pointer:
6991 case DeclaratorChunk::BlockPointer:
6992 case DeclaratorChunk::Reference:
6993 case DeclaratorChunk::MemberPointer:
6994 extendLeft(Before, Chunk.getSourceRange());
6995 break;
6996
6997 case DeclaratorChunk::Paren:
6998 extendLeft(Before, Chunk.Loc);
6999 extendRight(After, Chunk.EndLoc);
7000 break;
7001 }
7002 }
7003
7004 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7005 After.isValid() ? After.getBegin() :
7006 D.getIdentifierLoc();
7007 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7008 DB << Before << After;
7009
7010 if (!NeedsTypedef) {
7011 DB << /*don't need a typedef*/0;
7012
7013 // If we can provide a correct fix-it hint, do so.
7014 if (After.isInvalid() && ConvTSI) {
7015 SourceLocation InsertLoc =
7016 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7017 DB << FixItHint::CreateInsertion(InsertLoc, " ")
7018 << FixItHint::CreateInsertionFromRange(
7019 InsertLoc, CharSourceRange::getTokenRange(Before))
7020 << FixItHint::CreateRemoval(Before);
7021 }
7022 } else if (!Proto->getReturnType()->isDependentType()) {
7023 DB << /*typedef*/1 << Proto->getReturnType();
7024 } else if (getLangOpts().CPlusPlus11) {
7025 DB << /*alias template*/2 << Proto->getReturnType();
7026 } else {
7027 DB << /*might not be fixable*/3;
7028 }
7029
7030 // Recover by incorporating the other type chunks into the result type.
7031 // Note, this does *not* change the name of the function. This is compatible
7032 // with the GCC extension:
7033 // struct S { &operator int(); } s;
7034 // int &r = s.operator int(); // ok in GCC
7035 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00007036 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00007037 }
7038
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007039 // C++ [class.conv.fct]p4:
7040 // The conversion-type-id shall not represent a function type nor
7041 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007042 if (ConvType->isArrayType()) {
7043 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7044 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007045 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007046 } else if (ConvType->isFunctionType()) {
7047 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7048 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007049 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007050 }
7051
7052 // Rebuild the function type "R" without any parameters (in case any
7053 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00007054 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00007055 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007056 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007057
Douglas Gregor5fb53972009-01-14 15:45:31 +00007058 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007059 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00007060 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007061 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007062 diag::warn_cxx98_compat_explicit_conversion_functions :
7063 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00007064 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007065}
7066
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007067/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7068/// the declaration of the given C++ conversion function. This routine
7069/// is responsible for recording the conversion function in the C++
7070/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00007071Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007072 assert(Conversion && "Expected to receive a conversion function declaration");
7073
Douglas Gregor4287b372008-12-12 08:25:50 +00007074 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007075
7076 // Make sure we aren't redeclaring the conversion function.
7077 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007078
7079 // C++ [class.conv.fct]p1:
7080 // [...] A conversion function is never used to convert a
7081 // (possibly cv-qualified) object to the (possibly cv-qualified)
7082 // same object type (or a reference to it), to a (possibly
7083 // cv-qualified) base class of that type (or a reference to it),
7084 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00007085 // FIXME: Suppress this warning if the conversion function ends up being a
7086 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00007087 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007088 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007089 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007090 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007091 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7092 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00007093 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007094 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007095 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7096 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007097 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007098 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007099 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007100 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007101 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007102 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007103 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007104 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007105 }
7106
Douglas Gregor457104e2010-09-29 04:25:11 +00007107 if (FunctionTemplateDecl *ConversionTemplate
7108 = Conversion->getDescribedFunctionTemplate())
7109 return ConversionTemplate;
7110
John McCall48871652010-08-21 09:40:31 +00007111 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007112}
7113
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007114//===----------------------------------------------------------------------===//
7115// Namespace Handling
7116//===----------------------------------------------------------------------===//
7117
Richard Smith45bb8852012-10-04 22:13:39 +00007118/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7119/// reopened.
7120static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7121 SourceLocation Loc,
7122 IdentifierInfo *II, bool *IsInline,
7123 NamespaceDecl *PrevNS) {
7124 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00007125
Richard Smithf501cc32012-10-05 01:46:25 +00007126 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7127 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7128 // inline namespaces, with the intention of bringing names into namespace std.
7129 //
7130 // We support this just well enough to get that case working; this is not
7131 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00007132 if (*IsInline && II && II->getName().startswith("__atomic") &&
7133 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00007134 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00007135 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7136 NS = NS->getPreviousDecl())
7137 NS->setInline(*IsInline);
7138 // Patch up the lookup table for the containing namespace. This isn't really
7139 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00007140 for (auto *I : PrevNS->decls())
7141 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00007142 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7143 return;
7144 }
7145
7146 if (PrevNS->isInline())
7147 // The user probably just forgot the 'inline', so suggest that it
7148 // be added back.
7149 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7150 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7151 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00007152 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00007153
7154 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7155 *IsInline = PrevNS->isInline();
7156}
John McCallb1be5232010-08-26 09:15:37 +00007157
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007158/// ActOnStartNamespaceDef - This is called at the start of a namespace
7159/// definition.
John McCall48871652010-08-21 09:40:31 +00007160Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00007161 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007162 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00007163 SourceLocation IdentLoc,
7164 IdentifierInfo *II,
7165 SourceLocation LBrace,
7166 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007167 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7168 // For anonymous namespace, take the location of the left brace.
7169 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00007170 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00007171 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00007172 bool IsStd = false;
7173 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007174 Scope *DeclRegionScope = NamespcScope->getParent();
7175
Craig Topperc3ec1492014-05-26 06:22:03 +00007176 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007177 if (II) {
7178 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00007179 // The identifier in an original-namespace-definition shall not
7180 // have been previously defined in the declarative region in
7181 // which the original-namespace-definition appears. The
7182 // identifier in an original-namespace-definition is the name of
7183 // the namespace. Subsequently in that declarative region, it is
7184 // treated as an original-namespace-name.
7185 //
7186 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007187 // look through using directives, just look for any ordinary names.
7188
7189 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00007190 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7191 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00007192 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00007193 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7194 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7195 ++I) {
7196 if ((*I)->getIdentifierNamespace() & IDNS) {
7197 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007198 break;
7199 }
7200 }
7201
Douglas Gregore57e7522012-01-07 09:11:48 +00007202 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7203
7204 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00007205 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00007206 if (IsInline != PrevNS->isInline())
7207 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7208 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00007209 } else if (PrevDecl) {
7210 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007211 Diag(Loc, diag::err_redefinition_different_kind)
7212 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00007213 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007214 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00007215 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00007216 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007217 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007218 // This is the first "real" definition of the namespace "std", so update
7219 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007220 PrevNS = getStdNamespace();
7221 IsStd = true;
7222 AddToKnown = !IsInline;
7223 } else {
7224 // We've seen this namespace for the first time.
7225 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00007226 }
Douglas Gregor91f84212008-12-11 16:49:14 +00007227 } else {
John McCall4fa53422009-10-01 00:25:31 +00007228 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00007229
7230 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00007231 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00007232 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00007233 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007234 } else {
7235 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00007236 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007237 }
7238
Richard Smith45bb8852012-10-04 22:13:39 +00007239 if (PrevNS && IsInline != PrevNS->isInline())
7240 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7241 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00007242 }
7243
7244 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7245 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007246 if (IsInvalid)
7247 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00007248
7249 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00007250
Douglas Gregore57e7522012-01-07 09:11:48 +00007251 // FIXME: Should we be merging attributes?
7252 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007253 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00007254
7255 if (IsStd)
7256 StdNamespace = Namespc;
7257 if (AddToKnown)
7258 KnownNamespaces[Namespc] = false;
7259
7260 if (II) {
7261 PushOnScopeChains(Namespc, DeclRegionScope);
7262 } else {
7263 // Link the anonymous namespace into its parent.
7264 DeclContext *Parent = CurContext->getRedeclContext();
7265 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7266 TU->setAnonymousNamespace(Namespc);
7267 } else {
7268 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00007269 }
John McCall4fa53422009-10-01 00:25:31 +00007270
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00007271 CurContext->addDecl(Namespc);
7272
John McCall4fa53422009-10-01 00:25:31 +00007273 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7274 // behaves as if it were replaced by
7275 // namespace unique { /* empty body */ }
7276 // using namespace unique;
7277 // namespace unique { namespace-body }
7278 // where all occurrences of 'unique' in a translation unit are
7279 // replaced by the same identifier and this identifier differs
7280 // from all other identifiers in the entire program.
7281
7282 // We just create the namespace with an empty name and then add an
7283 // implicit using declaration, just like the standard suggests.
7284 //
7285 // CodeGen enforces the "universally unique" aspect by giving all
7286 // declarations semantically contained within an anonymous
7287 // namespace internal linkage.
7288
Douglas Gregore57e7522012-01-07 09:11:48 +00007289 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00007290 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00007291 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00007292 /* 'using' */ LBrace,
7293 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00007294 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00007295 /* identifier */ SourceLocation(),
7296 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00007297 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00007298 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00007299 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00007300 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007301 }
7302
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007303 ActOnDocumentableDecl(Namespc);
7304
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007305 // Although we could have an invalid decl (i.e. the namespace name is a
7306 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00007307 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7308 // for the namespace has the declarations that showed up in that particular
7309 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00007310 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00007311 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007312}
7313
Sebastian Redla6602e92009-11-23 15:34:23 +00007314/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7315/// is a namespace alias, returns the namespace it points to.
7316static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7317 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7318 return AD->getNamespace();
7319 return dyn_cast_or_null<NamespaceDecl>(D);
7320}
7321
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007322/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7323/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00007324void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007325 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7326 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007327 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007328 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00007329 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007330 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007331}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007332
John McCall28a0cf72010-08-25 07:42:41 +00007333CXXRecordDecl *Sema::getStdBadAlloc() const {
7334 return cast_or_null<CXXRecordDecl>(
7335 StdBadAlloc.get(Context.getExternalSource()));
7336}
7337
7338NamespaceDecl *Sema::getStdNamespace() const {
7339 return cast_or_null<NamespaceDecl>(
7340 StdNamespace.get(Context.getExternalSource()));
7341}
7342
Douglas Gregorcdf87022010-06-29 17:53:46 +00007343/// \brief Retrieve the special "std" namespace, which may require us to
7344/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007345NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00007346 if (!StdNamespace) {
7347 // The "std" namespace has not yet been defined, so build one implicitly.
7348 StdNamespace = NamespaceDecl::Create(Context,
7349 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007350 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007351 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007352 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00007353 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007354 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007355 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00007356
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007357 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007358}
7359
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007360bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007361 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007362 "Looking for std::initializer_list outside of C++.");
7363
7364 // We're looking for implicit instantiations of
7365 // template <typename E> class std::initializer_list.
7366
7367 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7368 return false;
7369
Craig Topperc3ec1492014-05-26 06:22:03 +00007370 ClassTemplateDecl *Template = nullptr;
7371 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007372
Sebastian Redl43144e72012-01-17 22:49:58 +00007373 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007374
Sebastian Redl43144e72012-01-17 22:49:58 +00007375 ClassTemplateSpecializationDecl *Specialization =
7376 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7377 if (!Specialization)
7378 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007379
Sebastian Redl43144e72012-01-17 22:49:58 +00007380 Template = Specialization->getSpecializedTemplate();
7381 Arguments = Specialization->getTemplateArgs().data();
7382 } else if (const TemplateSpecializationType *TST =
7383 Ty->getAs<TemplateSpecializationType>()) {
7384 Template = dyn_cast_or_null<ClassTemplateDecl>(
7385 TST->getTemplateName().getAsTemplateDecl());
7386 Arguments = TST->getArgs();
7387 }
7388 if (!Template)
7389 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007390
7391 if (!StdInitializerList) {
7392 // Haven't recognized std::initializer_list yet, maybe this is it.
7393 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7394 if (TemplateClass->getIdentifier() !=
7395 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007396 !getStdNamespace()->InEnclosingNamespaceSetOf(
7397 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007398 return false;
7399 // This is a template called std::initializer_list, but is it the right
7400 // template?
7401 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007402 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007403 return false;
7404 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7405 return false;
7406
7407 // It's the right template.
7408 StdInitializerList = Template;
7409 }
7410
Richard Smith7d7dee72015-02-24 03:30:14 +00007411 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007412 return false;
7413
7414 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007415 if (Element)
7416 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007417 return true;
7418}
7419
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007420static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7421 NamespaceDecl *Std = S.getStdNamespace();
7422 if (!Std) {
7423 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007424 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007425 }
7426
7427 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7428 Loc, Sema::LookupOrdinaryName);
7429 if (!S.LookupQualifiedName(Result, Std)) {
7430 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007431 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007432 }
7433 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7434 if (!Template) {
7435 Result.suppressDiagnostics();
7436 // We found something weird. Complain about the first thing we found.
7437 NamedDecl *Found = *Result.begin();
7438 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007439 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007440 }
7441
7442 // We found some template called std::initializer_list. Now verify that it's
7443 // correct.
7444 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007445 if (Params->getMinRequiredArguments() != 1 ||
7446 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007447 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007448 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007449 }
7450
7451 return Template;
7452}
7453
7454QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7455 if (!StdInitializerList) {
7456 StdInitializerList = LookupStdInitializerList(*this, Loc);
7457 if (!StdInitializerList)
7458 return QualType();
7459 }
7460
7461 TemplateArgumentListInfo Args(Loc, Loc);
7462 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7463 Context.getTrivialTypeSourceInfo(Element,
7464 Loc)));
7465 return Context.getCanonicalType(
7466 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7467}
7468
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007469bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7470 // C++ [dcl.init.list]p2:
7471 // A constructor is an initializer-list constructor if its first parameter
7472 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7473 // std::initializer_list<E> for some type E, and either there are no other
7474 // parameters or else all other parameters have default arguments.
7475 if (Ctor->getNumParams() < 1 ||
7476 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7477 return false;
7478
7479 QualType ArgType = Ctor->getParamDecl(0)->getType();
7480 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7481 ArgType = RT->getPointeeType().getUnqualifiedType();
7482
Craig Topperc3ec1492014-05-26 06:22:03 +00007483 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007484}
7485
Douglas Gregora172e082011-03-26 22:25:30 +00007486/// \brief Determine whether a using statement is in a context where it will be
7487/// apply in all contexts.
7488static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7489 switch (CurContext->getDeclKind()) {
7490 case Decl::TranslationUnit:
7491 return true;
7492 case Decl::LinkageSpec:
7493 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7494 default:
7495 return false;
7496 }
7497}
7498
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007499namespace {
7500
7501// Callback to only accept typo corrections that are namespaces.
7502class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007503public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007504 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007505 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007506 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007507 return false;
7508 }
7509};
7510
7511}
7512
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007513static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7514 CXXScopeSpec &SS,
7515 SourceLocation IdentLoc,
7516 IdentifierInfo *Ident) {
7517 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007518 if (TypoCorrection Corrected =
7519 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7520 llvm::make_unique<NamespaceValidatorCCC>(),
7521 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007522 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007523 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7524 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007525 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007526 S.diagnoseTypo(Corrected,
7527 S.PDiag(diag::err_using_directive_member_suggest)
7528 << Ident << DC << DroppedSpecifier << SS.getRange(),
7529 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007530 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007531 S.diagnoseTypo(Corrected,
7532 S.PDiag(diag::err_using_directive_suggest) << Ident,
7533 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007534 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007535 R.addDecl(Corrected.getCorrectionDecl());
7536 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007537 }
7538 return false;
7539}
7540
John McCall48871652010-08-21 09:40:31 +00007541Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007542 SourceLocation UsingLoc,
7543 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007544 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007545 SourceLocation IdentLoc,
7546 IdentifierInfo *NamespcName,
7547 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007548 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7549 assert(NamespcName && "Invalid NamespcName.");
7550 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007551
7552 // This can only happen along a recovery path.
7553 while (S->getFlags() & Scope::TemplateParamScope)
7554 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007555 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007556
Craig Topperc3ec1492014-05-26 06:22:03 +00007557 UsingDirectiveDecl *UDir = nullptr;
7558 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007559 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007560 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007561
Douglas Gregor34074322009-01-14 22:20:51 +00007562 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007563 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7564 LookupParsedName(R, S, &SS);
7565 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007566 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007567
Douglas Gregorcdf87022010-06-29 17:53:46 +00007568 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007569 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007570 // Allow "using namespace std;" or "using namespace ::std;" even if
7571 // "std" hasn't been defined yet, for GCC compatibility.
7572 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7573 NamespcName->isStr("std")) {
7574 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007575 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007576 R.resolveKind();
7577 }
7578 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007579 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007580 }
7581
John McCall9f3059a2009-10-09 21:13:30 +00007582 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007583 NamedDecl *Named = R.getFoundDecl();
7584 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7585 && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00007586
Nico Riecke50e59a2014-11-24 17:29:52 +00007587 // The use of a nested name specifier may trigger deprecation warnings.
7588 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00007589
Douglas Gregor889ceb72009-02-03 19:21:40 +00007590 // C++ [namespace.udir]p1:
7591 // A using-directive specifies that the names in the nominated
7592 // namespace can be used in the scope in which the
7593 // using-directive appears after the using-directive. During
7594 // unqualified name lookup (3.4.1), the names appear as if they
7595 // were declared in the nearest enclosing namespace which
7596 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007597 // namespace. [Note: in this context, "contains" means "contains
7598 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007599
7600 // Find enclosing context containing both using-directive and
7601 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007602 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007603 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7604 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7605 CommonAncestor = CommonAncestor->getParent();
7606
Sebastian Redla6602e92009-11-23 15:34:23 +00007607 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007608 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007609 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007610
Douglas Gregora172e082011-03-26 22:25:30 +00007611 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007612 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007613 Diag(IdentLoc, diag::warn_using_directive_in_header);
7614 }
7615
Douglas Gregor889ceb72009-02-03 19:21:40 +00007616 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007617 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007618 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007619 }
7620
Richard Smith54ecd982013-02-20 19:22:51 +00007621 if (UDir)
7622 ProcessDeclAttributeList(S, UDir, AttrList);
7623
John McCall48871652010-08-21 09:40:31 +00007624 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007625}
7626
7627void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007628 // If the scope has an associated entity and the using directive is at
7629 // namespace or translation unit scope, add the UsingDirectiveDecl into
7630 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007631 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007632 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007633 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007634 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007635 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007636 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007637 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007638}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007639
Douglas Gregorfec52632009-06-20 00:51:54 +00007640
John McCall48871652010-08-21 09:40:31 +00007641Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007642 AccessSpecifier AS,
7643 bool HasUsingKeyword,
7644 SourceLocation UsingLoc,
7645 CXXScopeSpec &SS,
7646 UnqualifiedId &Name,
7647 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007648 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007649 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007650 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007651
Douglas Gregor220f4272009-11-04 16:30:06 +00007652 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007653 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007654 case UnqualifiedId::IK_Identifier:
7655 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007656 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007657 case UnqualifiedId::IK_ConversionFunctionId:
7658 break;
7659
7660 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007661 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007662 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007663 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007664 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007665 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007666 diag::err_using_decl_constructor)
7667 << SS.getRange();
7668
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007669 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007670
Craig Topperc3ec1492014-05-26 06:22:03 +00007671 return nullptr;
7672
Douglas Gregor220f4272009-11-04 16:30:06 +00007673 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007674 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007675 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007676 return nullptr;
7677
Douglas Gregor220f4272009-11-04 16:30:06 +00007678 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007679 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007680 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007681 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007682 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007683
7684 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7685 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007686 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007687 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007688
Richard Smithc2bc61b2013-03-18 21:12:30 +00007689 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007690 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007691 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007692 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7693 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007694 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007695 }
7696
Douglas Gregorc4356532010-12-16 00:46:58 +00007697 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7698 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007699 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007700
John McCall3f746822009-11-17 05:59:44 +00007701 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007702 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007703 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007704 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007705 if (UD)
7706 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007707
John McCall48871652010-08-21 09:40:31 +00007708 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007709}
7710
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007711/// \brief Determine whether a using declaration considers the given
7712/// declarations as "equivalent", e.g., if they are redeclarations of
7713/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007714static bool
7715IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7716 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007717 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007718
Richard Smithdda56e42011-04-15 14:24:37 +00007719 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007720 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007721 return Context.hasSameType(TD1->getUnderlyingType(),
7722 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007723
7724 return false;
7725}
7726
7727
John McCall84d87672009-12-10 09:41:52 +00007728/// Determines whether to create a using shadow decl for a particular
7729/// decl, given the set of decls existing prior to this using lookup.
7730bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007731 const LookupResult &Previous,
7732 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007733 // Diagnose finding a decl which is not from a base class of the
7734 // current class. We do this now because there are cases where this
7735 // function will silently decide not to build a shadow decl, which
7736 // will pre-empt further diagnostics.
7737 //
7738 // We don't need to do this in C++0x because we do the check once on
7739 // the qualifier.
7740 //
7741 // FIXME: diagnose the following if we care enough:
7742 // struct A { int foo; };
7743 // struct B : A { using A::foo; };
7744 // template <class T> struct C : A {};
7745 // template <class T> struct D : C<T> { using B::foo; } // <---
7746 // This is invalid (during instantiation) in C++03 because B::foo
7747 // resolves to the using decl in B, which is not a base class of D<T>.
7748 // We can't diagnose it immediately because C<T> is an unknown
7749 // specialization. The UsingShadowDecl in D<T> then points directly
7750 // to A::foo, which will look well-formed when we instantiate.
7751 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007752 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007753 DeclContext *OrigDC = Orig->getDeclContext();
7754
7755 // Handle enums and anonymous structs.
7756 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7757 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7758 while (OrigRec->isAnonymousStructOrUnion())
7759 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7760
7761 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7762 if (OrigDC == CurContext) {
7763 Diag(Using->getLocation(),
7764 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007765 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007766 Diag(Orig->getLocation(), diag::note_using_decl_target);
7767 return true;
7768 }
7769
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007770 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007771 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007772 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007773 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007774 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007775 Diag(Orig->getLocation(), diag::note_using_decl_target);
7776 return true;
7777 }
7778 }
7779
7780 if (Previous.empty()) return false;
7781
7782 NamedDecl *Target = Orig;
7783 if (isa<UsingShadowDecl>(Target))
7784 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7785
John McCalla17e83e2009-12-11 02:33:26 +00007786 // If the target happens to be one of the previous declarations, we
7787 // don't have a conflict.
7788 //
7789 // FIXME: but we might be increasing its access, in which case we
7790 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007791 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007792 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007793 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7794 I != E; ++I) {
7795 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007796 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7797 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7798 PrevShadow = Shadow;
7799 FoundEquivalentDecl = true;
7800 }
John McCalla17e83e2009-12-11 02:33:26 +00007801
7802 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7803 }
7804
Richard Smithfd8634a2013-10-23 02:17:46 +00007805 if (FoundEquivalentDecl)
7806 return false;
7807
Alp Tokera2794f92014-01-22 07:29:52 +00007808 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007809 NamedDecl *OldDecl = nullptr;
7810 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7811 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007812 case Ovl_Overload:
7813 return false;
7814
7815 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007816 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007817 break;
Richard Smith18819302014-02-06 01:31:33 +00007818
John McCall84d87672009-12-10 09:41:52 +00007819 // We found a decl with the exact signature.
7820 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007821 // If we're in a record, we want to hide the target, so we
7822 // return true (without a diagnostic) to tell the caller not to
7823 // build a shadow decl.
7824 if (CurContext->isRecord())
7825 return true;
7826
7827 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007828 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007829 break;
7830 }
7831
7832 Diag(Target->getLocation(), diag::note_using_decl_target);
7833 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7834 return true;
7835 }
7836
7837 // Target is not a function.
7838
John McCall84d87672009-12-10 09:41:52 +00007839 if (isa<TagDecl>(Target)) {
7840 // No conflict between a tag and a non-tag.
7841 if (!Tag) return false;
7842
John McCalle29c5cd2009-12-10 19:51:03 +00007843 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007844 Diag(Target->getLocation(), diag::note_using_decl_target);
7845 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7846 return true;
7847 }
7848
7849 // No conflict between a tag and a non-tag.
7850 if (!NonTag) return false;
7851
John McCalle29c5cd2009-12-10 19:51:03 +00007852 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007853 Diag(Target->getLocation(), diag::note_using_decl_target);
7854 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7855 return true;
7856}
7857
John McCall3f746822009-11-17 05:59:44 +00007858/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007859UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007860 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007861 NamedDecl *Orig,
7862 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007863
7864 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007865 NamedDecl *Target = Orig;
7866 if (isa<UsingShadowDecl>(Target)) {
7867 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7868 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007869 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007870
John McCall3f746822009-11-17 05:59:44 +00007871 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007872 = UsingShadowDecl::Create(Context, CurContext,
7873 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007874 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007875
Douglas Gregor457104e2010-09-29 04:25:11 +00007876 Shadow->setAccess(UD->getAccess());
7877 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7878 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007879
7880 Shadow->setPreviousDecl(PrevDecl);
7881
John McCall3f746822009-11-17 05:59:44 +00007882 if (S)
John McCall3969e302009-12-08 07:46:18 +00007883 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007884 else
John McCall3969e302009-12-08 07:46:18 +00007885 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007886
John McCall3969e302009-12-08 07:46:18 +00007887
John McCall84d87672009-12-10 09:41:52 +00007888 return Shadow;
7889}
John McCall3969e302009-12-08 07:46:18 +00007890
John McCall84d87672009-12-10 09:41:52 +00007891/// Hides a using shadow declaration. This is required by the current
7892/// using-decl implementation when a resolvable using declaration in a
7893/// class is followed by a declaration which would hide or override
7894/// one or more of the using decl's targets; for example:
7895///
7896/// struct Base { void foo(int); };
7897/// struct Derived : Base {
7898/// using Base::foo;
7899/// void foo(int);
7900/// };
7901///
7902/// The governing language is C++03 [namespace.udecl]p12:
7903///
7904/// When a using-declaration brings names from a base class into a
7905/// derived class scope, member functions in the derived class
7906/// override and/or hide member functions with the same name and
7907/// parameter types in a base class (rather than conflicting).
7908///
7909/// There are two ways to implement this:
7910/// (1) optimistically create shadow decls when they're not hidden
7911/// by existing declarations, or
7912/// (2) don't create any shadow decls (or at least don't make them
7913/// visible) until we've fully parsed/instantiated the class.
7914/// The problem with (1) is that we might have to retroactively remove
7915/// a shadow decl, which requires several O(n) operations because the
7916/// decl structures are (very reasonably) not designed for removal.
7917/// (2) avoids this but is very fiddly and phase-dependent.
7918void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007919 if (Shadow->getDeclName().getNameKind() ==
7920 DeclarationName::CXXConversionFunctionName)
7921 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7922
John McCall84d87672009-12-10 09:41:52 +00007923 // Remove it from the DeclContext...
7924 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007925
John McCall84d87672009-12-10 09:41:52 +00007926 // ...and the scope, if applicable...
7927 if (S) {
John McCall48871652010-08-21 09:40:31 +00007928 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007929 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007930 }
7931
John McCall84d87672009-12-10 09:41:52 +00007932 // ...and the using decl.
7933 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7934
7935 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007936 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007937}
7938
Richard Smith09d5b3a2014-05-01 00:35:04 +00007939/// Find the base specifier for a base class with the given type.
7940static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7941 QualType DesiredBase,
7942 bool &AnyDependentBases) {
7943 // Check whether the named type is a direct base class.
7944 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7945 for (auto &Base : Derived->bases()) {
7946 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7947 if (CanonicalDesiredBase == BaseType)
7948 return &Base;
7949 if (BaseType->isDependentType())
7950 AnyDependentBases = true;
7951 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007952 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007953}
7954
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007955namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007956class UsingValidatorCCC : public CorrectionCandidateCallback {
7957public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007958 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007959 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007960 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007961 IsInstantiation(IsInstantiation), OldNNS(NNS),
7962 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007963
Craig Toppera798a9d2014-03-02 09:32:10 +00007964 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007965 NamedDecl *ND = Candidate.getCorrectionDecl();
7966
7967 // Keywords are not valid here.
7968 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007969 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007970
7971 // Completely unqualified names are invalid for a 'using' declaration.
7972 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7973 return false;
7974
Richard Smith09d5b3a2014-05-01 00:35:04 +00007975 if (RequireMemberOf) {
7976 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7977 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7978 // No-one ever wants a using-declaration to name an injected-class-name
7979 // of a base class, unless they're declaring an inheriting constructor.
7980 ASTContext &Ctx = ND->getASTContext();
7981 if (!Ctx.getLangOpts().CPlusPlus11)
7982 return false;
7983 QualType FoundType = Ctx.getRecordType(FoundRecord);
7984
7985 // Check that the injected-class-name is named as a member of its own
7986 // type; we don't want to suggest 'using Derived::Base;', since that
7987 // means something else.
7988 NestedNameSpecifier *Specifier =
7989 Candidate.WillReplaceSpecifier()
7990 ? Candidate.getCorrectionSpecifier()
7991 : OldNNS;
7992 if (!Specifier->getAsType() ||
7993 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7994 return false;
7995
7996 // Check that this inheriting constructor declaration actually names a
7997 // direct base class of the current class.
7998 bool AnyDependentBases = false;
7999 if (!findDirectBaseWithType(RequireMemberOf,
8000 Ctx.getRecordType(FoundRecord),
8001 AnyDependentBases) &&
8002 !AnyDependentBases)
8003 return false;
8004 } else {
8005 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8006 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8007 return false;
8008
8009 // FIXME: Check that the base class member is accessible?
8010 }
8011 }
8012
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008013 if (isa<TypeDecl>(ND))
8014 return HasTypenameKeyword || !IsInstantiation;
8015
8016 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008017 }
8018
8019private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008020 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008021 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008022 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00008023 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008024};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008025} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008026
John McCalle61f2ba2009-11-18 02:36:19 +00008027/// Builds a using declaration.
8028///
8029/// \param IsInstantiation - Whether this call arises from an
8030/// instantiation of an unresolved using declaration. We treat
8031/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00008032NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8033 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008034 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00008035 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00008036 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00008037 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008038 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00008039 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00008040 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008041 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00008042 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00008043
Anders Carlssonf038fc22009-08-28 05:49:21 +00008044 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00008045
Anders Carlsson59140b32009-08-28 03:16:11 +00008046 if (SS.isEmpty()) {
8047 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00008048 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00008049 }
Mike Stump11289f42009-09-09 15:08:12 +00008050
John McCall84d87672009-12-10 09:41:52 +00008051 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008052 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00008053 ForRedeclaration);
8054 Previous.setHideTags(false);
8055 if (S) {
8056 LookupName(Previous, S);
8057
8058 // It is really dumb that we have to do this.
8059 LookupResult::Filter F = Previous.makeFilter();
8060 while (F.hasNext()) {
8061 NamedDecl *D = F.next();
8062 if (!isDeclInScope(D, CurContext, S))
8063 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00008064 // If we found a local extern declaration that's not ordinarily visible,
8065 // and this declaration is being added to a non-block scope, ignore it.
8066 // We're only checking for scope conflicts here, not also for violations
8067 // of the linkage rules.
8068 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8069 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8070 F.erase();
John McCall84d87672009-12-10 09:41:52 +00008071 }
8072 F.done();
8073 } else {
8074 assert(IsInstantiation && "no scope in non-instantiation");
8075 assert(CurContext->isRecord() && "scope not record in instantiation");
8076 LookupQualifiedName(Previous, CurContext);
8077 }
8078
John McCall84d87672009-12-10 09:41:52 +00008079 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008080 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8081 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00008082 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00008083
8084 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00008085 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00008086 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00008087
John McCall84c16cf2009-11-12 03:15:40 +00008088 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008089 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008090 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00008091 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008092 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00008093 // FIXME: not all declaration name kinds are legal here
8094 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8095 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008096 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008097 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00008098 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008099 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8100 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00008101 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00008102 D->setAccess(AS);
8103 CurContext->addDecl(D);
8104 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00008105 }
John McCallb96ec562009-12-04 22:46:56 +00008106
Richard Smith09d5b3a2014-05-01 00:35:04 +00008107 auto Build = [&](bool Invalid) {
8108 UsingDecl *UD =
8109 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8110 HasTypenameKeyword);
8111 UD->setAccess(AS);
8112 CurContext->addDecl(UD);
8113 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00008114 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008115 };
8116 auto BuildInvalid = [&]{ return Build(true); };
8117 auto BuildValid = [&]{ return Build(false); };
8118
8119 if (RequireCompleteDeclContext(SS, LookupContext))
8120 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00008121
Richard Smith78163e22015-04-01 19:31:06 +00008122 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008123 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00008124
John McCall3969e302009-12-08 07:46:18 +00008125 // Unlike most lookups, we don't always want to hide tag
8126 // declarations: tag names are visible through the using declaration
8127 // even if hidden by ordinary names, *except* in a dependent context
8128 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00008129 if (!IsInstantiation)
8130 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00008131
John McCall5dadb652012-04-07 03:04:20 +00008132 // For the purposes of this lookup, we have a base object type
8133 // equal to that of the current context.
8134 if (CurContext->isRecord()) {
8135 R.setBaseObjectType(
8136 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8137 }
8138
John McCall27b18f82009-11-17 02:14:36 +00008139 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00008140
Richard Smith78163e22015-04-01 19:31:06 +00008141 // Try to correct typos if possible. If constructor name lookup finds no
8142 // results, that means the named class has no explicit constructors, and we
8143 // suppressed declaring implicit ones (probably because it's dependent or
8144 // invalid).
8145 if (R.empty() &&
8146 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008147 if (TypoCorrection Corrected = CorrectTypo(
8148 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8149 llvm::make_unique<UsingValidatorCCC>(
8150 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8151 dyn_cast<CXXRecordDecl>(CurContext)),
8152 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008153 // We reject any correction for which ND would be NULL.
8154 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008155
Richard Smithf9b15102013-08-17 00:46:16 +00008156 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008157 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00008158 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8159 << NameInfo.getName() << LookupContext << 0
8160 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00008161
8162 // If we corrected to an inheriting constructor, handle it as one.
8163 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8164 if (RD && RD->isInjectedClassName()) {
8165 // Fix up the information we'll use to build the using declaration.
8166 if (Corrected.WillReplaceSpecifier()) {
8167 NestedNameSpecifierLocBuilder Builder;
8168 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8169 QualifierLoc.getSourceRange());
8170 QualifierLoc = Builder.getWithLocInContext(Context);
8171 }
8172
8173 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8174 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00008175 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00008176 for (auto *Ctor : LookupConstructors(RD))
8177 R.addDecl(Ctor);
8178 } else {
8179 // FIXME: Pick up all the declarations if we found an overloaded function.
8180 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008181 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008182 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008183 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008184 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008185 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008186 }
Douglas Gregorfec52632009-06-20 00:51:54 +00008187 }
8188
Richard Smith09d5b3a2014-05-01 00:35:04 +00008189 if (R.isAmbiguous())
8190 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00008191
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008192 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00008193 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00008194 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008195 Diag(IdentLoc, diag::err_using_typename_non_type);
8196 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8197 Diag((*I)->getUnderlyingDecl()->getLocation(),
8198 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008199 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008200 }
8201 } else {
8202 // If we asked for a non-typename and we got a type, error out,
8203 // but only if this is an instantiation of an unresolved using
8204 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00008205 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008206 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8207 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008208 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008209 }
Anders Carlsson59140b32009-08-28 03:16:11 +00008210 }
8211
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008212 // C++0x N2914 [namespace.udecl]p6:
8213 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00008214 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008215 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8216 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008217 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008218 }
Mike Stump11289f42009-09-09 15:08:12 +00008219
Richard Smith09d5b3a2014-05-01 00:35:04 +00008220 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00008221
8222 // The normal rules do not apply to inheriting constructor declarations.
8223 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8224 // Suppress access diagnostics; the access check is instead performed at the
8225 // point of use for an inheriting constructor.
8226 R.suppressDiagnostics();
8227 CheckInheritingConstructorUsingDecl(UD);
8228 return UD;
8229 }
8230
8231 // Otherwise, look up the target name.
8232
John McCall84d87672009-12-10 09:41:52 +00008233 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008234 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008235 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8236 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00008237 }
John McCall3f746822009-11-17 05:59:44 +00008238
8239 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00008240}
8241
Sebastian Redl08905022011-02-05 19:23:19 +00008242/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00008243bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008244 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00008245
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008246 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00008247 assert(SourceType &&
8248 "Using decl naming constructor doesn't have type in scope spec.");
8249 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8250
8251 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00008252 bool AnyDependentBases = false;
8253 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8254 AnyDependentBases);
8255 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008256 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00008257 diag::err_using_decl_constructor_not_in_direct_base)
8258 << UD->getNameInfo().getSourceRange()
8259 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008260 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00008261 return true;
8262 }
8263
Richard Smith09d5b3a2014-05-01 00:35:04 +00008264 if (Base)
8265 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00008266
8267 return false;
8268}
8269
John McCall84d87672009-12-10 09:41:52 +00008270/// Checks that the given using declaration is not an invalid
8271/// redeclaration. Note that this is checking only for the using decl
8272/// itself, not for any ill-formedness among the UsingShadowDecls.
8273bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008274 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00008275 const CXXScopeSpec &SS,
8276 SourceLocation NameLoc,
8277 const LookupResult &Prev) {
8278 // C++03 [namespace.udecl]p8:
8279 // C++0x [namespace.udecl]p10:
8280 // A using-declaration is a declaration and can therefore be used
8281 // repeatedly where (and only where) multiple declarations are
8282 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00008283 //
John McCall032092f2010-11-29 18:01:58 +00008284 // That's in non-member contexts.
8285 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00008286 return false;
8287
Aaron Ballman4a979672014-01-03 13:56:08 +00008288 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00008289
8290 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8291 NamedDecl *D = *I;
8292
8293 bool DTypename;
8294 NestedNameSpecifier *DQual;
8295 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008296 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008297 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008298 } else if (UnresolvedUsingValueDecl *UD
8299 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8300 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008301 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008302 } else if (UnresolvedUsingTypenameDecl *UD
8303 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8304 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008305 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008306 } else continue;
8307
8308 // using decls differ if one says 'typename' and the other doesn't.
8309 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008310 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00008311
8312 // using decls differ if they name different scopes (but note that
8313 // template instantiation can cause this check to trigger when it
8314 // didn't before instantiation).
8315 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8316 Context.getCanonicalNestedNameSpecifier(DQual))
8317 continue;
8318
8319 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00008320 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00008321 return true;
8322 }
8323
8324 return false;
8325}
8326
John McCall3969e302009-12-08 07:46:18 +00008327
John McCallb96ec562009-12-04 22:46:56 +00008328/// Checks that the given nested-name qualifier used in a using decl
8329/// in the current context is appropriately related to the current
8330/// scope. If an error is found, diagnoses it and returns true.
8331bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8332 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00008333 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00008334 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00008335 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008336
John McCall3969e302009-12-08 07:46:18 +00008337 if (!CurContext->isRecord()) {
8338 // C++03 [namespace.udecl]p3:
8339 // C++0x [namespace.udecl]p8:
8340 // A using-declaration for a class member shall be a member-declaration.
8341
8342 // If we weren't able to compute a valid scope, it must be a
8343 // dependent class scope.
8344 if (!NamedContext || NamedContext->isRecord()) {
David Majnemer4d2de1b02014-12-17 02:41:36 +00008345 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
Richard Smith7ad0b882014-04-02 21:44:35 +00008346 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00008347 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008348
John McCall3969e302009-12-08 07:46:18 +00008349 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8350 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00008351
8352 // If we have a complete, non-dependent source type, try to suggest a
8353 // way to get the same effect.
8354 if (!RD)
8355 return true;
8356
8357 // Find what this using-declaration was referring to.
8358 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8359 R.setHideTags(false);
8360 R.suppressDiagnostics();
8361 LookupQualifiedName(R, RD);
8362
8363 if (R.getAsSingle<TypeDecl>()) {
8364 if (getLangOpts().CPlusPlus11) {
8365 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8366 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8367 << 0 // alias declaration
8368 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8369 NameInfo.getName().getAsString() +
8370 " = ");
8371 } else {
8372 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8373 SourceLocation InsertLoc =
8374 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8375 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8376 << 1 // typedef declaration
8377 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8378 << FixItHint::CreateInsertion(
8379 InsertLoc, " " + NameInfo.getName().getAsString());
8380 }
8381 } else if (R.getAsSingle<VarDecl>()) {
8382 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8383 // repeating the type of the static data member here.
8384 FixItHint FixIt;
8385 if (getLangOpts().CPlusPlus11) {
8386 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8387 FixIt = FixItHint::CreateReplacement(
8388 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8389 }
8390
8391 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8392 << 2 // reference declaration
8393 << FixIt;
8394 }
John McCall3969e302009-12-08 07:46:18 +00008395 return true;
8396 }
8397
8398 // Otherwise, everything is known to be fine.
8399 return false;
8400 }
8401
8402 // The current scope is a record.
8403
8404 // If the named context is dependent, we can't decide much.
8405 if (!NamedContext) {
8406 // FIXME: in C++0x, we can diagnose if we can prove that the
8407 // nested-name-specifier does not refer to a base class, which is
8408 // still possible in some cases.
8409
8410 // Otherwise we have to conservatively report that things might be
8411 // okay.
8412 return false;
8413 }
8414
8415 if (!NamedContext->isRecord()) {
8416 // Ideally this would point at the last name in the specifier,
8417 // but we don't have that level of source info.
8418 Diag(SS.getRange().getBegin(),
8419 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008420 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008421 return true;
8422 }
8423
Douglas Gregor7c842292010-12-21 07:41:49 +00008424 if (!NamedContext->isDependentContext() &&
8425 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8426 return true;
8427
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008428 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008429 // C++0x [namespace.udecl]p3:
8430 // In a using-declaration used as a member-declaration, the
8431 // nested-name-specifier shall name a base class of the class
8432 // being defined.
8433
8434 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8435 cast<CXXRecordDecl>(NamedContext))) {
8436 if (CurContext == NamedContext) {
8437 Diag(NameLoc,
8438 diag::err_using_decl_nested_name_specifier_is_current_class)
8439 << SS.getRange();
8440 return true;
8441 }
8442
8443 Diag(SS.getRange().getBegin(),
8444 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008445 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008446 << cast<CXXRecordDecl>(CurContext)
8447 << SS.getRange();
8448 return true;
8449 }
8450
8451 return false;
8452 }
8453
8454 // C++03 [namespace.udecl]p4:
8455 // A using-declaration used as a member-declaration shall refer
8456 // to a member of a base class of the class being defined [etc.].
8457
8458 // Salient point: SS doesn't have to name a base class as long as
8459 // lookup only finds members from base classes. Therefore we can
8460 // diagnose here only if we can prove that that can't happen,
8461 // i.e. if the class hierarchies provably don't intersect.
8462
8463 // TODO: it would be nice if "definitely valid" results were cached
8464 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8465 // need to be repeated.
8466
8467 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008468 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008469
8470 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8471 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8472 Data->Bases.insert(Base);
8473 return true;
8474 }
8475
8476 bool hasDependentBases(const CXXRecordDecl *Class) {
8477 return !Class->forallBases(collect, this);
8478 }
8479
8480 /// Returns true if the base is dependent or is one of the
8481 /// accumulated base classes.
8482 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8483 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8484 return !Data->Bases.count(Base);
8485 }
8486
8487 bool mightShareBases(const CXXRecordDecl *Class) {
8488 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8489 }
8490 };
8491
8492 UserData Data;
8493
8494 // Returns false if we find a dependent base.
8495 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8496 return false;
8497
8498 // Returns false if the class has a dependent base or if it or one
8499 // of its bases is present in the base set of the current context.
8500 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8501 return false;
8502
8503 Diag(SS.getRange().getBegin(),
8504 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008505 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008506 << cast<CXXRecordDecl>(CurContext)
8507 << SS.getRange();
8508
8509 return true;
John McCallb96ec562009-12-04 22:46:56 +00008510}
8511
Richard Smithdda56e42011-04-15 14:24:37 +00008512Decl *Sema::ActOnAliasDeclaration(Scope *S,
8513 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008514 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008515 SourceLocation UsingLoc,
8516 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008517 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00008518 TypeResult Type,
8519 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008520 // Skip up to the relevant declaration scope.
8521 while (S->getFlags() & Scope::TemplateParamScope)
8522 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008523 assert((S->getFlags() & Scope::DeclScope) &&
8524 "got alias-declaration outside of declaration scope");
8525
8526 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008527 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008528
8529 bool Invalid = false;
8530 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008531 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008532 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008533
8534 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008535 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008536
8537 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008538 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008539 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008540 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8541 TInfo->getTypeLoc().getBeginLoc());
8542 }
Richard Smithdda56e42011-04-15 14:24:37 +00008543
8544 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8545 LookupName(Previous, S);
8546
8547 // Warn about shadowing the name of a template parameter.
8548 if (Previous.isSingleResult() &&
8549 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008550 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008551 Previous.clear();
8552 }
8553
8554 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8555 "name in alias declaration must be an identifier");
8556 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8557 Name.StartLocation,
8558 Name.Identifier, TInfo);
8559
8560 NewTD->setAccess(AS);
8561
8562 if (Invalid)
8563 NewTD->setInvalidDecl();
8564
Richard Smith54ecd982013-02-20 19:22:51 +00008565 ProcessDeclAttributeList(S, NewTD, AttrList);
8566
Richard Smith3f1b5d02011-05-05 21:57:07 +00008567 CheckTypedefForVariablyModifiedType(S, NewTD);
8568 Invalid |= NewTD->isInvalidDecl();
8569
Richard Smithdda56e42011-04-15 14:24:37 +00008570 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008571
8572 NamedDecl *NewND;
8573 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008574 TypeAliasTemplateDecl *OldDecl = nullptr;
8575 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008576
8577 if (TemplateParamLists.size() != 1) {
8578 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008579 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8580 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008581 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008582 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008583
8584 // Only consider previous declarations in the same scope.
8585 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8586 /*ExplicitInstantiationOrSpecialization*/false);
8587 if (!Previous.empty()) {
8588 Redeclaration = true;
8589
8590 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8591 if (!OldDecl && !Invalid) {
8592 Diag(UsingLoc, diag::err_redefinition_different_kind)
8593 << Name.Identifier;
8594
8595 NamedDecl *OldD = Previous.getRepresentativeDecl();
8596 if (OldD->getLocation().isValid())
8597 Diag(OldD->getLocation(), diag::note_previous_definition);
8598
8599 Invalid = true;
8600 }
8601
8602 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8603 if (TemplateParameterListsAreEqual(TemplateParams,
8604 OldDecl->getTemplateParameters(),
8605 /*Complain=*/true,
8606 TPL_TemplateMatch))
8607 OldTemplateParams = OldDecl->getTemplateParameters();
8608 else
8609 Invalid = true;
8610
8611 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8612 if (!Invalid &&
8613 !Context.hasSameType(OldTD->getUnderlyingType(),
8614 NewTD->getUnderlyingType())) {
8615 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8616 // but we can't reasonably accept it.
8617 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8618 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8619 if (OldTD->getLocation().isValid())
8620 Diag(OldTD->getLocation(), diag::note_previous_definition);
8621 Invalid = true;
8622 }
8623 }
8624 }
8625
8626 // Merge any previous default template arguments into our parameters,
8627 // and check the parameter list.
8628 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8629 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008630 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008631
8632 TypeAliasTemplateDecl *NewDecl =
8633 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8634 Name.Identifier, TemplateParams,
8635 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008636 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008637
8638 NewDecl->setAccess(AS);
8639
8640 if (Invalid)
8641 NewDecl->setInvalidDecl();
8642 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008643 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008644
8645 NewND = NewDecl;
8646 } else {
David Majnemerf9bde282015-03-11 06:45:39 +00008647 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8648 setTagNameForLinkagePurposes(TD, NewTD);
8649 handleTagNumbering(TD, S);
8650 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00008651 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8652 NewND = NewTD;
8653 }
Richard Smithdda56e42011-04-15 14:24:37 +00008654
8655 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008656 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008657
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008658 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008659 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008660}
8661
Richard Smithf4634362014-09-03 23:11:22 +00008662Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8663 SourceLocation AliasLoc,
8664 IdentifierInfo *Alias, CXXScopeSpec &SS,
8665 SourceLocation IdentLoc,
8666 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008667
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008668 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008669 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8670 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008671
John McCall27b18f82009-11-17 02:14:36 +00008672 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008673 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008674
John McCall9f3059a2009-10-09 21:13:30 +00008675 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008676 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008677 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008678 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008679 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008680 }
Richard Smithf4634362014-09-03 23:11:22 +00008681 assert(!R.isAmbiguous() && !R.empty());
8682
8683 // Check if we have a previous declaration with the same name.
8684 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8685 ForRedeclaration);
8686 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8687 PrevDecl = nullptr;
8688
Aaron Ballman43f40102014-11-14 22:34:56 +00008689 NamedDecl *ND = R.getFoundDecl();
8690
Richard Smithf4634362014-09-03 23:11:22 +00008691 if (PrevDecl) {
8692 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8693 // We already have an alias with the same name that points to the same
8694 // namespace; check that it matches.
Aaron Ballman43f40102014-11-14 22:34:56 +00008695 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
Richard Smithf4634362014-09-03 23:11:22 +00008696 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8697 << Alias;
8698 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8699 << AD->getNamespace();
8700 return nullptr;
8701 }
8702 } else {
8703 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8704 ? diag::err_redefinition
8705 : diag::err_redefinition_different_kind;
8706 Diag(AliasLoc, DiagID) << Alias;
8707 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8708 return nullptr;
8709 }
8710 }
Mike Stump11289f42009-09-09 15:08:12 +00008711
Nico Riecke50e59a2014-11-24 17:29:52 +00008712 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00008713 DiagnoseUseOfDecl(ND, IdentLoc);
8714
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008715 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008716 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008717 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00008718 IdentLoc, ND);
Richard Smithf4634362014-09-03 23:11:22 +00008719 if (PrevDecl)
8720 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump11289f42009-09-09 15:08:12 +00008721
John McCalld8d0d432010-02-16 06:53:13 +00008722 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008723 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008724}
8725
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008726Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008727Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8728 CXXMethodDecl *MD) {
8729 CXXRecordDecl *ClassDecl = MD->getParent();
8730
Douglas Gregor6d880b12010-07-01 22:31:05 +00008731 // C++ [except.spec]p14:
8732 // An implicitly declared special member function (Clause 12) shall have an
8733 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008734 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008735 if (ClassDecl->isInvalidDecl())
8736 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008737
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008738 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008739 for (const auto &B : ClassDecl->bases()) {
8740 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008741 continue;
8742
Aaron Ballman574705e2014-03-13 15:41:46 +00008743 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008744 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008745 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8746 // If this is a deleted function, add it anyway. This might be conformant
8747 // with the standard. This might not. I'm not sure. It might not matter.
8748 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008749 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008750 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008751 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008752
8753 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008754 for (const auto &B : ClassDecl->vbases()) {
8755 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008756 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008757 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8758 // If this is a deleted function, add it anyway. This might be conformant
8759 // with the standard. This might not. I'm not sure. It might not matter.
8760 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008761 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008762 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008763 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008764
8765 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008766 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008767 if (F->hasInClassInitializer()) {
8768 if (Expr *E = F->getInClassInitializer())
8769 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00008770 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008771 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008772 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8773 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8774 // If this is a deleted function, add it anyway. This might be conformant
8775 // with the standard. This might not. I'm not sure. It might not matter.
8776 // In particular, the problem is that this function never gets called. It
8777 // might just be ill-formed because this function attempts to refer to
8778 // a deleted function here.
8779 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008780 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008781 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008782 }
John McCalldb40c7f2010-12-14 08:05:40 +00008783
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008784 return ExceptSpec;
8785}
8786
Richard Smithc2bc61b2013-03-18 21:12:30 +00008787Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008788Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8789 CXXRecordDecl *ClassDecl = CD->getParent();
8790
8791 // C++ [except.spec]p14:
8792 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008793 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008794 if (ClassDecl->isInvalidDecl())
8795 return ExceptSpec;
8796
8797 // Inherited constructor.
8798 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8799 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8800 // FIXME: Copying or moving the parameters could add extra exceptions to the
8801 // set, as could the default arguments for the inherited constructor. This
8802 // will be addressed when we implement the resolution of core issue 1351.
8803 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8804
8805 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008806 for (const auto &B : ClassDecl->bases()) {
8807 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008808 continue;
8809
Aaron Ballman574705e2014-03-13 15:41:46 +00008810 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008811 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8812 if (BaseClassDecl == InheritedDecl)
8813 continue;
8814 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8815 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008816 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008817 }
8818 }
8819
8820 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008821 for (const auto &B : ClassDecl->vbases()) {
8822 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008823 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8824 if (BaseClassDecl == InheritedDecl)
8825 continue;
8826 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8827 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008828 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008829 }
8830 }
8831
8832 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008833 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008834 if (F->hasInClassInitializer()) {
8835 if (Expr *E = F->getInClassInitializer())
8836 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00008837 } else if (const RecordType *RecordTy
8838 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8839 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8840 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8841 if (Constructor)
8842 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8843 }
8844 }
8845
Richard Smithc2bc61b2013-03-18 21:12:30 +00008846 return ExceptSpec;
8847}
8848
Richard Smith8bf22e52012-11-29 01:34:07 +00008849namespace {
8850/// RAII object to register a special member as being currently declared.
8851struct DeclaringSpecialMember {
8852 Sema &S;
8853 Sema::SpecialMemberDecl D;
8854 bool WasAlreadyBeingDeclared;
8855
8856 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8857 : S(S), D(RD, CSM) {
David Blaikie82e95a32014-11-19 07:49:47 +00008858 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00008859 if (WasAlreadyBeingDeclared)
8860 // This almost never happens, but if it does, ensure that our cache
8861 // doesn't contain a stale result.
8862 S.SpecialMemberCache.clear();
8863
8864 // FIXME: Register a note to be produced if we encounter an error while
8865 // declaring the special member.
8866 }
8867 ~DeclaringSpecialMember() {
8868 if (!WasAlreadyBeingDeclared)
8869 S.SpecialMembersBeingDeclared.erase(D);
8870 }
8871
8872 /// \brief Are we already trying to declare this special member?
8873 bool isAlreadyBeingDeclared() const {
8874 return WasAlreadyBeingDeclared;
8875 }
8876};
8877}
8878
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008879CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8880 CXXRecordDecl *ClassDecl) {
8881 // C++ [class.ctor]p5:
8882 // A default constructor for a class X is a constructor of class X
8883 // that can be called without an argument. If there is no
8884 // user-declared constructor for class X, a default constructor is
8885 // implicitly declared. An implicitly-declared default constructor
8886 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008887 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008888 "Should not build implicit default constructor!");
8889
Richard Smith8bf22e52012-11-29 01:34:07 +00008890 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8891 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008892 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008893
Richard Smithb5800092012-06-10 05:43:50 +00008894 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8895 CXXDefaultConstructor,
8896 false);
8897
Douglas Gregor6d880b12010-07-01 22:31:05 +00008898 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008899 CanQualType ClassType
8900 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008901 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008902 DeclarationName Name
8903 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008904 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008905 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008906 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8907 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8908 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008909 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008910 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008911
8912 if (getLangOpts().CUDA) {
8913 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8914 DefaultCon,
8915 /* ConstRHS */ false,
8916 /* Diagnose */ false);
8917 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00008918
8919 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008920 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008921 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008922
Richard Smith6b02d462012-12-08 08:32:28 +00008923 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8924 // constructors is easy to compute.
8925 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8926
8927 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008928 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008929
Douglas Gregor9672f922010-07-03 00:47:00 +00008930 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008931 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008932
Douglas Gregor0be31a22010-07-02 17:43:08 +00008933 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008934 PushOnScopeChains(DefaultCon, S, false);
8935 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008936
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008937 return DefaultCon;
8938}
8939
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008940void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8941 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008942 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008943 !Constructor->doesThisDeclarationHaveABody() &&
8944 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008945 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008946
Anders Carlsson423f5d82010-04-23 16:04:08 +00008947 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008948 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008949
Eli Friedmaneaf34142012-10-18 20:14:08 +00008950 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008951 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008952 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008953 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008954 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008955 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008956 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008957 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008958 }
Douglas Gregor73193272010-09-20 16:48:21 +00008959
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00008960 // The exception specification is needed because we are defining the
8961 // function.
8962 ResolveExceptionSpec(CurrentLocation,
8963 Constructor->getType()->castAs<FunctionProtoType>());
8964
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008965 SourceLocation Loc = Constructor->getLocEnd().isValid()
8966 ? Constructor->getLocEnd()
8967 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008968 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008969
Eli Friedman276dd182013-09-05 00:02:25 +00008970 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008971 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008972
8973 if (ASTMutationListener *L = getASTMutationListener()) {
8974 L->CompletedImplicitDefinition(Constructor);
8975 }
Richard Trieuef64e942013-10-25 00:56:00 +00008976
8977 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008978}
8979
Richard Smith938f40b2011-06-11 17:19:42 +00008980void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008981 // Perform any delayed checks on exception specifications.
8982 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008983}
8984
Richard Smith185be182013-04-10 05:48:59 +00008985namespace {
8986/// Information on inheriting constructors to declare.
8987class InheritingConstructorInfo {
8988public:
8989 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8990 : SemaRef(SemaRef), Derived(Derived) {
8991 // Mark the constructors that we already have in the derived class.
8992 //
8993 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8994 // unless there is a user-declared constructor with the same signature in
8995 // the class where the using-declaration appears.
8996 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8997 }
8998
8999 void inheritAll(CXXRecordDecl *RD) {
9000 visitAll(RD, &InheritingConstructorInfo::inherit);
9001 }
9002
9003private:
9004 /// Information about an inheriting constructor.
9005 struct InheritingConstructor {
9006 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00009007 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00009008
9009 /// If \c true, a constructor with this signature is already declared
9010 /// in the derived class.
9011 bool DeclaredInDerived;
9012
9013 /// The constructor which is inherited.
9014 const CXXConstructorDecl *BaseCtor;
9015
9016 /// The derived constructor we declared.
9017 CXXConstructorDecl *DerivedCtor;
9018 };
9019
9020 /// Inheriting constructors with a given canonical type. There can be at
9021 /// most one such non-template constructor, and any number of templated
9022 /// constructors.
9023 struct InheritingConstructorsForType {
9024 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009025 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9026 Templates;
Richard Smith185be182013-04-10 05:48:59 +00009027
9028 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9029 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9030 TemplateParameterList *ParamList = FTD->getTemplateParameters();
9031 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9032 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9033 false, S.TPL_TemplateMatch))
9034 return Templates[I].second;
9035 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9036 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00009037 }
Richard Smith185be182013-04-10 05:48:59 +00009038
9039 return NonTemplate;
9040 }
9041 };
9042
9043 /// Get or create the inheriting constructor record for a constructor.
9044 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9045 QualType CtorType) {
9046 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9047 .getEntry(SemaRef, Ctor);
9048 }
9049
9050 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9051
9052 /// Process all constructors for a class.
9053 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009054 for (const auto *Ctor : RD->ctors())
9055 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00009056 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9057 I(RD->decls_begin()), E(RD->decls_end());
9058 I != E; ++I) {
9059 const FunctionDecl *FD = (*I)->getTemplatedDecl();
9060 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9061 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00009062 }
9063 }
Richard Smith185be182013-04-10 05:48:59 +00009064
9065 /// Note that a constructor (or constructor template) was declared in Derived.
9066 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9067 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9068 }
9069
9070 /// Inherit a single constructor.
9071 void inherit(const CXXConstructorDecl *Ctor) {
9072 const FunctionProtoType *CtorType =
9073 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00009074 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00009075 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9076
9077 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9078
9079 // Core issue (no number yet): the ellipsis is always discarded.
9080 if (EPI.Variadic) {
9081 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9082 SemaRef.Diag(Ctor->getLocation(),
9083 diag::note_using_decl_constructor_ellipsis);
9084 EPI.Variadic = false;
9085 }
9086
9087 // Declare a constructor for each number of parameters.
9088 //
9089 // C++11 [class.inhctor]p1:
9090 // The candidate set of inherited constructors from the class X named in
9091 // the using-declaration consists of [... modulo defects ...] for each
9092 // constructor or constructor template of X, the set of constructors or
9093 // constructor templates that results from omitting any ellipsis parameter
9094 // specification and successively omitting parameters with a default
9095 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00009096 unsigned MinParams = minParamsToInherit(Ctor);
9097 unsigned Params = Ctor->getNumParams();
9098 if (Params >= MinParams) {
9099 do
9100 declareCtor(UsingLoc, Ctor,
9101 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00009102 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00009103 while (Params > MinParams &&
9104 Ctor->getParamDecl(--Params)->hasDefaultArg());
9105 }
Richard Smith185be182013-04-10 05:48:59 +00009106 }
9107
9108 /// Find the using-declaration which specified that we should inherit the
9109 /// constructors of \p Base.
9110 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9111 // No fancy lookup required; just look for the base constructor name
9112 // directly within the derived class.
9113 ASTContext &Context = SemaRef.Context;
9114 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9115 Context.getCanonicalType(Context.getRecordType(Base)));
Richard Smithcf4bdde2015-02-21 02:45:19 +00009116 DeclContext::lookup_result Decls = Derived->lookup(Name);
Richard Smith185be182013-04-10 05:48:59 +00009117 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9118 }
9119
9120 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9121 // C++11 [class.inhctor]p3:
9122 // [F]or each constructor template in the candidate set of inherited
9123 // constructors, a constructor template is implicitly declared
9124 if (Ctor->getDescribedFunctionTemplate())
9125 return 0;
9126
9127 // For each non-template constructor in the candidate set of inherited
9128 // constructors other than a constructor having no parameters or a
9129 // copy/move constructor having a single parameter, a constructor is
9130 // implicitly declared [...]
9131 if (Ctor->getNumParams() == 0)
9132 return 1;
9133 if (Ctor->isCopyOrMoveConstructor())
9134 return 2;
9135
9136 // Per discussion on core reflector, never inherit a constructor which
9137 // would become a default, copy, or move constructor of Derived either.
9138 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9139 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9140 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9141 }
9142
9143 /// Declare a single inheriting constructor, inheriting the specified
9144 /// constructor, with the given type.
9145 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9146 QualType DerivedType) {
9147 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9148
9149 // C++11 [class.inhctor]p3:
9150 // ... a constructor is implicitly declared with the same constructor
9151 // characteristics unless there is a user-declared constructor with
9152 // the same signature in the class where the using-declaration appears
9153 if (Entry.DeclaredInDerived)
9154 return;
9155
9156 // C++11 [class.inhctor]p7:
9157 // If two using-declarations declare inheriting constructors with the
9158 // same signature, the program is ill-formed
9159 if (Entry.DerivedCtor) {
9160 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9161 // Only diagnose this once per constructor.
9162 if (Entry.DerivedCtor->isInvalidDecl())
9163 return;
9164 Entry.DerivedCtor->setInvalidDecl();
9165
9166 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9167 SemaRef.Diag(BaseCtor->getLocation(),
9168 diag::note_using_decl_constructor_conflict_current_ctor);
9169 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9170 diag::note_using_decl_constructor_conflict_previous_ctor);
9171 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9172 diag::note_using_decl_constructor_conflict_previous_using);
9173 } else {
9174 // Core issue (no number): if the same inheriting constructor is
9175 // produced by multiple base class constructors from the same base
9176 // class, the inheriting constructor is defined as deleted.
9177 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9178 }
9179
9180 return;
9181 }
9182
9183 ASTContext &Context = SemaRef.Context;
9184 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9185 Context.getCanonicalType(Context.getRecordType(Derived)));
9186 DeclarationNameInfo NameInfo(Name, UsingLoc);
9187
Craig Topperc3ec1492014-05-26 06:22:03 +00009188 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00009189 if (const FunctionTemplateDecl *FTD =
9190 BaseCtor->getDescribedFunctionTemplate()) {
9191 TemplateParams = FTD->getTemplateParameters();
9192 // We're reusing template parameters from a different DeclContext. This
9193 // is questionable at best, but works out because the template depth in
9194 // both places is guaranteed to be 0.
9195 // FIXME: Rebuild the template parameters in the new context, and
9196 // transform the function type to refer to them.
9197 }
9198
9199 // Build type source info pointing at the using-declaration. This is
9200 // required by template instantiation.
9201 TypeSourceInfo *TInfo =
9202 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9203 FunctionProtoTypeLoc ProtoLoc =
9204 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9205
9206 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9207 Context, Derived, UsingLoc, NameInfo, DerivedType,
9208 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9209 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9210
9211 // Build an unevaluated exception specification for this constructor.
9212 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9213 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009214 EPI.ExceptionSpec.Type = EST_Unevaluated;
9215 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00009216 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00009217 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00009218
9219 // Build the parameter declarations.
9220 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00009221 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00009222 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00009223 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00009224 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009225 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9226 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00009227 PD->setScopeInfo(0, I);
9228 PD->setImplicit();
9229 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009230 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00009231 }
9232
9233 // Set up the new constructor.
9234 DerivedCtor->setAccess(BaseCtor->getAccess());
9235 DerivedCtor->setParams(ParamDecls);
9236 DerivedCtor->setInheritedConstructor(BaseCtor);
9237 if (BaseCtor->isDeleted())
9238 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9239
9240 // If this is a constructor template, build the template declaration.
9241 if (TemplateParams) {
9242 FunctionTemplateDecl *DerivedTemplate =
9243 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9244 TemplateParams, DerivedCtor);
9245 DerivedTemplate->setAccess(BaseCtor->getAccess());
9246 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9247 Derived->addDecl(DerivedTemplate);
9248 } else {
9249 Derived->addDecl(DerivedCtor);
9250 }
9251
9252 Entry.BaseCtor = BaseCtor;
9253 Entry.DerivedCtor = DerivedCtor;
9254 }
9255
9256 Sema &SemaRef;
9257 CXXRecordDecl *Derived;
9258 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9259 MapType Map;
9260};
9261}
9262
9263void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9264 // Defer declaring the inheriting constructors until the class is
9265 // instantiated.
9266 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00009267 return;
9268
Richard Smith185be182013-04-10 05:48:59 +00009269 // Find base classes from which we might inherit constructors.
9270 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00009271 for (const auto &BaseIt : ClassDecl->bases())
9272 if (BaseIt.getInheritConstructors())
9273 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00009274
Richard Smith185be182013-04-10 05:48:59 +00009275 // Go no further if we're not inheriting any constructors.
9276 if (InheritedBases.empty())
9277 return;
Sebastian Redl08905022011-02-05 19:23:19 +00009278
Richard Smith185be182013-04-10 05:48:59 +00009279 // Declare the inherited constructors.
9280 InheritingConstructorInfo ICI(*this, ClassDecl);
9281 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9282 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00009283}
9284
Richard Smithc2bc61b2013-03-18 21:12:30 +00009285void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9286 CXXConstructorDecl *Constructor) {
9287 CXXRecordDecl *ClassDecl = Constructor->getParent();
9288 assert(Constructor->getInheritedConstructor() &&
9289 !Constructor->doesThisDeclarationHaveABody() &&
9290 !Constructor->isDeleted());
9291
9292 SynthesizedFunctionScope Scope(*this, Constructor);
9293 DiagnosticErrorTrap Trap(Diags);
9294 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9295 Trap.hasErrorOccurred()) {
9296 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9297 << Context.getTagDeclType(ClassDecl);
9298 Constructor->setInvalidDecl();
9299 return;
9300 }
9301
9302 SourceLocation Loc = Constructor->getLocation();
9303 Constructor->setBody(new (Context) CompoundStmt(Loc));
9304
Eli Friedman276dd182013-09-05 00:02:25 +00009305 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00009306 MarkVTableUsed(CurrentLocation, ClassDecl);
9307
9308 if (ASTMutationListener *L = getASTMutationListener()) {
9309 L->CompletedImplicitDefinition(Constructor);
9310 }
9311}
9312
9313
Alexis Huntf91729462011-05-12 22:46:25 +00009314Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009315Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9316 CXXRecordDecl *ClassDecl = MD->getParent();
9317
Douglas Gregorf1203042010-07-01 19:09:28 +00009318 // C++ [except.spec]p14:
9319 // An implicitly declared special member function (Clause 12) shall have
9320 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00009321 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009322 if (ClassDecl->isInvalidDecl())
9323 return ExceptSpec;
9324
Douglas Gregorf1203042010-07-01 19:09:28 +00009325 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009326 for (const auto &B : ClassDecl->bases()) {
9327 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00009328 continue;
9329
Aaron Ballman574705e2014-03-13 15:41:46 +00009330 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9331 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009332 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009333 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009334
Douglas Gregorf1203042010-07-01 19:09:28 +00009335 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009336 for (const auto &B : ClassDecl->vbases()) {
9337 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9338 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009339 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009340 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009341
Douglas Gregorf1203042010-07-01 19:09:28 +00009342 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009343 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00009344 if (const RecordType *RecordTy
9345 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00009346 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009347 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009348 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009349
Alexis Huntf91729462011-05-12 22:46:25 +00009350 return ExceptSpec;
9351}
9352
9353CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9354 // C++ [class.dtor]p2:
9355 // If a class has no user-declared destructor, a destructor is
9356 // declared implicitly. An implicitly-declared destructor is an
9357 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00009358 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00009359
Richard Smith8bf22e52012-11-29 01:34:07 +00009360 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9361 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009362 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009363
Douglas Gregor7454c562010-07-02 20:37:36 +00009364 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00009365 CanQualType ClassType
9366 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009367 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00009368 DeclarationName Name
9369 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009370 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00009371 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00009372 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009373 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009374 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00009375 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00009376 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009377
9378 if (getLangOpts().CUDA) {
9379 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9380 Destructor,
9381 /* ConstRHS */ false,
9382 /* Diagnose */ false);
9383 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009384
9385 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009386 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009387 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009388
Richard Smith6b02d462012-12-08 08:32:28 +00009389 AddOverriddenMethods(ClassDecl, Destructor);
9390
9391 // We don't need to use SpecialMemberIsTrivial here; triviality for
9392 // destructors is easy to compute.
9393 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9394
9395 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009396 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00009397
Douglas Gregor7454c562010-07-02 20:37:36 +00009398 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009399 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009400
Douglas Gregor7454c562010-07-02 20:37:36 +00009401 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00009402 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00009403 PushOnScopeChains(Destructor, S, false);
9404 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009405
Douglas Gregorf1203042010-07-01 19:09:28 +00009406 return Destructor;
9407}
9408
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009409void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009410 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009411 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009412 !Destructor->doesThisDeclarationHaveABody() &&
9413 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009414 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009415 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009416 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009417
Douglas Gregor54818f02010-05-12 16:39:35 +00009418 if (Destructor->isInvalidDecl())
9419 return;
9420
Eli Friedmaneaf34142012-10-18 20:14:08 +00009421 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009422
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009423 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009424 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9425 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009426
Douglas Gregor54818f02010-05-12 16:39:35 +00009427 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009428 Diag(CurrentLocation, diag::note_member_synthesized_at)
9429 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9430
9431 Destructor->setInvalidDecl();
9432 return;
9433 }
9434
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009435 // The exception specification is needed because we are defining the
9436 // function.
9437 ResolveExceptionSpec(CurrentLocation,
9438 Destructor->getType()->castAs<FunctionProtoType>());
9439
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009440 SourceLocation Loc = Destructor->getLocEnd().isValid()
9441 ? Destructor->getLocEnd()
9442 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009443 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009444 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009445 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009446
9447 if (ASTMutationListener *L = getASTMutationListener()) {
9448 L->CompletedImplicitDefinition(Destructor);
9449 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009450}
9451
Richard Smith84973e52012-04-21 18:42:51 +00009452/// \brief Perform any semantic analysis which needs to be delayed until all
9453/// pending class member declarations have been parsed.
9454void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009455 // If the context is an invalid C++ class, just suppress these checks.
9456 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9457 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009458 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +00009459 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009460 return;
9461 }
9462 }
Richard Smith84973e52012-04-21 18:42:51 +00009463}
9464
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009465static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9466 // Don't do anything for template patterns.
9467 if (Class->getDescribedClassTemplate())
9468 return;
9469
9470 for (Decl *Member : Class->decls()) {
9471 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9472 if (!CD) {
9473 // Recurse on nested classes.
9474 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9475 getDefaultArgExprsForConstructors(S, NestedRD);
9476 continue;
9477 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9478 continue;
9479 }
9480
9481 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
9482 // Skip any default arguments that we've already instantiated.
9483 if (S.Context.getDefaultArgExprForConstructor(CD, I))
9484 continue;
9485
9486 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9487 CD->getParamDecl(I)).get();
9488 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9489 }
9490 }
9491}
9492
Reid Kleckner93f661a2015-03-17 21:51:43 +00009493void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009494 auto *RD = dyn_cast<CXXRecordDecl>(D);
9495
9496 // Default constructors that are annotated with __declspec(dllexport) which
9497 // have default arguments or don't use the standard calling convention are
9498 // wrapped with a thunk called the default constructor closure.
9499 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9500 getDefaultArgExprsForConstructors(*this, RD);
9501}
9502
Richard Smithd3b5c9082012-07-27 04:22:15 +00009503void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9504 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009505 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009506 "adjusting dtor exception specs was introduced in c++11");
9507
Sebastian Redl623ea822011-05-19 05:13:44 +00009508 // C++11 [class.dtor]p3:
9509 // A declaration of a destructor that does not have an exception-
9510 // specification is implicitly considered to have the same exception-
9511 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009512 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009513 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009514 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009515 return;
9516
Chandler Carruth9a797572011-09-20 04:55:26 +00009517 // Replace the destructor's type, building off the existing one. Fortunately,
9518 // the only thing of interest in the destructor type is its extended info.
9519 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009520 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009521 EPI.ExceptionSpec.Type = EST_Unevaluated;
9522 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009523 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009524
Sebastian Redl623ea822011-05-19 05:13:44 +00009525 // FIXME: If the destructor has a body that could throw, and the newly created
9526 // spec doesn't allow exceptions, we should emit a warning, because this
9527 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009528 // However, we don't have a body or an exception specification yet, so it
9529 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009530}
9531
Pavel Labath58934982013-08-30 08:52:28 +00009532namespace {
9533/// \brief An abstract base class for all helper classes used in building the
9534// copy/move operators. These classes serve as factory functions and help us
9535// avoid using the same Expr* in the AST twice.
9536class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +00009537 ExprBuilder(const ExprBuilder&) = delete;
9538 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +00009539
9540protected:
9541 static Expr *assertNotNull(Expr *E) {
9542 assert(E && "Expression construction must not fail.");
9543 return E;
9544 }
9545
9546public:
9547 ExprBuilder() {}
9548 virtual ~ExprBuilder() {}
9549
9550 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9551};
9552
9553class RefBuilder: public ExprBuilder {
9554 VarDecl *Var;
9555 QualType VarType;
9556
9557public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009558 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009559 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009560 }
9561
9562 RefBuilder(VarDecl *Var, QualType VarType)
9563 : Var(Var), VarType(VarType) {}
9564};
9565
9566class ThisBuilder: public ExprBuilder {
9567public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009568 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009569 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009570 }
9571};
9572
9573class CastBuilder: public ExprBuilder {
9574 const ExprBuilder &Builder;
9575 QualType Type;
9576 ExprValueKind Kind;
9577 const CXXCastPath &Path;
9578
9579public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009580 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009581 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9582 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009583 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009584 }
9585
9586 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9587 const CXXCastPath &Path)
9588 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9589};
9590
9591class DerefBuilder: public ExprBuilder {
9592 const ExprBuilder &Builder;
9593
9594public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009595 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009596 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009597 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009598 }
9599
9600 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9601};
9602
9603class MemberBuilder: public ExprBuilder {
9604 const ExprBuilder &Builder;
9605 QualType Type;
9606 CXXScopeSpec SS;
9607 bool IsArrow;
9608 LookupResult &MemberLookup;
9609
9610public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009611 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009612 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009613 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009614 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009615 }
9616
9617 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9618 LookupResult &MemberLookup)
9619 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9620 MemberLookup(MemberLookup) {}
9621};
9622
9623class MoveCastBuilder: public ExprBuilder {
9624 const ExprBuilder &Builder;
9625
9626public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009627 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009628 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9629 }
9630
9631 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9632};
9633
9634class LvalueConvBuilder: public ExprBuilder {
9635 const ExprBuilder &Builder;
9636
9637public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009638 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009639 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009640 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009641 }
9642
9643 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9644};
9645
9646class SubscriptBuilder: public ExprBuilder {
9647 const ExprBuilder &Base;
9648 const ExprBuilder &Index;
9649
9650public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009651 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009652 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009653 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009654 }
9655
9656 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9657 : Base(Base), Index(Index) {}
9658};
9659
9660} // end anonymous namespace
9661
Richard Smith41ae3282012-11-14 00:50:40 +00009662/// When generating a defaulted copy or move assignment operator, if a field
9663/// should be copied with __builtin_memcpy rather than via explicit assignments,
9664/// do so. This optimization only applies for arrays of scalars, and for arrays
9665/// of class type where the selected copy/move-assignment operator is trivial.
9666static StmtResult
9667buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009668 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009669 // Compute the size of the memory buffer to be copied.
9670 QualType SizeType = S.Context.getSizeType();
9671 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9672 S.Context.getTypeSizeInChars(T).getQuantity());
9673
9674 // Take the address of the field references for "from" and "to". We
9675 // directly construct UnaryOperators here because semantic analysis
9676 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009677 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009678 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9679 S.Context.getPointerType(From->getType()),
9680 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009681 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009682 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9683 S.Context.getPointerType(To->getType()),
9684 VK_RValue, OK_Ordinary, Loc);
9685
9686 const Type *E = T->getBaseElementTypeUnsafe();
9687 bool NeedsCollectableMemCpy =
9688 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9689
9690 // Create a reference to the __builtin_objc_memmove_collectable function
9691 StringRef MemCpyName = NeedsCollectableMemCpy ?
9692 "__builtin_objc_memmove_collectable" :
9693 "__builtin_memcpy";
9694 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9695 Sema::LookupOrdinaryName);
9696 S.LookupName(R, S.TUScope, true);
9697
9698 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9699 if (!MemCpy)
9700 // Something went horribly wrong earlier, and we will have complained
9701 // about it.
9702 return StmtError();
9703
9704 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009705 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009706 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9707
9708 Expr *CallArgs[] = {
9709 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9710 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009711 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009712 Loc, CallArgs, Loc);
9713
9714 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009715 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009716}
9717
Sebastian Redl22653ba2011-08-30 19:58:05 +00009718/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009719/// \c To.
9720///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009721/// This routine is used to copy/move the members of a class with an
9722/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009723/// copied are arrays, this routine builds for loops to copy them.
9724///
9725/// \param S The Sema object used for type-checking.
9726///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009727/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009728///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009729/// \param T The type of the expressions being copied/moved. Both expressions
9730/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009731///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009732/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009733///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009734/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009735///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009736/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009737/// Otherwise, it's a non-static member subobject.
9738///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009739/// \param Copying Whether we're copying or moving.
9740///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009741/// \param Depth Internal parameter recording the depth of the recursion.
9742///
Richard Smith41ae3282012-11-14 00:50:40 +00009743/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9744/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009745static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009746buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009747 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009748 bool CopyingBaseSubobject, bool Copying,
9749 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009750 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009751 // Each subobject is assigned in the manner appropriate to its type:
9752 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009753 // - if the subobject is of class type, as if by a call to operator= with
9754 // the subobject as the object expression and the corresponding
9755 // subobject of x as a single function argument (as if by explicit
9756 // qualification; that is, ignoring any possible virtual overriding
9757 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009758 //
9759 // C++03 [class.copy]p13:
9760 // - if the subobject is of class type, the copy assignment operator for
9761 // the class is used (as if by explicit qualification; that is,
9762 // ignoring any possible virtual overriding functions in more derived
9763 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009764 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9765 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009766
Douglas Gregorb139cd52010-05-01 20:49:11 +00009767 // Look for operator=.
9768 DeclarationName Name
9769 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9770 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9771 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009772
Richard Smith52c0b582012-11-13 00:54:12 +00009773 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9774 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009775 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009776 LookupResult::Filter F = OpLookup.makeFilter();
9777 while (F.hasNext()) {
9778 NamedDecl *D = F.next();
9779 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9780 if (Method->isCopyAssignmentOperator() ||
9781 (!Copying && Method->isMoveAssignmentOperator()))
9782 continue;
9783
9784 F.erase();
9785 }
9786 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009787 }
Richard Smith52c0b582012-11-13 00:54:12 +00009788
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009789 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009790 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009791 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009792 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009793 // ambiguities), we need to cast "this" to that subobject type; to
9794 // ensure that we don't go through the virtual call mechanism, we need
9795 // to qualify the operator= name with the base class (see below). However,
9796 // this means that if the base class has a protected copy assignment
9797 // operator, the protected member access check will fail. So, we
9798 // rewrite "protected" access to "public" access in this case, since we
9799 // know by construction that we're calling from a derived class.
9800 if (CopyingBaseSubobject) {
9801 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9802 L != LEnd; ++L) {
9803 if (L.getAccess() == AS_protected)
9804 L.setAccess(AS_public);
9805 }
9806 }
Richard Smith52c0b582012-11-13 00:54:12 +00009807
Douglas Gregorb139cd52010-05-01 20:49:11 +00009808 // Create the nested-name-specifier that will be used to qualify the
9809 // reference to operator=; this is required to suppress the virtual
9810 // call mechanism.
9811 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009812 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009813 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009814 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009815 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009816 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009817
Douglas Gregorb139cd52010-05-01 20:49:11 +00009818 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009819 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009820 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9821 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009822 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009823 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009824 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009825 /*SuppressQualifierCheck=*/true);
9826 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009827 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009828
Douglas Gregorb139cd52010-05-01 20:49:11 +00009829 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009830
Pavel Labath58934982013-08-30 08:52:28 +00009831 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009832 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009833 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009834 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009835 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009836 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009837
Richard Smith41ae3282012-11-14 00:50:40 +00009838 // If we built a call to a trivial 'operator=' while copying an array,
9839 // bail out. We'll replace the whole shebang with a memcpy.
9840 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9841 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009842 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009843
Richard Smith52c0b582012-11-13 00:54:12 +00009844 // Convert to an expression-statement, and clean up any produced
9845 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009846 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009847 }
John McCallab8c2732010-03-16 06:11:48 +00009848
Richard Smith52c0b582012-11-13 00:54:12 +00009849 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009850 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009851 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009852 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009853 ExprResult Assignment = S.CreateBuiltinBinOp(
9854 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009855 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009856 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009857 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009858 }
Richard Smith52c0b582012-11-13 00:54:12 +00009859
9860 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009861 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009862
Douglas Gregorb139cd52010-05-01 20:49:11 +00009863 // Construct a loop over the array bounds, e.g.,
9864 //
9865 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9866 //
9867 // that will copy each of the array elements.
9868 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009869
Douglas Gregorb139cd52010-05-01 20:49:11 +00009870 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009871 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009872 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009873 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009874 llvm::raw_svector_ostream OS(Str);
9875 OS << "__i" << Depth;
9876 IterationVarName = &S.Context.Idents.get(OS.str());
9877 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009878 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009879 IterationVarName, SizeType,
9880 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009881 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009882
Douglas Gregorb139cd52010-05-01 20:49:11 +00009883 // Initialize the iteration variable to zero.
9884 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009885 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009886
Pavel Labath58934982013-08-30 08:52:28 +00009887 // Creates a reference to the iteration variable.
9888 RefBuilder IterationVarRef(IterationVar, SizeType);
9889 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009890
Douglas Gregorb139cd52010-05-01 20:49:11 +00009891 // Create the DeclStmt that holds the iteration variable.
9892 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009893
Douglas Gregorb139cd52010-05-01 20:49:11 +00009894 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009895 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9896 MoveCastBuilder FromIndexMove(FromIndexCopy);
9897 const ExprBuilder *FromIndex;
9898 if (Copying)
9899 FromIndex = &FromIndexCopy;
9900 else
9901 FromIndex = &FromIndexMove;
9902
9903 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009904
9905 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009906 StmtResult Copy =
9907 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009908 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009909 Copying, Depth + 1);
9910 // Bail out if copying fails or if we determined that we should use memcpy.
9911 if (Copy.isInvalid() || !Copy.get())
9912 return Copy;
9913
9914 // Create the comparison against the array bound.
9915 llvm::APInt Upper
9916 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9917 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009918 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009919 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9920 BO_NE, S.Context.BoolTy,
9921 VK_RValue, OK_Ordinary, Loc, false);
9922
9923 // Create the pre-increment of the iteration variable.
9924 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009925 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9926 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009927
Douglas Gregorb139cd52010-05-01 20:49:11 +00009928 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009929 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009930 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009931 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009932 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009933}
9934
Richard Smith41ae3282012-11-14 00:50:40 +00009935static StmtResult
9936buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009937 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009938 bool CopyingBaseSubobject, bool Copying) {
9939 // Maybe we should use a memcpy?
9940 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9941 T.isTriviallyCopyableType(S.Context))
9942 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9943
9944 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9945 CopyingBaseSubobject,
9946 Copying, 0));
9947
9948 // If we ended up picking a trivial assignment operator for an array of a
9949 // non-trivially-copyable class type, just emit a memcpy.
9950 if (!Result.isInvalid() && !Result.get())
9951 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9952
9953 return Result;
9954}
9955
Richard Smithd3b5c9082012-07-27 04:22:15 +00009956Sema::ImplicitExceptionSpecification
9957Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9958 CXXRecordDecl *ClassDecl = MD->getParent();
9959
9960 ImplicitExceptionSpecification ExceptSpec(*this);
9961 if (ClassDecl->isInvalidDecl())
9962 return ExceptSpec;
9963
9964 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009965 assert(T->getNumParams() == 1 && "not a copy assignment op");
9966 unsigned ArgQuals =
9967 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009968
Douglas Gregor68e11362010-07-01 17:48:08 +00009969 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009970 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009971 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009972
9973 // It is unspecified whether or not an implicit copy assignment operator
9974 // attempts to deduplicate calls to assignment operators of virtual bases are
9975 // made. As such, this exception specification is effectively unspecified.
9976 // Based on a similar decision made for constness in C++0x, we're erring on
9977 // the side of assuming such calls to be made regardless of whether they
9978 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009979 for (const auto &Base : ClassDecl->bases()) {
9980 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009981 continue;
9982
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009983 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009984 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009985 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9986 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009987 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009988 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009989
Aaron Ballman445a9392014-03-13 16:15:17 +00009990 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009991 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009992 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009993 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9994 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009995 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009996 }
9997
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009998 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009999 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +000010000 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10001 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +000010002 LookupCopyingAssignment(FieldClassDecl,
10003 ArgQuals | FieldType.getCVRQualifiers(),
10004 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010005 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010006 }
Douglas Gregor68e11362010-07-01 17:48:08 +000010007 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010008
Richard Smithd3b5c9082012-07-27 04:22:15 +000010009 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +000010010}
10011
10012CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10013 // Note: The following rules are largely analoguous to the copy
10014 // constructor rules. Note that virtual bases are not taken into account
10015 // for determining the argument type of the operator. Note also that
10016 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000010017 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000010018
Richard Smith8bf22e52012-11-29 01:34:07 +000010019 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10020 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010021 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010022
Alexis Hunt119f3652011-05-14 05:23:20 +000010023 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10024 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000010025 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10026 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000010027 ArgType = ArgType.withConst();
10028 ArgType = Context.getLValueReferenceType(ArgType);
10029
Richard Smith99005e62013-05-07 03:19:20 +000010030 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10031 CXXCopyAssignment,
10032 Const);
10033
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010034 // An implicitly-declared copy assignment operator is an inline public
10035 // member of its class.
10036 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010037 SourceLocation ClassLoc = ClassDecl->getLocation();
10038 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010039 CXXMethodDecl *CopyAssignment =
10040 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010041 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10042 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010043 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000010044 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010045 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010046
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010047 if (getLangOpts().CUDA) {
10048 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10049 CopyAssignment,
10050 /* ConstRHS */ Const,
10051 /* Diagnose */ false);
10052 }
10053
Richard Smithd3b5c9082012-07-27 04:22:15 +000010054 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010055 FunctionProtoType::ExtProtoInfo EPI =
10056 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010057 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010058
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010059 // Add the parameter to the operator.
10060 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010061 ClassLoc, ClassLoc,
10062 /*Id=*/nullptr, ArgType,
10063 /*TInfo=*/nullptr, SC_None,
10064 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010065 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000010066
Richard Smith6b02d462012-12-08 08:32:28 +000010067 AddOverriddenMethods(ClassDecl, CopyAssignment);
10068
10069 CopyAssignment->setTrivial(
10070 ClassDecl->needsOverloadResolutionForCopyAssignment()
10071 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10072 : ClassDecl->hasTrivialCopyAssignment());
10073
Richard Smith852265f2012-03-30 20:53:28 +000010074 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +000010075 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010076
Richard Smith6b02d462012-12-08 08:32:28 +000010077 // Note that we have added this copy-assignment operator.
10078 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10079
10080 if (Scope *S = getScopeForContext(ClassDecl))
10081 PushOnScopeChains(CopyAssignment, S, false);
10082 ClassDecl->addDecl(CopyAssignment);
10083
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010084 return CopyAssignment;
10085}
10086
Richard Smithd577fbb2013-06-13 03:23:42 +000010087/// Diagnose an implicit copy operation for a class which is odr-used, but
10088/// which is deprecated because the class has a user-declared copy constructor,
10089/// copy assignment operator, or destructor.
10090static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10091 SourceLocation UseLoc) {
10092 assert(CopyOp->isImplicit());
10093
10094 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000010095 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000010096
10097 // In Microsoft mode, assignment operations don't affect constructors and
10098 // vice versa.
10099 if (RD->hasUserDeclaredDestructor()) {
10100 UserDeclaredOperation = RD->getDestructor();
10101 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10102 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010103 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010104 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010105 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010106 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010107 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010108 break;
10109 }
10110 }
10111 assert(UserDeclaredOperation);
10112 } else if (isa<CXXConstructorDecl>(CopyOp) &&
10113 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010114 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010115 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000010116 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010117 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000010118 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010119 break;
10120 }
10121 }
10122 assert(UserDeclaredOperation);
10123 }
10124
10125 if (UserDeclaredOperation) {
10126 S.Diag(UserDeclaredOperation->getLocation(),
10127 diag::warn_deprecated_copy_operation)
10128 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10129 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10130 S.Diag(UseLoc, diag::note_member_synthesized_at)
10131 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10132 : Sema::CXXCopyAssignment)
10133 << RD;
10134 }
10135}
10136
Douglas Gregorb139cd52010-05-01 20:49:11 +000010137void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10138 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000010139 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010140 CopyAssignOperator->isOverloadedOperator() &&
10141 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010142 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10143 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010144 "DefineImplicitCopyAssignment called for wrong function");
10145
10146 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10147
10148 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10149 CopyAssignOperator->setInvalidDecl();
10150 return;
10151 }
Richard Smithd577fbb2013-06-13 03:23:42 +000010152
10153 // C++11 [class.copy]p18:
10154 // The [definition of an implicitly declared copy assignment operator] is
10155 // deprecated if the class has a user-declared copy constructor or a
10156 // user-declared destructor.
10157 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10158 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10159
Eli Friedman276dd182013-09-05 00:02:25 +000010160 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010161
Eli Friedmaneaf34142012-10-18 20:14:08 +000010162 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010163 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010164
10165 // C++0x [class.copy]p30:
10166 // The implicitly-defined or explicitly-defaulted copy assignment operator
10167 // for a non-union class X performs memberwise copy assignment of its
10168 // subobjects. The direct base classes of X are assigned first, in the
10169 // order of their declaration in the base-specifier-list, and then the
10170 // immediate non-static data members of X are assigned, in the order in
10171 // which they were declared in the class definition.
10172
10173 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010174 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010175
10176 // The parameter for the "other" object, which we are copying from.
10177 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10178 Qualifiers OtherQuals = Other->getType().getQualifiers();
10179 QualType OtherRefType = Other->getType();
10180 if (const LValueReferenceType *OtherRef
10181 = OtherRefType->getAs<LValueReferenceType>()) {
10182 OtherRefType = OtherRef->getPointeeType();
10183 OtherQuals = OtherRefType.getQualifiers();
10184 }
10185
10186 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010187 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10188 ? CopyAssignOperator->getLocEnd()
10189 : CopyAssignOperator->getLocation();
10190
Pavel Labath58934982013-08-30 08:52:28 +000010191 // Builds a DeclRefExpr for the "other" object.
10192 RefBuilder OtherRef(Other, OtherRefType);
10193
10194 // Builds the "this" pointer.
10195 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010196
10197 // Assign base classes.
10198 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010199 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010200 // Form the assignment:
10201 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010202 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000010203 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010204 Invalid = true;
10205 continue;
10206 }
10207
John McCallcf142162010-08-07 06:22:56 +000010208 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010209 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000010210
Douglas Gregorb139cd52010-05-01 20:49:11 +000010211 // Construct the "from" expression, which is an implicit cast to the
10212 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010213 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10214 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010215
10216 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010217 DerefBuilder DerefThis(This);
10218 CastBuilder To(DerefThis,
10219 Context.getCVRQualifiedType(
10220 BaseType, CopyAssignOperator->getTypeQualifiers()),
10221 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010222
10223 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000010224 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010225 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010226 /*CopyingBaseSubobject=*/true,
10227 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010228 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010229 Diag(CurrentLocation, diag::note_member_synthesized_at)
10230 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10231 CopyAssignOperator->setInvalidDecl();
10232 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010233 }
10234
10235 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010236 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010237 }
10238
Douglas Gregorb139cd52010-05-01 20:49:11 +000010239 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010240 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000010241 // FIXME: We should form some kind of AST representation for the implied
10242 // memcpy in a union copy operation.
10243 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000010244 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010245
10246 if (Field->isInvalidDecl()) {
10247 Invalid = true;
10248 continue;
10249 }
10250
Douglas Gregorb139cd52010-05-01 20:49:11 +000010251 // Check for members of reference type; we can't copy those.
10252 if (Field->getType()->isReferenceType()) {
10253 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10254 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10255 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010256 Diag(CurrentLocation, diag::note_member_synthesized_at)
10257 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010258 Invalid = true;
10259 continue;
10260 }
10261
10262 // Check for members of const-qualified, non-class type.
10263 QualType BaseType = Context.getBaseElementType(Field->getType());
10264 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10265 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10266 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10267 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010268 Diag(CurrentLocation, diag::note_member_synthesized_at)
10269 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010270 Invalid = true;
10271 continue;
10272 }
John McCall1b1a1db2011-06-17 00:18:42 +000010273
10274 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010275 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10276 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010277
10278 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010279 if (FieldType->isIncompleteArrayType()) {
10280 assert(ClassDecl->hasFlexibleArrayMember() &&
10281 "Incomplete array type is not valid");
10282 continue;
10283 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010284
10285 // Build references to the field in the object we're copying from and to.
10286 CXXScopeSpec SS; // Intentionally empty
10287 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10288 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010289 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010290 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010291
10292 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10293
10294 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010295
Douglas Gregorb139cd52010-05-01 20:49:11 +000010296 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010297 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010298 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010299 /*CopyingBaseSubobject=*/false,
10300 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010301 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010302 Diag(CurrentLocation, diag::note_member_synthesized_at)
10303 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10304 CopyAssignOperator->setInvalidDecl();
10305 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010306 }
10307
10308 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010309 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010310 }
10311
10312 if (!Invalid) {
10313 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010314 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010315
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010316 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010317 if (Return.isInvalid())
10318 Invalid = true;
10319 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010320 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000010321
10322 if (Trap.hasErrorOccurred()) {
10323 Diag(CurrentLocation, diag::note_member_synthesized_at)
10324 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10325 Invalid = true;
10326 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010327 }
10328 }
10329
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010330 // The exception specification is needed because we are defining the
10331 // function.
10332 ResolveExceptionSpec(CurrentLocation,
10333 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10334
Douglas Gregorb139cd52010-05-01 20:49:11 +000010335 if (Invalid) {
10336 CopyAssignOperator->setInvalidDecl();
10337 return;
10338 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010339
10340 StmtResult Body;
10341 {
10342 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010343 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010344 /*isStmtExpr=*/false);
10345 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10346 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010347 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000010348
10349 if (ASTMutationListener *L = getASTMutationListener()) {
10350 L->CompletedImplicitDefinition(CopyAssignOperator);
10351 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010352}
10353
Sebastian Redl22653ba2011-08-30 19:58:05 +000010354Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010355Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10356 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010357
Richard Smithd3b5c9082012-07-27 04:22:15 +000010358 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010359 if (ClassDecl->isInvalidDecl())
10360 return ExceptSpec;
10361
10362 // C++0x [except.spec]p14:
10363 // An implicitly declared special member function (Clause 12) shall have an
10364 // exception-specification. [...]
10365
10366 // It is unspecified whether or not an implicit move assignment operator
10367 // attempts to deduplicate calls to assignment operators of virtual bases are
10368 // made. As such, this exception specification is effectively unspecified.
10369 // Based on a similar decision made for constness in C++0x, we're erring on
10370 // the side of assuming such calls to be made regardless of whether they
10371 // actually happen.
10372 // Note that a move constructor is not implicitly declared when there are
10373 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000010374 for (const auto &Base : ClassDecl->bases()) {
10375 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000010376 continue;
10377
10378 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010379 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010380 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010381 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010382 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010383 }
10384
Aaron Ballman445a9392014-03-13 16:15:17 +000010385 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010386 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010387 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010388 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010389 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010390 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010391 }
10392
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010393 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010394 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010395 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010396 if (CXXMethodDecl *MoveAssign =
10397 LookupMovingAssignment(FieldClassDecl,
10398 FieldType.getCVRQualifiers(),
10399 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010400 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010401 }
10402 }
10403
10404 return ExceptSpec;
10405}
10406
10407CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010408 assert(ClassDecl->needsImplicitMoveAssignment());
10409
Richard Smith8bf22e52012-11-29 01:34:07 +000010410 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10411 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010412 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010413
Sebastian Redl22653ba2011-08-30 19:58:05 +000010414 // Note: The following rules are largely analoguous to the move
10415 // constructor rules.
10416
Sebastian Redl22653ba2011-08-30 19:58:05 +000010417 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10418 QualType RetType = Context.getLValueReferenceType(ArgType);
10419 ArgType = Context.getRValueReferenceType(ArgType);
10420
Richard Smith99005e62013-05-07 03:19:20 +000010421 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10422 CXXMoveAssignment,
10423 false);
10424
Sebastian Redl22653ba2011-08-30 19:58:05 +000010425 // An implicitly-declared move assignment operator is an inline public
10426 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010427 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10428 SourceLocation ClassLoc = ClassDecl->getLocation();
10429 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010430 CXXMethodDecl *MoveAssignment =
10431 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010432 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000010433 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010434 MoveAssignment->setAccess(AS_public);
10435 MoveAssignment->setDefaulted();
10436 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010437
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010438 if (getLangOpts().CUDA) {
10439 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10440 MoveAssignment,
10441 /* ConstRHS */ false,
10442 /* Diagnose */ false);
10443 }
10444
Richard Smithd3b5c9082012-07-27 04:22:15 +000010445 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010446 FunctionProtoType::ExtProtoInfo EPI =
10447 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010448 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010449
Sebastian Redl22653ba2011-08-30 19:58:05 +000010450 // Add the parameter to the operator.
10451 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010452 ClassLoc, ClassLoc,
10453 /*Id=*/nullptr, ArgType,
10454 /*TInfo=*/nullptr, SC_None,
10455 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010456 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010457
Richard Smith6b02d462012-12-08 08:32:28 +000010458 AddOverriddenMethods(ClassDecl, MoveAssignment);
10459
10460 MoveAssignment->setTrivial(
10461 ClassDecl->needsOverloadResolutionForMoveAssignment()
10462 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10463 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010464
Richard Smithd951a1d2012-02-18 02:02:13 +000010465 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010466 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10467 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010468 }
10469
Richard Smith6b02d462012-12-08 08:32:28 +000010470 // Note that we have added this copy-assignment operator.
10471 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10472
Sebastian Redl22653ba2011-08-30 19:58:05 +000010473 if (Scope *S = getScopeForContext(ClassDecl))
10474 PushOnScopeChains(MoveAssignment, S, false);
10475 ClassDecl->addDecl(MoveAssignment);
10476
Sebastian Redl22653ba2011-08-30 19:58:05 +000010477 return MoveAssignment;
10478}
10479
Richard Smithb2504bd2013-11-04 04:26:14 +000010480/// Check if we're implicitly defining a move assignment operator for a class
10481/// with virtual bases. Such a move assignment might move-assign the virtual
10482/// base multiple times.
10483static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10484 SourceLocation CurrentLocation) {
10485 assert(!Class->isDependentContext() && "should not define dependent move");
10486
10487 // Only a virtual base could get implicitly move-assigned multiple times.
10488 // Only a non-trivial move assignment can observe this. We only want to
10489 // diagnose if we implicitly define an assignment operator that assigns
10490 // two base classes, both of which move-assign the same virtual base.
10491 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10492 Class->getNumBases() < 2)
10493 return;
10494
10495 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10496 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10497 VBaseMap VBases;
10498
Aaron Ballman574705e2014-03-13 15:41:46 +000010499 for (auto &BI : Class->bases()) {
10500 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010501 while (!Worklist.empty()) {
10502 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10503 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10504
10505 // If the base has no non-trivial move assignment operators,
10506 // we don't care about moves from it.
10507 if (!Base->hasNonTrivialMoveAssignment())
10508 continue;
10509
10510 // If there's nothing virtual here, skip it.
10511 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10512 continue;
10513
10514 // If we're not actually going to call a move assignment for this base,
10515 // or the selected move assignment is trivial, skip it.
10516 Sema::SpecialMemberOverloadResult *SMOR =
10517 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10518 /*ConstArg*/false, /*VolatileArg*/false,
10519 /*RValueThis*/true, /*ConstThis*/false,
10520 /*VolatileThis*/false);
10521 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10522 !SMOR->getMethod()->isMoveAssignmentOperator())
10523 continue;
10524
10525 if (BaseSpec->isVirtual()) {
10526 // We're going to move-assign this virtual base, and its move
10527 // assignment operator is not trivial. If this can happen for
10528 // multiple distinct direct bases of Class, diagnose it. (If it
10529 // only happens in one base, we'll diagnose it when synthesizing
10530 // that base class's move assignment operator.)
10531 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010532 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010533 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010534 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010535 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10536 << Class << Base;
10537 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10538 << (Base->getCanonicalDecl() ==
10539 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10540 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010541 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010542 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010543 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10544 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010545
10546 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010547 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010548 }
10549 } else {
10550 // Only walk over bases that have defaulted move assignment operators.
10551 // We assume that any user-provided move assignment operator handles
10552 // the multiple-moves-of-vbase case itself somehow.
10553 if (!SMOR->getMethod()->isDefaulted())
10554 continue;
10555
10556 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010557 for (auto &BI : Base->bases())
10558 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010559 }
10560 }
10561 }
10562}
10563
Sebastian Redl22653ba2011-08-30 19:58:05 +000010564void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10565 CXXMethodDecl *MoveAssignOperator) {
10566 assert((MoveAssignOperator->isDefaulted() &&
10567 MoveAssignOperator->isOverloadedOperator() &&
10568 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010569 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10570 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010571 "DefineImplicitMoveAssignment called for wrong function");
10572
10573 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10574
10575 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10576 MoveAssignOperator->setInvalidDecl();
10577 return;
10578 }
10579
Eli Friedman276dd182013-09-05 00:02:25 +000010580 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010581
Eli Friedmaneaf34142012-10-18 20:14:08 +000010582 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010583 DiagnosticErrorTrap Trap(Diags);
10584
10585 // C++0x [class.copy]p28:
10586 // The implicitly-defined or move assignment operator for a non-union class
10587 // X performs memberwise move assignment of its subobjects. The direct base
10588 // classes of X are assigned first, in the order of their declaration in the
10589 // base-specifier-list, and then the immediate non-static data members of X
10590 // are assigned, in the order in which they were declared in the class
10591 // definition.
10592
Richard Smithb2504bd2013-11-04 04:26:14 +000010593 // Issue a warning if our implicit move assignment operator will move
10594 // from a virtual base more than once.
10595 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010596
Sebastian Redl22653ba2011-08-30 19:58:05 +000010597 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010598 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010599
10600 // The parameter for the "other" object, which we are move from.
10601 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10602 QualType OtherRefType = Other->getType()->
10603 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010604 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010605 "Bad argument type of defaulted move assignment");
10606
10607 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010608 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10609 ? MoveAssignOperator->getLocEnd()
10610 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010611
Pavel Labath58934982013-08-30 08:52:28 +000010612 // Builds a reference to the "other" object.
10613 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010614 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010615 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010616
Pavel Labath58934982013-08-30 08:52:28 +000010617 // Builds the "this" pointer.
10618 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010619
Sebastian Redl22653ba2011-08-30 19:58:05 +000010620 // Assign base classes.
10621 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010622 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010623 // C++11 [class.copy]p28:
10624 // It is unspecified whether subobjects representing virtual base classes
10625 // are assigned more than once by the implicitly-defined copy assignment
10626 // operator.
10627 // FIXME: Do not assign to a vbase that will be assigned by some other base
10628 // class. For a move-assignment, this can result in the vbase being moved
10629 // multiple times.
10630
Sebastian Redl22653ba2011-08-30 19:58:05 +000010631 // Form the assignment:
10632 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010633 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010634 if (!BaseType->isRecordType()) {
10635 Invalid = true;
10636 continue;
10637 }
10638
10639 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010640 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010641
10642 // Construct the "from" expression, which is an implicit cast to the
10643 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010644 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010645
10646 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010647 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010648
10649 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010650 CastBuilder To(DerefThis,
10651 Context.getCVRQualifiedType(
10652 BaseType, MoveAssignOperator->getTypeQualifiers()),
10653 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010654
10655 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010656 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010657 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010658 /*CopyingBaseSubobject=*/true,
10659 /*Copying=*/false);
10660 if (Move.isInvalid()) {
10661 Diag(CurrentLocation, diag::note_member_synthesized_at)
10662 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10663 MoveAssignOperator->setInvalidDecl();
10664 return;
10665 }
10666
10667 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010668 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010669 }
10670
Sebastian Redl22653ba2011-08-30 19:58:05 +000010671 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010672 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000010673 // FIXME: We should form some kind of AST representation for the implied
10674 // memcpy in a union copy operation.
10675 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000010676 continue;
10677
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010678 if (Field->isInvalidDecl()) {
10679 Invalid = true;
10680 continue;
10681 }
10682
Sebastian Redl22653ba2011-08-30 19:58:05 +000010683 // Check for members of reference type; we can't move those.
10684 if (Field->getType()->isReferenceType()) {
10685 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10686 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10687 Diag(Field->getLocation(), diag::note_declared_at);
10688 Diag(CurrentLocation, diag::note_member_synthesized_at)
10689 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10690 Invalid = true;
10691 continue;
10692 }
10693
10694 // Check for members of const-qualified, non-class type.
10695 QualType BaseType = Context.getBaseElementType(Field->getType());
10696 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10697 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10698 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10699 Diag(Field->getLocation(), diag::note_declared_at);
10700 Diag(CurrentLocation, diag::note_member_synthesized_at)
10701 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10702 Invalid = true;
10703 continue;
10704 }
10705
10706 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010707 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10708 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010709
10710 QualType FieldType = Field->getType().getNonReferenceType();
10711 if (FieldType->isIncompleteArrayType()) {
10712 assert(ClassDecl->hasFlexibleArrayMember() &&
10713 "Incomplete array type is not valid");
10714 continue;
10715 }
10716
10717 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010718 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10719 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010720 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010721 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010722 MemberBuilder From(MoveOther, OtherRefType,
10723 /*IsArrow=*/false, MemberLookup);
10724 MemberBuilder To(This, getCurrentThisType(),
10725 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010726
Pavel Labath58934982013-08-30 08:52:28 +000010727 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010728 "Member reference with rvalue base must be rvalue except for reference "
10729 "members, which aren't allowed for move assignment.");
10730
Sebastian Redl22653ba2011-08-30 19:58:05 +000010731 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010732 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010733 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010734 /*CopyingBaseSubobject=*/false,
10735 /*Copying=*/false);
10736 if (Move.isInvalid()) {
10737 Diag(CurrentLocation, diag::note_member_synthesized_at)
10738 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10739 MoveAssignOperator->setInvalidDecl();
10740 return;
10741 }
Richard Smith11d19592012-11-12 23:33:00 +000010742
Sebastian Redl22653ba2011-08-30 19:58:05 +000010743 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010744 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010745 }
10746
10747 if (!Invalid) {
10748 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010749 ExprResult ThisObj =
10750 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10751
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010752 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010753 if (Return.isInvalid())
10754 Invalid = true;
10755 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010756 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010757
10758 if (Trap.hasErrorOccurred()) {
10759 Diag(CurrentLocation, diag::note_member_synthesized_at)
10760 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10761 Invalid = true;
10762 }
10763 }
10764 }
10765
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010766 // The exception specification is needed because we are defining the
10767 // function.
10768 ResolveExceptionSpec(CurrentLocation,
10769 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10770
Sebastian Redl22653ba2011-08-30 19:58:05 +000010771 if (Invalid) {
10772 MoveAssignOperator->setInvalidDecl();
10773 return;
10774 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010775
10776 StmtResult Body;
10777 {
10778 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010779 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010780 /*isStmtExpr=*/false);
10781 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10782 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010783 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010784
10785 if (ASTMutationListener *L = getASTMutationListener()) {
10786 L->CompletedImplicitDefinition(MoveAssignOperator);
10787 }
10788}
10789
Richard Smithd3b5c9082012-07-27 04:22:15 +000010790Sema::ImplicitExceptionSpecification
10791Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10792 CXXRecordDecl *ClassDecl = MD->getParent();
10793
10794 ImplicitExceptionSpecification ExceptSpec(*this);
10795 if (ClassDecl->isInvalidDecl())
10796 return ExceptSpec;
10797
10798 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010799 assert(T->getNumParams() >= 1 && "not a copy ctor");
10800 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010801
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010802 // C++ [except.spec]p14:
10803 // An implicitly declared special member function (Clause 12) shall have an
10804 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010805 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010806 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010807 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010808 continue;
10809
Douglas Gregora6d69502010-07-02 23:41:54 +000010810 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010811 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010812 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010813 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010814 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010815 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010816 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010817 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010818 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010819 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010820 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010821 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010822 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010823 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010824 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010825 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10826 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010827 LookupCopyingConstructor(FieldClassDecl,
10828 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010829 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010830 }
10831 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010832
Richard Smithd3b5c9082012-07-27 04:22:15 +000010833 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010834}
10835
10836CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10837 CXXRecordDecl *ClassDecl) {
10838 // C++ [class.copy]p4:
10839 // If the class definition does not explicitly declare a copy
10840 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010841 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010842
Richard Smith8bf22e52012-11-29 01:34:07 +000010843 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10844 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010845 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010846
Alexis Hunt913820d2011-05-13 06:10:58 +000010847 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10848 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010849 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010850 if (Const)
10851 ArgType = ArgType.withConst();
10852 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010853
Richard Smithb5800092012-06-10 05:43:50 +000010854 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10855 CXXCopyConstructor,
10856 Const);
10857
Douglas Gregor54be3392010-07-01 17:57:27 +000010858 DeclarationName Name
10859 = Context.DeclarationNames.getCXXConstructorName(
10860 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010861 SourceLocation ClassLoc = ClassDecl->getLocation();
10862 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010863
10864 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010865 // member of its class.
10866 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010867 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010868 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010869 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010870 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010871 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010872
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010873 if (getLangOpts().CUDA) {
10874 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10875 CopyConstructor,
10876 /* ConstRHS */ Const,
10877 /* Diagnose */ false);
10878 }
10879
Richard Smithd3b5c9082012-07-27 04:22:15 +000010880 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010881 FunctionProtoType::ExtProtoInfo EPI =
10882 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010883 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010884 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010885
Douglas Gregor54be3392010-07-01 17:57:27 +000010886 // Add the parameter to the constructor.
10887 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010888 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010889 /*IdentifierInfo=*/nullptr,
10890 ArgType, /*TInfo=*/nullptr,
10891 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010892 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010893
Richard Smith6b02d462012-12-08 08:32:28 +000010894 CopyConstructor->setTrivial(
10895 ClassDecl->needsOverloadResolutionForCopyConstructor()
10896 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10897 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010898
Richard Smith852265f2012-03-30 20:53:28 +000010899 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010900 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010901
Richard Smith6b02d462012-12-08 08:32:28 +000010902 // Note that we have declared this constructor.
10903 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10904
10905 if (Scope *S = getScopeForContext(ClassDecl))
10906 PushOnScopeChains(CopyConstructor, S, false);
10907 ClassDecl->addDecl(CopyConstructor);
10908
Douglas Gregor54be3392010-07-01 17:57:27 +000010909 return CopyConstructor;
10910}
10911
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010912void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010913 CXXConstructorDecl *CopyConstructor) {
10914 assert((CopyConstructor->isDefaulted() &&
10915 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010916 !CopyConstructor->doesThisDeclarationHaveABody() &&
10917 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010918 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010919
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010920 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010921 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010922
Richard Smithd577fbb2013-06-13 03:23:42 +000010923 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010924 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010925 // deprecated if the class has a user-declared copy assignment operator
10926 // or a user-declared destructor.
10927 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10928 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10929
Eli Friedmaneaf34142012-10-18 20:14:08 +000010930 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010931 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010932
David Blaikie3fc2f912013-01-17 05:26:25 +000010933 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010934 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010935 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010936 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010937 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010938 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010939 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10940 ? CopyConstructor->getLocEnd()
10941 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010942 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010943 CopyConstructor->setBody(
10944 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010945 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010946
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010947 // The exception specification is needed because we are defining the
10948 // function.
10949 ResolveExceptionSpec(CurrentLocation,
10950 CopyConstructor->getType()->castAs<FunctionProtoType>());
10951
Eli Friedman276dd182013-09-05 00:02:25 +000010952 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010953 MarkVTableUsed(CurrentLocation, ClassDecl);
10954
Sebastian Redlab238a72011-04-24 16:28:06 +000010955 if (ASTMutationListener *L = getASTMutationListener()) {
10956 L->CompletedImplicitDefinition(CopyConstructor);
10957 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010958}
10959
Sebastian Redl22653ba2011-08-30 19:58:05 +000010960Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010961Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10962 CXXRecordDecl *ClassDecl = MD->getParent();
10963
Sebastian Redl22653ba2011-08-30 19:58:05 +000010964 // C++ [except.spec]p14:
10965 // An implicitly declared special member function (Clause 12) shall have an
10966 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010967 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010968 if (ClassDecl->isInvalidDecl())
10969 return ExceptSpec;
10970
10971 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010972 for (const auto &B : ClassDecl->bases()) {
10973 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010974 continue;
10975
Aaron Ballman574705e2014-03-13 15:41:46 +000010976 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010977 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010978 CXXConstructorDecl *Constructor =
10979 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010980 // If this is a deleted function, add it anyway. This might be conformant
10981 // with the standard. This might not. I'm not sure. It might not matter.
10982 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010983 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010984 }
10985 }
10986
10987 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010988 for (const auto &B : ClassDecl->vbases()) {
10989 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010990 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010991 CXXConstructorDecl *Constructor =
10992 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010993 // If this is a deleted function, add it anyway. This might be conformant
10994 // with the standard. This might not. I'm not sure. It might not matter.
10995 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010996 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010997 }
10998 }
10999
11000 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011001 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011002 QualType FieldType = Context.getBaseElementType(F->getType());
11003 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11004 CXXConstructorDecl *Constructor =
11005 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011006 // If this is a deleted function, add it anyway. This might be conformant
11007 // with the standard. This might not. I'm not sure. It might not matter.
11008 // In particular, the problem is that this function never gets called. It
11009 // might just be ill-formed because this function attempts to refer to
11010 // a deleted function here.
11011 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000011012 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011013 }
11014 }
11015
11016 return ExceptSpec;
11017}
11018
11019CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11020 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011021 assert(ClassDecl->needsImplicitMoveConstructor());
11022
Richard Smith8bf22e52012-11-29 01:34:07 +000011023 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11024 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011025 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011026
Sebastian Redl22653ba2011-08-30 19:58:05 +000011027 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11028 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011029
Richard Smithb5800092012-06-10 05:43:50 +000011030 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11031 CXXMoveConstructor,
11032 false);
11033
Sebastian Redl22653ba2011-08-30 19:58:05 +000011034 DeclarationName Name
11035 = Context.DeclarationNames.getCXXConstructorName(
11036 Context.getCanonicalType(ClassType));
11037 SourceLocation ClassLoc = ClassDecl->getLocation();
11038 DeclarationNameInfo NameInfo(Name, ClassLoc);
11039
Richard Smith99005e62013-05-07 03:19:20 +000011040 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000011041 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011042 // member of its class.
11043 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011044 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011045 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011046 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011047 MoveConstructor->setAccess(AS_public);
11048 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011049
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011050 if (getLangOpts().CUDA) {
11051 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11052 MoveConstructor,
11053 /* ConstRHS */ false,
11054 /* Diagnose */ false);
11055 }
11056
Richard Smithd3b5c9082012-07-27 04:22:15 +000011057 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011058 FunctionProtoType::ExtProtoInfo EPI =
11059 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011060 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011061 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011062
Sebastian Redl22653ba2011-08-30 19:58:05 +000011063 // Add the parameter to the constructor.
11064 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11065 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011066 /*IdentifierInfo=*/nullptr,
11067 ArgType, /*TInfo=*/nullptr,
11068 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011069 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011070
Richard Smith6b02d462012-12-08 08:32:28 +000011071 MoveConstructor->setTrivial(
11072 ClassDecl->needsOverloadResolutionForMoveConstructor()
11073 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11074 : ClassDecl->hasTrivialMoveConstructor());
11075
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000011076 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011077 ClassDecl->setImplicitMoveConstructorIsDeleted();
11078 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011079 }
11080
11081 // Note that we have declared this constructor.
11082 ++ASTContext::NumImplicitMoveConstructorsDeclared;
11083
11084 if (Scope *S = getScopeForContext(ClassDecl))
11085 PushOnScopeChains(MoveConstructor, S, false);
11086 ClassDecl->addDecl(MoveConstructor);
11087
11088 return MoveConstructor;
11089}
11090
11091void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11092 CXXConstructorDecl *MoveConstructor) {
11093 assert((MoveConstructor->isDefaulted() &&
11094 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011095 !MoveConstructor->doesThisDeclarationHaveABody() &&
11096 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011097 "DefineImplicitMoveConstructor - call it for implicit move ctor");
11098
11099 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11100 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11101
Eli Friedmaneaf34142012-10-18 20:14:08 +000011102 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011103 DiagnosticErrorTrap Trap(Diags);
11104
David Blaikie3fc2f912013-01-17 05:26:25 +000011105 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000011106 Trap.hasErrorOccurred()) {
11107 Diag(CurrentLocation, diag::note_member_synthesized_at)
11108 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11109 MoveConstructor->setInvalidDecl();
11110 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011111 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11112 ? MoveConstructor->getLocEnd()
11113 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011114 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011115 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011116 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011117 }
11118
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011119 // The exception specification is needed because we are defining the
11120 // function.
11121 ResolveExceptionSpec(CurrentLocation,
11122 MoveConstructor->getType()->castAs<FunctionProtoType>());
11123
Eli Friedman276dd182013-09-05 00:02:25 +000011124 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011125 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011126
11127 if (ASTMutationListener *L = getASTMutationListener()) {
11128 L->CompletedImplicitDefinition(MoveConstructor);
11129 }
11130}
11131
Douglas Gregor74f7d502012-02-15 19:33:52 +000011132bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000011133 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000011134}
Douglas Gregord3b672c2012-02-16 01:06:16 +000011135
11136void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000011137 SourceLocation CurrentLocation,
11138 CXXConversionDecl *Conv) {
11139 CXXRecordDecl *Lambda = Conv->getParent();
11140 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11141 // If we are defining a specialization of a conversion to function-ptr
11142 // cache the deduced template arguments for this specialization
11143 // so that we can use them to retrieve the corresponding call-operator
11144 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000011145 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11146
Faisal Vali571df122013-09-29 08:45:24 +000011147 // Retrieve the corresponding call-operator specialization.
11148 if (Lambda->isGenericLambda()) {
11149 assert(Conv->isFunctionTemplateSpecialization());
11150 FunctionTemplateDecl *CallOpTemplate =
11151 CallOp->getDescribedFunctionTemplate();
11152 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000011153 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011154 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011155 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011156 InsertPos);
11157 assert(CallOpSpec &&
11158 "Conversion operator must have a corresponding call operator");
11159 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11160 }
11161 // Mark the call operator referenced (and add to pending instantiations
11162 // if necessary).
11163 // For both the conversion and static-invoker template specializations
11164 // we construct their body's in this function, so no need to add them
11165 // to the PendingInstantiations.
11166 MarkFunctionReferenced(CurrentLocation, CallOp);
11167
Eli Friedmaneaf34142012-10-18 20:14:08 +000011168 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011169 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000011170
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011171 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000011172 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11173 // ... and get the corresponding specialization for a generic lambda.
11174 if (Lambda->isGenericLambda()) {
11175 assert(DeducedTemplateArgs &&
11176 "Must have deduced template arguments from Conversion Operator");
11177 FunctionTemplateDecl *InvokeTemplate =
11178 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000011179 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011180 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011181 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011182 InsertPos);
11183 assert(InvokeSpec &&
11184 "Must have a corresponding static invoker specialization");
11185 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11186 }
11187 // Construct the body of the conversion function { return __invoke; }.
11188 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011189 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000011190 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011191 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000011192 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11193 Conv->getLocation(),
11194 Conv->getLocation()));
11195
11196 Conv->markUsed(Context);
11197 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011198
Faisal Vali571df122013-09-29 08:45:24 +000011199 // Fill in the __invoke function with a dummy implementation. IR generation
11200 // will fill in the actual details.
11201 Invoker->markUsed(Context);
11202 Invoker->setReferenced();
11203 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11204
Douglas Gregord3b672c2012-02-16 01:06:16 +000011205 if (ASTMutationListener *L = getASTMutationListener()) {
11206 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000011207 L->CompletedImplicitDefinition(Invoker);
11208 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000011209}
11210
Faisal Vali571df122013-09-29 08:45:24 +000011211
11212
Douglas Gregord3b672c2012-02-16 01:06:16 +000011213void Sema::DefineImplicitLambdaToBlockPointerConversion(
11214 SourceLocation CurrentLocation,
11215 CXXConversionDecl *Conv)
11216{
Faisal Vali850da1a2013-09-29 17:08:32 +000011217 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000011218
Eli Friedman276dd182013-09-05 00:02:25 +000011219 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011220
Eli Friedmaneaf34142012-10-18 20:14:08 +000011221 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011222 DiagnosticErrorTrap Trap(Diags);
11223
Douglas Gregored90df32012-02-22 05:02:47 +000011224 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011225 Expr *This = ActOnCXXThis(CurrentLocation).get();
11226 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011227
Eli Friedman98b01ed2012-03-01 04:01:32 +000011228 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11229 Conv->getLocation(),
11230 Conv, DerefThis);
11231
11232 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11233 // behavior. Note that only the general conversion function does this
11234 // (since it's unusable otherwise); in the case where we inline the
11235 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011236 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000011237 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11238 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000011239 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000011240
11241 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000011242 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000011243 Conv->setInvalidDecl();
11244 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000011245 }
Douglas Gregored90df32012-02-22 05:02:47 +000011246
Douglas Gregored90df32012-02-22 05:02:47 +000011247 // Create the return statement that returns the block from the conversion
11248 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011249 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000011250 if (Return.isInvalid()) {
11251 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11252 Conv->setInvalidDecl();
11253 return;
11254 }
11255
11256 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011257 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000011258 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000011259 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000011260 Conv->getLocation()));
11261
Douglas Gregored90df32012-02-22 05:02:47 +000011262 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000011263 if (ASTMutationListener *L = getASTMutationListener()) {
11264 L->CompletedImplicitDefinition(Conv);
11265 }
11266}
11267
Douglas Gregord2f70072012-03-10 06:53:13 +000011268/// \brief Determine whether the given list arguments contains exactly one
11269/// "real" (non-default) argument.
11270static bool hasOneRealArgument(MultiExprArg Args) {
11271 switch (Args.size()) {
11272 case 0:
11273 return false;
11274
11275 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011276 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000011277 return false;
11278
11279 // fall through
11280 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011281 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000011282 }
11283
11284 return false;
11285}
11286
John McCalldadc5752010-08-24 06:29:42 +000011287ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011288Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000011289 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011290 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011291 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011292 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011293 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011294 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011295 unsigned ConstructKind,
11296 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000011297 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000011298
Douglas Gregor45cf7e32010-04-02 18:24:57 +000011299 // C++0x [class.copy]p34:
11300 // When certain criteria are met, an implementation is allowed to
11301 // omit the copy/move construction of a class object, even if the
11302 // copy/move constructor and/or destructor for the object have
11303 // side effects. [...]
11304 // - when a temporary class object that has not been bound to a
11305 // reference (12.2) would be copied/moved to a class object
11306 // with the same cv-unqualified type, the copy/move operation
11307 // can be omitted by constructing the temporary object
11308 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000011309 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000011310 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011311 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000011312 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000011313 }
Mike Stump11289f42009-09-09 15:08:12 +000011314
11315 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011316 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011317 IsListInitialization,
11318 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000011319 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000011320}
11321
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011322/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11323/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000011324ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011325Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11326 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011327 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011328 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011329 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011330 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011331 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011332 unsigned ConstructKind,
11333 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011334 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011335 return CXXConstructExpr::Create(
11336 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011337 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11338 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011339 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11340 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011341}
11342
Reid Klecknerd60b82f2014-11-17 23:36:45 +000011343ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11344 assert(Field->hasInClassInitializer());
11345
11346 // If we already have the in-class initializer nothing needs to be done.
11347 if (Field->getInClassInitializer())
11348 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11349
11350 // Maybe we haven't instantiated the in-class initializer. Go check the
11351 // pattern FieldDecl to see if it has one.
11352 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11353
11354 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11355 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11356 DeclContext::lookup_result Lookup =
11357 ClassPattern->lookup(Field->getDeclName());
11358 assert(Lookup.size() == 1);
11359 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11360 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11361 getTemplateInstantiationArgs(Field)))
11362 return ExprError();
11363 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11364 }
11365
11366 // DR1351:
11367 // If the brace-or-equal-initializer of a non-static data member
11368 // invokes a defaulted default constructor of its class or of an
11369 // enclosing class in a potentially evaluated subexpression, the
11370 // program is ill-formed.
11371 //
11372 // This resolution is unworkable: the exception specification of the
11373 // default constructor can be needed in an unevaluated context, in
11374 // particular, in the operand of a noexcept-expression, and we can be
11375 // unable to compute an exception specification for an enclosed class.
11376 //
11377 // Any attempt to resolve the exception specification of a defaulted default
11378 // constructor before the initializer is lexically complete will ultimately
11379 // come here at which point we can diagnose it.
11380 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11381 if (OutermostClass == ParentRD) {
11382 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11383 << ParentRD << Field;
11384 } else {
11385 Diag(Field->getLocEnd(),
11386 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11387 << ParentRD << OutermostClass << Field;
11388 }
11389
11390 return ExprError();
11391}
11392
John McCall03c48482010-02-02 09:10:11 +000011393void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000011394 if (VD->isInvalidDecl()) return;
11395
John McCall03c48482010-02-02 09:10:11 +000011396 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000011397 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000011398 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011399 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000011400
Chandler Carruth86d17d32011-03-27 21:26:48 +000011401 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011402 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000011403 CheckDestructorAccess(VD->getLocation(), Destructor,
11404 PDiag(diag::err_access_dtor_var)
11405 << VD->getDeclName()
11406 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000011407 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000011408
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011409 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011410 if (!VD->hasGlobalStorage()) return;
11411
11412 // Emit warning for non-trivial dtor in global scope (a real global,
11413 // class-static, function-static).
11414 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11415
11416 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011417 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000011418 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000011419}
11420
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011421/// \brief Given a constructor and the set of arguments provided for the
11422/// constructor, convert the arguments and add any required default arguments
11423/// to form a proper call to this constructor.
11424///
11425/// \returns true if an error occurred, false otherwise.
11426bool
11427Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11428 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000011429 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000011430 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011431 bool AllowExplicit,
11432 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011433 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11434 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011435 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011436
11437 const FunctionProtoType *Proto
11438 = Constructor->getType()->getAs<FunctionProtoType>();
11439 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011440 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000011441
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011442 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011443 if (NumArgs < NumParams)
11444 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011445 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011446 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011447
11448 VariadicCallType CallType =
11449 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011450 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011451 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011452 Proto, 0,
11453 llvm::makeArrayRef(Args, NumArgs),
11454 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011455 CallType, AllowExplicit,
11456 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000011457 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000011458
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011459 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011460
Dmitri Gribenko765396f2013-01-13 20:46:02 +000011461 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000011462 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000011463 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011464
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011465 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000011466}
11467
Anders Carlssone363c8e2009-12-12 00:32:00 +000011468static inline bool
11469CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11470 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011471 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000011472 if (isa<NamespaceDecl>(DC)) {
11473 return SemaRef.Diag(FnDecl->getLocation(),
11474 diag::err_operator_new_delete_declared_in_namespace)
11475 << FnDecl->getDeclName();
11476 }
11477
11478 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000011479 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011480 return SemaRef.Diag(FnDecl->getLocation(),
11481 diag::err_operator_new_delete_declared_static)
11482 << FnDecl->getDeclName();
11483 }
11484
Anders Carlsson60659a82009-12-12 02:43:16 +000011485 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000011486}
11487
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011488static inline bool
11489CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11490 CanQualType ExpectedResultType,
11491 CanQualType ExpectedFirstParamType,
11492 unsigned DependentParamTypeDiag,
11493 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000011494 QualType ResultType =
11495 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011496
11497 // Check that the result type is not dependent.
11498 if (ResultType->isDependentType())
11499 return SemaRef.Diag(FnDecl->getLocation(),
11500 diag::err_operator_new_delete_dependent_result_type)
11501 << FnDecl->getDeclName() << ExpectedResultType;
11502
11503 // Check that the result type is what we expect.
11504 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11505 return SemaRef.Diag(FnDecl->getLocation(),
11506 diag::err_operator_new_delete_invalid_result_type)
11507 << FnDecl->getDeclName() << ExpectedResultType;
11508
11509 // A function template must have at least 2 parameters.
11510 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11511 return SemaRef.Diag(FnDecl->getLocation(),
11512 diag::err_operator_new_delete_template_too_few_parameters)
11513 << FnDecl->getDeclName();
11514
11515 // The function decl must have at least 1 parameter.
11516 if (FnDecl->getNumParams() == 0)
11517 return SemaRef.Diag(FnDecl->getLocation(),
11518 diag::err_operator_new_delete_too_few_parameters)
11519 << FnDecl->getDeclName();
11520
Sylvestre Ledru830885c2012-07-23 08:59:39 +000011521 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011522 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11523 if (FirstParamType->isDependentType())
11524 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11525 << FnDecl->getDeclName() << ExpectedFirstParamType;
11526
11527 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000011528 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011529 ExpectedFirstParamType)
11530 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11531 << FnDecl->getDeclName() << ExpectedFirstParamType;
11532
11533 return false;
11534}
11535
Anders Carlsson12308f42009-12-11 23:23:22 +000011536static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011537CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011538 // C++ [basic.stc.dynamic.allocation]p1:
11539 // A program is ill-formed if an allocation function is declared in a
11540 // namespace scope other than global scope or declared static in global
11541 // scope.
11542 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11543 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011544
11545 CanQualType SizeTy =
11546 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11547
11548 // C++ [basic.stc.dynamic.allocation]p1:
11549 // The return type shall be void*. The first parameter shall have type
11550 // std::size_t.
11551 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11552 SizeTy,
11553 diag::err_operator_new_dependent_param_type,
11554 diag::err_operator_new_param_type))
11555 return true;
11556
11557 // C++ [basic.stc.dynamic.allocation]p1:
11558 // The first parameter shall not have an associated default argument.
11559 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011560 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011561 diag::err_operator_new_default_arg)
11562 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11563
11564 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011565}
11566
11567static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011568CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011569 // C++ [basic.stc.dynamic.deallocation]p1:
11570 // A program is ill-formed if deallocation functions are declared in a
11571 // namespace scope other than global scope or declared static in global
11572 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011573 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11574 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011575
11576 // C++ [basic.stc.dynamic.deallocation]p2:
11577 // Each deallocation function shall return void and its first parameter
11578 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011579 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11580 SemaRef.Context.VoidPtrTy,
11581 diag::err_operator_delete_dependent_param_type,
11582 diag::err_operator_delete_param_type))
11583 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011584
Anders Carlsson12308f42009-12-11 23:23:22 +000011585 return false;
11586}
11587
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011588/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11589/// of this overloaded operator is well-formed. If so, returns false;
11590/// otherwise, emits appropriate diagnostics and returns true.
11591bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011592 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011593 "Expected an overloaded operator declaration");
11594
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011595 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11596
Mike Stump11289f42009-09-09 15:08:12 +000011597 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011598 // The allocation and deallocation functions, operator new,
11599 // operator new[], operator delete and operator delete[], are
11600 // described completely in 3.7.3. The attributes and restrictions
11601 // found in the rest of this subclause do not apply to them unless
11602 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011603 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011604 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011605
Anders Carlsson22f443f2009-12-12 00:26:23 +000011606 if (Op == OO_New || Op == OO_Array_New)
11607 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011608
11609 // C++ [over.oper]p6:
11610 // An operator function shall either be a non-static member
11611 // function or be a non-member function and have at least one
11612 // parameter whose type is a class, a reference to a class, an
11613 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011614 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11615 if (MethodDecl->isStatic())
11616 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011617 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011618 } else {
11619 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011620 for (auto Param : FnDecl->params()) {
11621 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011622 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11623 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011624 ClassOrEnumParam = true;
11625 break;
11626 }
11627 }
11628
Douglas Gregord69246b2008-11-17 16:14:12 +000011629 if (!ClassOrEnumParam)
11630 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011631 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011632 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011633 }
11634
11635 // C++ [over.oper]p8:
11636 // An operator function cannot have default arguments (8.3.6),
11637 // except where explicitly stated below.
11638 //
Mike Stump11289f42009-09-09 15:08:12 +000011639 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011640 // (C++ [over.call]p1).
11641 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011642 for (auto Param : FnDecl->params()) {
11643 if (Param->hasDefaultArg())
11644 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011645 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011646 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011647 }
11648 }
11649
Douglas Gregor6cf08062008-11-10 13:38:07 +000011650 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11651 { false, false, false }
11652#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11653 , { Unary, Binary, MemberOnly }
11654#include "clang/Basic/OperatorKinds.def"
11655 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011656
Douglas Gregor6cf08062008-11-10 13:38:07 +000011657 bool CanBeUnaryOperator = OperatorUses[Op][0];
11658 bool CanBeBinaryOperator = OperatorUses[Op][1];
11659 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011660
11661 // C++ [over.oper]p8:
11662 // [...] Operator functions cannot have more or fewer parameters
11663 // than the number required for the corresponding operator, as
11664 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011665 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011666 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011667 if (Op != OO_Call &&
11668 ((NumParams == 1 && !CanBeUnaryOperator) ||
11669 (NumParams == 2 && !CanBeBinaryOperator) ||
11670 (NumParams < 1) || (NumParams > 2))) {
11671 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011672 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011673 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011674 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011675 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011676 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011677 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011678 assert(CanBeBinaryOperator &&
11679 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011680 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011681 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011682
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011683 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011684 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011685 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011686
Douglas Gregord69246b2008-11-17 16:14:12 +000011687 // Overloaded operators other than operator() cannot be variadic.
11688 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011689 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011690 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011691 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011692 }
11693
11694 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011695 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11696 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011697 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011698 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011699 }
11700
11701 // C++ [over.inc]p1:
11702 // The user-defined function called operator++ implements the
11703 // prefix and postfix ++ operator. If this function is a member
11704 // function with no parameters, or a non-member function with one
11705 // parameter of class or enumeration type, it defines the prefix
11706 // increment operator ++ for objects of that type. If the function
11707 // is a member function with one parameter (which shall be of type
11708 // int) or a non-member function with two parameters (the second
11709 // of which shall be of type int), it defines the postfix
11710 // increment operator ++ for objects of that type.
11711 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11712 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011713 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011714
Richard Smith538b52a2014-01-30 22:24:05 +000011715 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11716 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011717 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011718 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011719 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011720 }
11721
Douglas Gregord69246b2008-11-17 16:14:12 +000011722 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011723}
Chris Lattner3b024a32008-12-17 07:09:26 +000011724
Alexis Huntc88db062010-01-13 09:01:02 +000011725/// CheckLiteralOperatorDeclaration - Check whether the declaration
11726/// of this literal operator function is well-formed. If so, returns
11727/// false; otherwise, emits appropriate diagnostics and returns true.
11728bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011729 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011730 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11731 << FnDecl->getDeclName();
11732 return true;
11733 }
11734
Richard Smith72eebee2012-03-04 09:41:16 +000011735 if (FnDecl->isExternC()) {
11736 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11737 return true;
11738 }
11739
Alexis Huntc88db062010-01-13 09:01:02 +000011740 bool Valid = false;
11741
Richard Smithbcc22fc2012-03-09 08:00:36 +000011742 // This might be the definition of a literal operator template.
11743 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11744 // This might be a specialization of a literal operator template.
11745 if (!TpDecl)
11746 TpDecl = FnDecl->getPrimaryTemplate();
11747
Richard Smithb8b41d32013-10-07 19:57:58 +000011748 // template <char...> type operator "" name() and
11749 // template <class T, T...> type operator "" name() are the only valid
11750 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011751 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011752 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011753 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011754 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11755 if (Params->size() == 1) {
11756 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011757 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011758
Alexis Hunt7dd26172010-04-07 23:11:06 +000011759 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011760 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11761 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11762 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011763 } else if (Params->size() == 2) {
11764 TemplateTypeParmDecl *PmType =
11765 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11766 NonTypeTemplateParmDecl *PmArgs =
11767 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11768
11769 // The second template parameter must be a parameter pack with the
11770 // first template parameter as its type.
11771 if (PmType && PmArgs &&
11772 !PmType->isTemplateParameterPack() &&
11773 PmArgs->isTemplateParameterPack()) {
11774 const TemplateTypeParmType *TArgs =
11775 PmArgs->getType()->getAs<TemplateTypeParmType>();
11776 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11777 TArgs->getIndex() == PmType->getIndex()) {
11778 Valid = true;
11779 if (ActiveTemplateInstantiations.empty())
11780 Diag(FnDecl->getLocation(),
11781 diag::ext_string_literal_operator_template);
11782 }
11783 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011784 }
11785 }
Richard Smith72eebee2012-03-04 09:41:16 +000011786 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011787 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011788 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11789
Richard Smith72eebee2012-03-04 09:41:16 +000011790 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011791
Alexis Hunt079a6f72010-04-07 22:57:35 +000011792 // unsigned long long int, long double, and any character type are allowed
11793 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011794 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11795 Context.hasSameType(T, Context.LongDoubleTy) ||
11796 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011797 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011798 Context.hasSameType(T, Context.Char16Ty) ||
11799 Context.hasSameType(T, Context.Char32Ty)) {
11800 if (++Param == FnDecl->param_end())
11801 Valid = true;
11802 goto FinishedParams;
11803 }
11804
Alexis Hunt079a6f72010-04-07 22:57:35 +000011805 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011806 const PointerType *PT = T->getAs<PointerType>();
11807 if (!PT)
11808 goto FinishedParams;
11809 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011810 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011811 goto FinishedParams;
11812 T = T.getUnqualifiedType();
11813
11814 // Move on to the second parameter;
11815 ++Param;
11816
11817 // If there is no second parameter, the first must be a const char *
11818 if (Param == FnDecl->param_end()) {
11819 if (Context.hasSameType(T, Context.CharTy))
11820 Valid = true;
11821 goto FinishedParams;
11822 }
11823
11824 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11825 // are allowed as the first parameter to a two-parameter function
11826 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011827 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011828 Context.hasSameType(T, Context.Char16Ty) ||
11829 Context.hasSameType(T, Context.Char32Ty)))
11830 goto FinishedParams;
11831
11832 // The second and final parameter must be an std::size_t
11833 T = (*Param)->getType().getUnqualifiedType();
11834 if (Context.hasSameType(T, Context.getSizeType()) &&
11835 ++Param == FnDecl->param_end())
11836 Valid = true;
11837 }
11838
11839 // FIXME: This diagnostic is absolutely terrible.
11840FinishedParams:
11841 if (!Valid) {
11842 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11843 << FnDecl->getDeclName();
11844 return true;
11845 }
11846
Richard Smith768cecc2012-03-09 08:16:22 +000011847 // A parameter-declaration-clause containing a default argument is not
11848 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011849 for (auto Param : FnDecl->params()) {
11850 if (Param->hasDefaultArg()) {
11851 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011852 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011853 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011854 break;
11855 }
11856 }
11857
Richard Smith0df56f42012-03-08 02:39:21 +000011858 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011859 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11860 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011861 // C++11 [usrlit.suffix]p1:
11862 // Literal suffix identifiers that do not start with an underscore
11863 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011864 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11865 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011866 }
Richard Smith0df56f42012-03-08 02:39:21 +000011867
Alexis Huntc88db062010-01-13 09:01:02 +000011868 return false;
11869}
11870
Douglas Gregor07665a62009-01-05 19:45:36 +000011871/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11872/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011873/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11874/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011875/// the '{' brace. Otherwise, this linkage specification does not
11876/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011877Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011878 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011879 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011880 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11881 if (!Lit->isAscii()) {
11882 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11883 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011884 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011885 }
11886
11887 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011888 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011889 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011890 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011891 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011892 Language = LinkageSpecDecl::lang_cxx;
11893 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011894 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11895 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011896 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011897 }
Mike Stump11289f42009-09-09 15:08:12 +000011898
Chris Lattner438e5012008-12-17 07:13:27 +000011899 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011900
Richard Smith4ee696d2014-02-17 23:25:27 +000011901 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11902 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011903 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011904 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011905 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011906 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011907}
11908
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011909/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011910/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11911/// valid, it's the position of the closing '}' brace in a linkage
11912/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011913Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011914 Decl *LinkageSpec,
11915 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011916 if (RBraceLoc.isValid()) {
11917 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11918 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011919 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011920 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011921 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011922}
11923
Michael Han84324352013-02-22 17:15:32 +000011924Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11925 AttributeList *AttrList,
11926 SourceLocation SemiLoc) {
11927 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11928 // Attribute declarations appertain to empty declaration so we handle
11929 // them here.
11930 if (AttrList)
11931 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011932
Michael Han84324352013-02-22 17:15:32 +000011933 CurContext->addDecl(ED);
11934 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011935}
11936
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011937/// \brief Perform semantic analysis for the variable declaration that
11938/// occurs within a C++ catch clause, returning the newly-created
11939/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011940VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011941 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011942 SourceLocation StartLoc,
11943 SourceLocation Loc,
11944 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011945 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011946 QualType ExDeclType = TInfo->getType();
11947
Sebastian Redl54c04d42008-12-22 19:15:10 +000011948 // Arrays and functions decay.
11949 if (ExDeclType->isArrayType())
11950 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11951 else if (ExDeclType->isFunctionType())
11952 ExDeclType = Context.getPointerType(ExDeclType);
11953
11954 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11955 // The exception-declaration shall not denote a pointer or reference to an
11956 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011957 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011958 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011959 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011960 Invalid = true;
11961 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011962
Sebastian Redl54c04d42008-12-22 19:15:10 +000011963 QualType BaseType = ExDeclType;
11964 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011965 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011966 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011967 BaseType = Ptr->getPointeeType();
11968 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011969 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011970 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011971 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011972 BaseType = Ref->getPointeeType();
11973 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011974 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011975 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011976 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011977 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011978 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011979
Mike Stump11289f42009-09-09 15:08:12 +000011980 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011981 RequireNonAbstractType(Loc, ExDeclType,
11982 diag::err_abstract_type_in_decl,
11983 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011984 Invalid = true;
11985
John McCall2ca705e2010-07-24 00:37:23 +000011986 // Only the non-fragile NeXT runtime currently supports C++ catches
11987 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011988 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011989 QualType T = ExDeclType;
11990 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11991 T = RT->getPointeeType();
11992
11993 if (T->isObjCObjectType()) {
11994 Diag(Loc, diag::err_objc_object_catch);
11995 Invalid = true;
11996 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011997 // FIXME: should this be a test for macosx-fragile specifically?
11998 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011999 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000012000 }
12001 }
12002
Abramo Bagnaradff19302011-03-08 08:55:46 +000012003 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000012004 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000012005 ExDecl->setExceptionVariable(true);
12006
Douglas Gregor8ca0c642011-12-10 01:22:52 +000012007 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012008 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000012009 Invalid = true;
12010
Douglas Gregor750734c2011-07-06 18:14:43 +000012011 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000012012 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000012013 // Insulate this from anything else we might currently be parsing.
12014 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12015
Douglas Gregor6de584c2010-03-05 23:38:39 +000012016 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000012017 // The object declared in an exception-declaration or, if the
12018 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000012019 // copy-initialized (8.5) from the exception object. [...]
12020 // The object is destroyed when the handler exits, after the destruction
12021 // of any automatic objects initialized within the handler.
12022 //
Nick Lewycky0f292892013-09-22 10:06:57 +000012023 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000012024 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000012025 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000012026
12027 InitializedEntity entity =
12028 InitializedEntity::InitializeVariable(ExDecl);
12029 InitializationKind initKind =
12030 InitializationKind::CreateCopy(Loc, SourceLocation());
12031
12032 Expr *opaqueValue =
12033 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000012034 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12035 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000012036 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000012037 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000012038 else {
12039 // If the constructor used was non-trivial, set this as the
12040 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012041 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000012042 if (!construct->getConstructor()->isTrivial()) {
12043 Expr *init = MaybeCreateExprWithCleanups(construct);
12044 ExDecl->setInit(init);
12045 }
12046
12047 // And make sure it's destructable.
12048 FinalizeVarWithDestructor(ExDecl, recordType);
12049 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000012050 }
12051 }
12052
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012053 if (Invalid)
12054 ExDecl->setInvalidDecl();
12055
12056 return ExDecl;
12057}
12058
12059/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12060/// handler.
John McCall48871652010-08-21 09:40:31 +000012061Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000012062 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000012063 bool Invalid = D.isInvalidType();
12064
12065 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000012066 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12067 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000012068 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12069 D.getIdentifierLoc());
12070 Invalid = true;
12071 }
12072
Sebastian Redl54c04d42008-12-22 19:15:10 +000012073 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012074 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000012075 LookupOrdinaryName,
12076 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012077 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012078 // it contains any previous declaration, except for function parameters in
12079 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000012080 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012081 if (isDeclInScope(PrevDecl, CurContext, S)) {
12082 Diag(D.getIdentifierLoc(), diag::err_redefinition)
12083 << D.getIdentifier();
12084 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12085 Invalid = true;
12086 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000012087 // Maybe we will complain about the shadowed template parameter.
12088 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012089 }
12090
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012091 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012092 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12093 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012094 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012095 }
12096
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012097 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012098 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000012099 D.getIdentifierLoc(),
12100 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012101 if (Invalid)
12102 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000012103
Sebastian Redl54c04d42008-12-22 19:15:10 +000012104 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000012105 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012106 PushOnScopeChains(ExDecl, S);
12107 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012108 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012109
Douglas Gregor758a8692009-06-17 21:51:59 +000012110 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000012111 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012112}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012113
Abramo Bagnaraea947882011-03-08 16:41:52 +000012114Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000012115 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000012116 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000012117 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000012118 StringLiteral *AssertMessage =
12119 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012120
Richard Smithded9c2e2012-07-11 22:37:56 +000012121 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000012122 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000012123
12124 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12125 AssertMessage, RParenLoc, false);
12126}
12127
12128Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12129 Expr *AssertExpr,
12130 StringLiteral *AssertMessage,
12131 SourceLocation RParenLoc,
12132 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000012133 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000012134 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12135 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012136 // In a static_assert-declaration, the constant-expression shall be a
12137 // constant expression that can be contextually converted to bool.
12138 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12139 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012140 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000012141
Richard Smith902ca212011-12-14 23:32:26 +000012142 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000012143 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000012144 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000012145 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012146 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012147
Richard Smithded9c2e2012-07-11 22:37:56 +000012148 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012149 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000012150 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000012151 if (AssertMessage)
12152 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000012153 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000012154 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000012155 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000012156 }
Anders Carlsson54b26982009-03-14 00:33:21 +000012157 }
Mike Stump11289f42009-09-09 15:08:12 +000012158
Abramo Bagnaraea947882011-03-08 16:41:52 +000012159 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000012160 AssertExpr, AssertMessage, RParenLoc,
12161 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000012162
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012163 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000012164 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012165}
Sebastian Redlf769df52009-03-24 22:27:57 +000012166
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012167/// \brief Perform semantic analysis of the given friend type declaration.
12168///
12169/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000012170FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000012171 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012172 TypeSourceInfo *TSInfo) {
12173 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12174
12175 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000012176 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012177
Richard Smithc8239732011-10-18 21:39:00 +000012178 // C++03 [class.friend]p2:
12179 // An elaborated-type-specifier shall be used in a friend declaration
12180 // for a class.*
12181 //
12182 // * The class-key of the elaborated-type-specifier is required.
12183 if (!ActiveTemplateInstantiations.empty()) {
12184 // Do not complain about the form of friend template types during
12185 // template instantiation; we will already have complained when the
12186 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000012187 } else {
12188 if (!T->isElaboratedTypeSpecifier()) {
12189 // If we evaluated the type to a record type, suggest putting
12190 // a tag in front.
12191 if (const RecordType *RT = T->getAs<RecordType>()) {
12192 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000012193
12194 SmallString<16> InsertionText(" ");
12195 InsertionText += RD->getKindName();
12196
Nick Lewycky36722d22013-02-06 05:59:33 +000012197 Diag(TypeRange.getBegin(),
12198 getLangOpts().CPlusPlus11 ?
12199 diag::warn_cxx98_compat_unelaborated_friend_type :
12200 diag::ext_unelaborated_friend_type)
12201 << (unsigned) RD->getTagKind()
12202 << T
12203 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12204 InsertionText);
12205 } else {
12206 Diag(FriendLoc,
12207 getLangOpts().CPlusPlus11 ?
12208 diag::warn_cxx98_compat_nonclass_type_friend :
12209 diag::ext_nonclass_type_friend)
12210 << T
12211 << TypeRange;
12212 }
12213 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000012214 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012215 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000012216 diag::warn_cxx98_compat_enum_friend :
12217 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012218 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000012219 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012220 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012221
Nick Lewycky36722d22013-02-06 05:59:33 +000012222 // C++11 [class.friend]p3:
12223 // A friend declaration that does not declare a function shall have one
12224 // of the following forms:
12225 // friend elaborated-type-specifier ;
12226 // friend simple-type-specifier ;
12227 // friend typename-specifier ;
12228 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12229 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12230 }
Richard Smitha31a89a2012-09-20 01:31:00 +000012231
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012232 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000012233 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012234 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000012235 return FriendDecl::Create(Context, CurContext,
12236 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12237 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012238}
12239
John McCallace48cd2010-10-19 01:40:49 +000012240/// Handle a friend tag declaration where the scope specifier was
12241/// templated.
12242Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12243 unsigned TagSpec, SourceLocation TagLoc,
12244 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012245 IdentifierInfo *Name,
12246 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000012247 AttributeList *Attr,
12248 MultiTemplateParamsArg TempParamLists) {
12249 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12250
12251 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000012252 bool Invalid = false;
12253
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012254 if (TemplateParameterList *TemplateParams =
12255 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000012256 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012257 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000012258 if (TemplateParams->size() > 0) {
12259 // This is a declaration of a class template.
12260 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000012261 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000012262
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012263 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12264 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000012265 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012266 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012267 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000012268 } else {
12269 // The "template<>" header is extraneous.
12270 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12271 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12272 isExplicitSpecialization = true;
12273 }
12274 }
12275
Craig Topperc3ec1492014-05-26 06:22:03 +000012276 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012277
John McCallace48cd2010-10-19 01:40:49 +000012278 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000012279 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012280 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000012281 isAllExplicitSpecializations = false;
12282 break;
12283 }
12284 }
12285
12286 // FIXME: don't ignore attributes.
12287
12288 // If it's explicit specializations all the way down, just forget
12289 // about the template header and build an appropriate non-templated
12290 // friend. TODO: for source fidelity, remember the headers.
12291 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012292 if (SS.isEmpty()) {
12293 bool Owned = false;
12294 bool IsDependent = false;
12295 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000012296 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012297 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000012298 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000012299 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012300 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000012301 /*UnderlyingType=*/TypeResult(),
12302 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012303 }
Richard Smith649c7b062014-01-08 00:56:48 +000012304
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012305 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000012306 ElaboratedTypeKeyword Keyword
12307 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012308 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000012309 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012310 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000012311 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012312
12313 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12314 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000012315 DependentNameTypeLoc TL =
12316 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012317 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012318 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000012319 TL.setNameLoc(NameLoc);
12320 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000012321 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012322 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000012323 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000012324 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012325 }
12326
12327 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012328 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012329 Friend->setAccess(AS_public);
12330 CurContext->addDecl(Friend);
12331 return Friend;
12332 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012333
12334 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12335
12336
John McCallace48cd2010-10-19 01:40:49 +000012337
12338 // Handle the case of a templated-scope friend class. e.g.
12339 // template <class T> class A<T>::B;
12340 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000012341 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12342 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000012343 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12344 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12345 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000012346 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012347 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012348 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000012349 TL.setNameLoc(NameLoc);
12350
12351 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012352 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012353 Friend->setAccess(AS_public);
12354 Friend->setUnsupportedFriend(true);
12355 CurContext->addDecl(Friend);
12356 return Friend;
12357}
12358
12359
John McCall11083da2009-09-16 22:47:08 +000012360/// Handle a friend type declaration. This works in tandem with
12361/// ActOnTag.
12362///
12363/// Notes on friend class templates:
12364///
12365/// We generally treat friend class declarations as if they were
12366/// declaring a class. So, for example, the elaborated type specifier
12367/// in a friend declaration is required to obey the restrictions of a
12368/// class-head (i.e. no typedefs in the scope chain), template
12369/// parameters are required to match up with simple template-ids, &c.
12370/// However, unlike when declaring a template specialization, it's
12371/// okay to refer to a template specialization without an empty
12372/// template parameter declaration, e.g.
12373/// friend class A<T>::B<unsigned>;
12374/// We permit this as a special case; if there are any template
12375/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000012376/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000012377Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000012378 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012379 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000012380
12381 assert(DS.isFriendSpecified());
12382 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12383
John McCall11083da2009-09-16 22:47:08 +000012384 // Try to convert the decl specifier to a type. This works for
12385 // friend templates because ActOnTag never produces a ClassTemplateDecl
12386 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000012387 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000012388 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12389 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000012390 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000012391 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012392
Douglas Gregor6c110f32010-12-16 01:14:37 +000012393 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012394 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012395
John McCall11083da2009-09-16 22:47:08 +000012396 // This is definitely an error in C++98. It's probably meant to
12397 // be forbidden in C++0x, too, but the specification is just
12398 // poorly written.
12399 //
12400 // The problem is with declarations like the following:
12401 // template <T> friend A<T>::foo;
12402 // where deciding whether a class C is a friend or not now hinges
12403 // on whether there exists an instantiation of A that causes
12404 // 'foo' to equal C. There are restrictions on class-heads
12405 // (which we declare (by fiat) elaborated friend declarations to
12406 // be) that makes this tractable.
12407 //
12408 // FIXME: handle "template <> friend class A<T>;", which
12409 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000012410 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000012411 Diag(Loc, diag::err_tagless_friend_type_template)
12412 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012413 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000012414 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012415
John McCallaa74a0c2009-08-28 07:59:38 +000012416 // C++98 [class.friend]p1: A friend of a class is a function
12417 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000012418 // This is fixed in DR77, which just barely didn't make the C++03
12419 // deadline. It's also a very silly restriction that seriously
12420 // affects inner classes and which nobody else seems to implement;
12421 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000012422 //
12423 // But note that we could warn about it: it's always useless to
12424 // friend one of your own members (it's not, however, worthless to
12425 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000012426
John McCall11083da2009-09-16 22:47:08 +000012427 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012428 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000012429 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012430 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012431 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000012432 TSI,
John McCall11083da2009-09-16 22:47:08 +000012433 DS.getFriendSpecLoc());
12434 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000012435 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012436
12437 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000012438 return nullptr;
12439
John McCall11083da2009-09-16 22:47:08 +000012440 D->setAccess(AS_public);
12441 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000012442
John McCall48871652010-08-21 09:40:31 +000012443 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000012444}
12445
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000012446NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12447 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000012448 const DeclSpec &DS = D.getDeclSpec();
12449
12450 assert(DS.isFriendSpecified());
12451 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12452
12453 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000012454 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000012455
12456 // C++ [class.friend]p1
12457 // A friend of a class is a function or class....
12458 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000012459 // It *doesn't* see through dependent types, which is correct
12460 // according to [temp.arg.type]p3:
12461 // If a declaration acquires a function type through a
12462 // type dependent on a template-parameter and this causes
12463 // a declaration that does not use the syntactic form of a
12464 // function declarator to have a function type, the program
12465 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012466 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000012467 Diag(Loc, diag::err_unexpected_friend);
12468
12469 // It might be worthwhile to try to recover by creating an
12470 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012471 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012472 }
12473
12474 // C++ [namespace.memdef]p3
12475 // - If a friend declaration in a non-local class first declares a
12476 // class or function, the friend class or function is a member
12477 // of the innermost enclosing namespace.
12478 // - The name of the friend is not found by simple name lookup
12479 // until a matching declaration is provided in that namespace
12480 // scope (either before or after the class declaration granting
12481 // friendship).
12482 // - If a friend function is called, its name may be found by the
12483 // name lookup that considers functions from namespaces and
12484 // classes associated with the types of the function arguments.
12485 // - When looking for a prior declaration of a class or a function
12486 // declared as a friend, scopes outside the innermost enclosing
12487 // namespace scope are not considered.
12488
John McCallde3fd222010-10-12 23:13:28 +000012489 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012490 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12491 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000012492 assert(Name);
12493
Douglas Gregor6c110f32010-12-16 01:14:37 +000012494 // Check for unexpanded parameter packs.
12495 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12496 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12497 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012498 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012499
John McCall07e91c02009-08-06 02:15:43 +000012500 // The context we found the declaration in, or in which we should
12501 // create the declaration.
12502 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000012503 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012504 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000012505 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000012506
Richard Smith114394f2013-08-09 04:35:01 +000012507 // There are five cases here.
12508 // - There's no scope specifier and we're in a local class. Only look
12509 // for functions declared in the immediately-enclosing block scope.
12510 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000012511 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000012512 if ((SS.isInvalid() || !SS.isSet()) &&
12513 (FunctionContainingLocalClass =
12514 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12515 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000012516 // If a friend declaration appears in a local class and the name
12517 // specified is an unqualified name, a prior declaration is
12518 // looked up without considering scopes that are outside the
12519 // innermost enclosing non-class scope. For a friend function
12520 // declaration, if there is no prior declaration, the program is
12521 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000012522
12523 // Find the innermost enclosing non-class scope. This is the block
12524 // scope containing the local class definition (or for a nested class,
12525 // the outer local class).
12526 DCScope = S->getFnParent();
12527
12528 // Look up the function name in the scope.
12529 Previous.clear(LookupLocalFriendName);
12530 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12531
12532 if (!Previous.empty()) {
12533 // All possible previous declarations must have the same context:
12534 // either they were declared at block scope or they are members of
12535 // one of the enclosing local classes.
12536 DC = Previous.getRepresentativeDecl()->getDeclContext();
12537 } else {
12538 // This is ill-formed, but provide the context that we would have
12539 // declared the function in, if we were permitted to, for error recovery.
12540 DC = FunctionContainingLocalClass;
12541 }
Richard Smith541b38b2013-09-20 01:15:31 +000012542 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012543
12544 // C++ [class.friend]p6:
12545 // A function can be defined in a friend declaration of a class if and
12546 // only if the class is a non-local class (9.8), the function name is
12547 // unqualified, and the function has namespace scope.
12548 if (D.isFunctionDefinition()) {
12549 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12550 }
12551
12552 // - There's no scope specifier, in which case we just go to the
12553 // appropriate scope and look for a function or function template
12554 // there as appropriate.
12555 } else if (SS.isInvalid() || !SS.isSet()) {
12556 // C++11 [namespace.memdef]p3:
12557 // If the name in a friend declaration is neither qualified nor
12558 // a template-id and the declaration is a function or an
12559 // elaborated-type-specifier, the lookup to determine whether
12560 // the entity has been previously declared shall not consider
12561 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012562 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012563
John McCallf7cfb222010-10-13 05:45:15 +000012564 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012565 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012566
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012567 // Skip class contexts. If someone can cite chapter and verse
12568 // for this behavior, that would be nice --- it's what GCC and
12569 // EDG do, and it seems like a reasonable intent, but the spec
12570 // really only says that checks for unqualified existing
12571 // declarations should stop at the nearest enclosing namespace,
12572 // not that they should only consider the nearest enclosing
12573 // namespace.
12574 while (DC->isRecord())
12575 DC = DC->getParent();
12576
12577 DeclContext *LookupDC = DC;
12578 while (LookupDC->isTransparentContext())
12579 LookupDC = LookupDC->getParent();
12580
12581 while (true) {
12582 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012583
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012584 if (!Previous.empty()) {
12585 DC = LookupDC;
12586 break;
John McCallf4776592010-10-14 22:22:28 +000012587 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012588
12589 if (isTemplateId) {
12590 if (isa<TranslationUnitDecl>(LookupDC)) break;
12591 } else {
12592 if (LookupDC->isFileContext()) break;
12593 }
12594 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012595 }
12596
John McCallccbc0322010-10-13 06:22:15 +000012597 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012598
John McCallde3fd222010-10-12 23:13:28 +000012599 // - There's a non-dependent scope specifier, in which case we
12600 // compute it and do a previous lookup there for a function
12601 // or function template.
12602 } else if (!SS.getScopeRep()->isDependent()) {
12603 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012604 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012605
Craig Topperc3ec1492014-05-26 06:22:03 +000012606 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012607
12608 LookupQualifiedName(Previous, DC);
12609
12610 // Ignore things found implicitly in the wrong scope.
12611 // TODO: better diagnostics for this case. Suggesting the right
12612 // qualified scope would be nice...
12613 LookupResult::Filter F = Previous.makeFilter();
12614 while (F.hasNext()) {
12615 NamedDecl *D = F.next();
12616 if (!DC->InEnclosingNamespaceSetOf(
12617 D->getDeclContext()->getRedeclContext()))
12618 F.erase();
12619 }
12620 F.done();
12621
12622 if (Previous.empty()) {
12623 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012624 Diag(Loc, diag::err_qualified_friend_not_found)
12625 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012626 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012627 }
12628
12629 // C++ [class.friend]p1: A friend of a class is a function or
12630 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012631 if (DC->Equals(CurContext))
12632 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012633 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012634 diag::warn_cxx98_compat_friend_is_member :
12635 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012636
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012637 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012638 // C++ [class.friend]p6:
12639 // A function can be defined in a friend declaration of a class if and
12640 // only if the class is a non-local class (9.8), the function name is
12641 // unqualified, and the function has namespace scope.
12642 SemaDiagnosticBuilder DB
12643 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12644
12645 DB << SS.getScopeRep();
12646 if (DC->isFileContext())
12647 DB << FixItHint::CreateRemoval(SS.getRange());
12648 SS.clear();
12649 }
John McCallde3fd222010-10-12 23:13:28 +000012650
12651 // - There's a scope specifier that does not match any template
12652 // parameter lists, in which case we use some arbitrary context,
12653 // create a method or method template, and wait for instantiation.
12654 // - There's a scope specifier that does match some template
12655 // parameter lists, which we don't handle right now.
12656 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012657 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012658 // C++ [class.friend]p6:
12659 // A function can be defined in a friend declaration of a class if and
12660 // only if the class is a non-local class (9.8), the function name is
12661 // unqualified, and the function has namespace scope.
12662 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12663 << SS.getScopeRep();
12664 }
12665
John McCallde3fd222010-10-12 23:13:28 +000012666 DC = CurContext;
12667 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012668 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012669
John McCallf7cfb222010-10-13 05:45:15 +000012670 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012671 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012672 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12673 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12674 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012675 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012676 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12677 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012678 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012679 }
John McCall07e91c02009-08-06 02:15:43 +000012680 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012681
Douglas Gregordd847ba2011-11-03 16:37:14 +000012682 // FIXME: This is an egregious hack to cope with cases where the scope stack
12683 // does not contain the declaration context, i.e., in an out-of-line
12684 // definition of a class.
12685 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12686 if (!DCScope) {
12687 FakeDCScope.setEntity(DC);
12688 DCScope = &FakeDCScope;
12689 }
Richard Smith114394f2013-08-09 04:35:01 +000012690
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012691 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012692 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012693 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012694 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012695
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012696 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012697
Richard Smith114394f2013-08-09 04:35:01 +000012698 // If we performed typo correction, we might have added a scope specifier
12699 // and changed the decl context.
12700 DC = ND->getDeclContext();
12701
John McCall759e32b2009-08-31 22:39:49 +000012702 // Add the function declaration to the appropriate lookup tables,
12703 // adjusting the redeclarations list as necessary. We don't
12704 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012705 //
John McCall759e32b2009-08-31 22:39:49 +000012706 // Also update the scope-based lookup if the target context's
12707 // lookup context is in lexical scope.
12708 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012709 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012710 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012711 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012712 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012713 }
John McCallaa74a0c2009-08-28 07:59:38 +000012714
12715 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012716 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012717 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012718 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012719 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012720
John McCalla0a96892012-08-10 03:15:35 +000012721 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012722 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012723 } else {
12724 if (DC->isRecord()) CheckFriendAccess(ND);
12725
John McCall2c2eb122010-10-16 06:59:13 +000012726 FunctionDecl *FD;
12727 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12728 FD = FTD->getTemplatedDecl();
12729 else
12730 FD = cast<FunctionDecl>(ND);
12731
David Majnemer502b0ed2013-06-25 23:09:30 +000012732 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12733 // default argument expression, that declaration shall be a definition
12734 // and shall be the only declaration of the function or function
12735 // template in the translation unit.
12736 if (functionDeclHasDefaultArgument(FD)) {
12737 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12738 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12739 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12740 } else if (!D.isFunctionDefinition())
12741 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12742 }
12743
John McCall2c2eb122010-10-16 06:59:13 +000012744 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000012745 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12746 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12747 << SS.getScopeRep() << SS.getRange()
12748 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000012749 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000012750 }
John McCall2c2eb122010-10-16 06:59:13 +000012751 }
John McCallde3fd222010-10-12 23:13:28 +000012752
John McCall48871652010-08-21 09:40:31 +000012753 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012754}
12755
John McCall48871652010-08-21 09:40:31 +000012756void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12757 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012758
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012759 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012760 if (!Fn) {
12761 Diag(DelLoc, diag::err_deleted_non_function);
12762 return;
12763 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012764
Douglas Gregorec9fd132012-01-14 16:38:05 +000012765 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012766 // Don't consider the implicit declaration we generate for explicit
12767 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012768 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12769 Prev->getPreviousDecl()) &&
12770 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012771 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012772 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12773 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12774 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012775 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012776 // If the declaration wasn't the first, we delete the function anyway for
12777 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012778 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012779 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012780
Nico Rieck9de0a572014-05-29 16:51:19 +000012781 // dllimport/dllexport cannot be deleted.
12782 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12783 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12784 Fn->setInvalidDecl();
12785 }
12786
Richard Smithb4d2a152013-04-02 19:38:47 +000012787 if (Fn->isDeleted())
12788 return;
12789
12790 // See if we're deleting a function which is already known to override a
12791 // non-deleted virtual function.
12792 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12793 bool IssuedDiagnostic = false;
12794 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12795 E = MD->end_overridden_methods();
12796 I != E; ++I) {
12797 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12798 if (!IssuedDiagnostic) {
12799 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12800 IssuedDiagnostic = true;
12801 }
12802 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12803 }
12804 }
12805 }
12806
Richard Smithb63b6ee2014-01-22 01:43:19 +000012807 // C++11 [basic.start.main]p3:
12808 // A program that defines main as deleted [...] is ill-formed.
12809 if (Fn->isMain())
12810 Diag(DelLoc, diag::err_deleted_main);
12811
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012812 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012813}
Sebastian Redl4c018662009-04-27 21:33:24 +000012814
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012815void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012816 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012817
12818 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012819 if (MD->getParent()->isDependentType()) {
12820 MD->setDefaulted();
12821 MD->setExplicitlyDefaulted();
12822 return;
12823 }
12824
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012825 CXXSpecialMember Member = getSpecialMember(MD);
12826 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012827 if (!MD->isInvalidDecl())
12828 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012829 return;
12830 }
12831
12832 MD->setDefaulted();
12833 MD->setExplicitlyDefaulted();
12834
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012835 // If this definition appears within the record, do the checking when
12836 // the record is complete.
12837 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012838 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012839 // Find the uninstantiated declaration that actually had the '= default'
12840 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012841 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012842
Richard Smith3901dfe2013-03-27 00:22:47 +000012843 // If the method was defaulted on its first declaration, we will have
12844 // already performed the checking in CheckCompletedCXXClass. Such a
12845 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012846 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012847 return;
12848
Richard Smithd3b5c9082012-07-27 04:22:15 +000012849 CheckExplicitlyDefaultedSpecialMember(MD);
12850
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012851 if (MD->isInvalidDecl())
12852 return;
12853
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012854 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012855 case CXXDefaultConstructor:
12856 DefineImplicitDefaultConstructor(DefaultLoc,
12857 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012858 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012859 case CXXCopyConstructor:
12860 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012861 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012862 case CXXCopyAssignment:
12863 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012864 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012865 case CXXDestructor:
12866 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012867 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012868 case CXXMoveConstructor:
12869 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012870 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012871 case CXXMoveAssignment:
12872 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012873 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012874 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012875 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012876 }
12877 } else {
12878 Diag(DefaultLoc, diag::err_default_special_members);
12879 }
12880}
12881
Sebastian Redl4c018662009-04-27 21:33:24 +000012882static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012883 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012884 Stmt *SubStmt = *CI;
12885 if (!SubStmt)
12886 continue;
12887 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012888 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012889 diag::err_return_in_constructor_handler);
12890 if (!isa<Expr>(SubStmt))
12891 SearchForReturnInStmt(Self, SubStmt);
12892 }
12893}
12894
12895void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12896 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12897 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12898 SearchForReturnInStmt(*this, Handler);
12899 }
12900}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012901
David Blaikie68f71a32013-01-18 23:03:15 +000012902bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012903 const CXXMethodDecl *Old) {
12904 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12905 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12906
12907 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12908
12909 // If the calling conventions match, everything is fine
12910 if (NewCC == OldCC)
12911 return false;
12912
Hans Wennborg2545efe2013-12-11 17:42:11 +000012913 // If the calling conventions mismatch because the new function is static,
12914 // suppress the calling convention mismatch error; the error about static
12915 // function override (err_static_overrides_virtual from
12916 // Sema::CheckFunctionDeclaration) is more clear.
12917 if (New->getStorageClass() == SC_Static)
12918 return false;
12919
Reid Kleckner78af0702013-08-27 23:08:25 +000012920 Diag(New->getLocation(),
12921 diag::err_conflicting_overriding_cc_attributes)
12922 << New->getDeclName() << New->getType() << Old->getType();
12923 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12924 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012925}
12926
Mike Stump11289f42009-09-09 15:08:12 +000012927bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012928 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012929 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12930 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012931
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012932 if (Context.hasSameType(NewTy, OldTy) ||
12933 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012934 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012935
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012936 // Check if the return types are covariant
12937 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012938
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012939 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012940 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12941 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012942 NewClassTy = NewPT->getPointeeType();
12943 OldClassTy = OldPT->getPointeeType();
12944 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012945 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12946 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12947 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12948 NewClassTy = NewRT->getPointeeType();
12949 OldClassTy = OldRT->getPointeeType();
12950 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012951 }
12952 }
Mike Stump11289f42009-09-09 15:08:12 +000012953
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012954 // The return types aren't either both pointers or references to a class type.
12955 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012956 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012957 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012958 << New->getDeclName() << NewTy << OldTy
12959 << New->getReturnTypeSourceRange();
12960 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12961 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012962
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012963 return true;
12964 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012965
Anders Carlssone60365b2009-12-31 18:34:24 +000012966 // C++ [class.virtual]p6:
12967 // If the return type of D::f differs from the return type of B::f, the
12968 // class type in the return type of D::f shall be complete at the point of
12969 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012970 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12971 if (!RT->isBeingDefined() &&
12972 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012973 diag::err_covariant_return_incomplete,
12974 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012975 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012976 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012977
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012978 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012979 // Check if the new class derives from the old class.
12980 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012981 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12982 << New->getDeclName() << NewTy << OldTy
12983 << New->getReturnTypeSourceRange();
12984 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12985 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012986 return true;
12987 }
Mike Stump11289f42009-09-09 15:08:12 +000012988
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012989 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012990 if (CheckDerivedToBaseConversion(
12991 NewClassTy, OldClassTy,
12992 diag::err_covariant_return_inaccessible_base,
12993 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12994 New->getLocation(), New->getReturnTypeSourceRange(),
12995 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012996 // FIXME: this note won't trigger for delayed access control
12997 // diagnostics, and it's impossible to get an undelayed error
12998 // here from access control during the original parse because
12999 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000013000 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13001 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013002 return true;
13003 }
13004 }
Mike Stump11289f42009-09-09 15:08:12 +000013005
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013006 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013007 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013008 Diag(New->getLocation(),
13009 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013010 << New->getDeclName() << NewTy << OldTy
13011 << New->getReturnTypeSourceRange();
13012 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13013 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013014 return true;
13015 };
Mike Stump11289f42009-09-09 15:08:12 +000013016
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013017
13018 // The new class type must have the same or less qualifiers as the old type.
13019 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13020 Diag(New->getLocation(),
13021 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013022 << New->getDeclName() << NewTy << OldTy
13023 << New->getReturnTypeSourceRange();
13024 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13025 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013026 return true;
13027 };
Mike Stump11289f42009-09-09 15:08:12 +000013028
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013029 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013030}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013031
Douglas Gregor21920e372009-12-01 17:24:26 +000013032/// \brief Mark the given method pure.
13033///
13034/// \param Method the method to be marked pure.
13035///
13036/// \param InitRange the source range that covers the "0" initializer.
13037bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000013038 SourceLocation EndLoc = InitRange.getEnd();
13039 if (EndLoc.isValid())
13040 Method->setRangeEnd(EndLoc);
13041
Douglas Gregor21920e372009-12-01 17:24:26 +000013042 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13043 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000013044 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000013045 }
Douglas Gregor21920e372009-12-01 17:24:26 +000013046
13047 if (!Method->isInvalidDecl())
13048 Diag(Method->getLocation(), diag::err_non_virtual_pure)
13049 << Method->getDeclName() << InitRange;
13050 return true;
13051}
13052
Douglas Gregor926410d2012-02-21 02:22:07 +000013053/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013054static bool isStaticDataMember(const Decl *D) {
13055 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13056 return Var->isStaticDataMember();
13057
13058 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000013059}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013060
John McCall1f4ee7b2009-12-19 09:28:58 +000013061/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13062/// an initializer for the out-of-line declaration 'Dcl'. The scope
13063/// is a fresh scope pushed for just this purpose.
13064///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013065/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13066/// static data member of class X, names should be looked up in the scope of
13067/// class X.
John McCall48871652010-08-21 09:40:31 +000013068void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013069 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013070 if (!D || D->isInvalidDecl())
13071 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013072
Richard Smitha2302242013-12-05 07:51:02 +000013073 // We will always have a nested name specifier here, but this declaration
13074 // might not be out of line if the specifier names the current namespace:
13075 // extern int n;
13076 // int ::n = 0;
13077 if (D->isOutOfLine())
13078 EnterDeclaratorContext(S, D->getDeclContext());
13079
Douglas Gregor926410d2012-02-21 02:22:07 +000013080 // If we are parsing the initializer for a static data member, push a
13081 // new expression evaluation context that is associated with this static
13082 // data member.
13083 if (isStaticDataMember(D))
13084 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013085}
13086
13087/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000013088/// initializer for the out-of-line declaration 'D'.
13089void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013090 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013091 if (!D || D->isInvalidDecl())
13092 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013093
Douglas Gregor926410d2012-02-21 02:22:07 +000013094 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000013095 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000013096
Richard Smitha2302242013-12-05 07:51:02 +000013097 if (D->isOutOfLine())
13098 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013099}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013100
13101/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13102/// C++ if/switch/while/for statement.
13103/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000013104DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013105 // C++ 6.4p2:
13106 // The declarator shall not specify a function or an array.
13107 // The type-specifier-seq shall not contain typedef and shall not declare a
13108 // new class or enumeration.
13109 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13110 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013111
13112 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013113 if (!Dcl)
13114 return true;
13115
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013116 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13117 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013118 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013119 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013120 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013121
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013122 return Dcl;
13123}
Anders Carlssonf98849e2009-12-02 17:15:43 +000013124
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013125void Sema::LoadExternalVTableUses() {
13126 if (!ExternalSource)
13127 return;
13128
13129 SmallVector<ExternalVTableUse, 4> VTables;
13130 ExternalSource->ReadUsedVTables(VTables);
13131 SmallVector<VTableUse, 4> NewUses;
13132 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13133 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13134 = VTablesUsed.find(VTables[I].Record);
13135 // Even if a definition wasn't required before, it may be required now.
13136 if (Pos != VTablesUsed.end()) {
13137 if (!Pos->second && VTables[I].DefinitionRequired)
13138 Pos->second = true;
13139 continue;
13140 }
13141
13142 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13143 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13144 }
13145
13146 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13147}
13148
Douglas Gregor88d292c2010-05-13 16:44:06 +000013149void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13150 bool DefinitionRequired) {
13151 // Ignore any vtable uses in unevaluated operands or for classes that do
13152 // not have a vtable.
13153 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000013154 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000013155 return;
13156
Douglas Gregor88d292c2010-05-13 16:44:06 +000013157 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013158 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013159 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13160 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13161 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13162 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000013163 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000013164 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000013165 // list, since we may have already processed the first entry.
13166 if (DefinitionRequired && !Pos.first->second) {
13167 Pos.first->second = true;
13168 } else {
13169 // Otherwise, we can early exit.
13170 return;
13171 }
Hans Wennborg3d791542014-02-24 15:58:24 +000013172 } else {
13173 // The Microsoft ABI requires that we perform the destructor body
13174 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13175 // the deleting destructor is emitted with the vtable, not with the
13176 // destructor definition as in the Itanium ABI.
13177 // If it has a definition, we do the check at that point instead.
13178 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13179 Class->hasUserDeclaredDestructor() &&
13180 !Class->getDestructor()->isDefined() &&
13181 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000013182 CXXDestructorDecl *DD = Class->getDestructor();
13183 ContextRAII SavedContext(*this, DD);
13184 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000013185 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013186 }
13187
13188 // Local classes need to have their virtual members marked
13189 // immediately. For all other classes, we mark their virtual members
13190 // at the end of the translation unit.
13191 if (Class->isLocalClass())
13192 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000013193 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000013194 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000013195}
13196
Douglas Gregor88d292c2010-05-13 16:44:06 +000013197bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013198 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013199 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000013200 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000013201
Douglas Gregor88d292c2010-05-13 16:44:06 +000013202 // Note: The VTableUses vector could grow as a result of marking
13203 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000013204 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000013205 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000013206 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013207 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000013208 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013209 if (!Class)
13210 continue;
13211
13212 SourceLocation Loc = VTableUses[I].second;
13213
Richard Smithd3b5c9082012-07-27 04:22:15 +000013214 bool DefineVTable = true;
13215
Douglas Gregor88d292c2010-05-13 16:44:06 +000013216 // If this class has a key function, but that key function is
13217 // defined in another translation unit, we don't need to emit the
13218 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000013219 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000013220 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000013221 // The key function is in another translation unit.
13222 DefineVTable = false;
13223 TemplateSpecializationKind TSK =
13224 KeyFunction->getTemplateSpecializationKind();
13225 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13226 TSK != TSK_ImplicitInstantiation &&
13227 "Instantiations don't have key functions");
13228 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013229 } else if (!KeyFunction) {
13230 // If we have a class with no key function that is the subject
13231 // of an explicit instantiation declaration, suppress the
13232 // vtable; it will live with the explicit instantiation
13233 // definition.
13234 bool IsExplicitInstantiationDeclaration
13235 = Class->getTemplateSpecializationKind()
13236 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000013237 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000013238 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000013239 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013240 if (TSK == TSK_ExplicitInstantiationDeclaration)
13241 IsExplicitInstantiationDeclaration = true;
13242 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13243 IsExplicitInstantiationDeclaration = false;
13244 break;
13245 }
13246 }
13247
13248 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000013249 DefineVTable = false;
13250 }
13251
13252 // The exception specifications for all virtual members may be needed even
13253 // if we are not providing an authoritative form of the vtable in this TU.
13254 // We may choose to emit it available_externally anyway.
13255 if (!DefineVTable) {
13256 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13257 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013258 }
13259
13260 // Mark all of the virtual members of this class as referenced, so
13261 // that we can build a vtable. Then, tell the AST consumer that a
13262 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000013263 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013264 MarkVirtualMembersReferenced(Loc, Class);
13265 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000013266 if (VTablesUsed[Canonical])
13267 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000013268
13269 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000013270 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000013271 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013272 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000013273 if (!KeyFunction ||
13274 (KeyFunction->hasBody(KeyFunctionDef) &&
13275 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000013276 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13277 TSK_ExplicitInstantiationDefinition
13278 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13279 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013280 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000013281 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013282 VTableUses.clear();
13283
Douglas Gregor97509692011-04-22 22:25:37 +000013284 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000013285}
Anders Carlsson82fccd02009-12-07 08:24:59 +000013286
Richard Smithd3b5c9082012-07-27 04:22:15 +000013287void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13288 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000013289 for (const auto *I : RD->methods())
13290 if (I->isVirtual() && !I->isPure())
13291 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000013292}
13293
Rafael Espindola5b334082010-03-26 00:36:59 +000013294void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13295 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000013296 // Mark all functions which will appear in RD's vtable as used.
13297 CXXFinalOverriderMap FinalOverriders;
13298 RD->getFinalOverriders(FinalOverriders);
13299 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13300 E = FinalOverriders.end();
13301 I != E; ++I) {
13302 for (OverridingMethods::const_iterator OI = I->second.begin(),
13303 OE = I->second.end();
13304 OI != OE; ++OI) {
13305 assert(OI->second.size() > 0 && "no final overrider");
13306 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000013307
Richard Smith4ff9ff92012-07-07 06:59:51 +000013308 // C++ [basic.def.odr]p2:
13309 // [...] A virtual member function is used if it is not pure. [...]
13310 if (!Overrider->isPure())
13311 MarkFunctionReferenced(Loc, Overrider);
13312 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013313 }
Rafael Espindola5b334082010-03-26 00:36:59 +000013314
13315 // Only classes that have virtual bases need a VTT.
13316 if (RD->getNumVBases() == 0)
13317 return;
13318
Aaron Ballman574705e2014-03-13 15:41:46 +000013319 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000013320 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000013321 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000013322 if (Base->getNumVBases() == 0)
13323 continue;
13324 MarkVirtualMembersReferenced(Loc, Base);
13325 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013326}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013327
13328/// SetIvarInitializers - This routine builds initialization ASTs for the
13329/// Objective-C implementation whose ivars need be initialized.
13330void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013331 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013332 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000013333 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013334 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013335 CollectIvarsToConstructOrDestruct(OID, ivars);
13336 if (ivars.empty())
13337 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013338 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013339 for (unsigned i = 0; i < ivars.size(); i++) {
13340 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000013341 if (Field->isInvalidDecl())
13342 continue;
13343
Alexis Hunt1d792652011-01-08 20:30:50 +000013344 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013345 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13346 InitializationKind InitKind =
13347 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000013348
13349 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13350 ExprResult MemberInit =
13351 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000013352 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013353 // Note, MemberInit could actually come back empty if no initialization
13354 // is required (e.g., because it would call a trivial default constructor)
13355 if (!MemberInit.get() || MemberInit.isInvalid())
13356 continue;
John McCallacf0ee52010-10-08 02:01:28 +000013357
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013358 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000013359 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13360 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013361 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000013362 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013363 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000013364
13365 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000013366 if (const RecordType *RecordTy =
13367 Context.getBaseElementType(Field->getType())
13368 ->getAs<RecordType>()) {
13369 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000013370 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013371 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000013372 CheckDestructorAccess(Field->getLocation(), Destructor,
13373 PDiag(diag::err_access_dtor_ivar)
13374 << Context.getBaseElementType(Field->getType()));
13375 }
13376 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013377 }
13378 ObjCImplementation->setIvarInitializers(Context,
13379 AllToInit.data(), AllToInit.size());
13380 }
13381}
Alexis Hunt6118d662011-05-04 05:57:24 +000013382
Alexis Hunt27a761d2011-05-04 23:29:54 +000013383static
13384void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13385 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13386 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13387 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13388 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000013389 if (Ctor->isInvalidDecl())
13390 return;
13391
Richard Smith802c4b72012-08-23 06:16:52 +000013392 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13393
13394 // Target may not be determinable yet, for instance if this is a dependent
13395 // call in an uninstantiated template.
13396 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013397 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000013398 (void)Target->hasBody(FNTarget);
13399 Target = const_cast<CXXConstructorDecl*>(
13400 cast_or_null<CXXConstructorDecl>(FNTarget));
13401 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000013402
13403 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13404 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000013405 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013406
David Blaikie82e95a32014-11-19 07:49:47 +000013407 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013408 return;
13409
13410 // We know that beyond here, we aren't chaining into a cycle.
13411 if (!Target || !Target->isDelegatingConstructor() ||
13412 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013413 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013414 Current.clear();
13415 // We've hit a cycle.
13416 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13417 Current.count(TCanonical)) {
13418 // If we haven't diagnosed this cycle yet, do so now.
13419 if (!Invalid.count(TCanonical)) {
13420 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000013421 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013422 << Ctor;
13423
Richard Smith802c4b72012-08-23 06:16:52 +000013424 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000013425 if (TCanonical != Canonical)
13426 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13427
13428 CXXConstructorDecl *C = Target;
13429 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013430 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013431 (void)C->getTargetConstructor()->hasBody(FNTarget);
13432 assert(FNTarget && "Ctor cycle through bodiless function");
13433
Richard Smith802c4b72012-08-23 06:16:52 +000013434 C = const_cast<CXXConstructorDecl*>(
13435 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000013436 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13437 }
13438 }
13439
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013440 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013441 Current.clear();
13442 } else {
13443 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13444 }
13445}
13446
13447
Alexis Hunt6118d662011-05-04 05:57:24 +000013448void Sema::CheckDelegatingCtorCycles() {
13449 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13450
Douglas Gregorbae31202011-07-27 21:57:17 +000013451 for (DelegatingCtorDeclsType::iterator
13452 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000013453 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000013454 I != E; ++I)
13455 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000013456
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013457 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13458 CE = Invalid.end();
13459 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013460 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000013461}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013462
Douglas Gregor3024f072012-04-16 07:05:22 +000013463namespace {
13464 /// \brief AST visitor that finds references to the 'this' expression.
13465 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13466 Sema &S;
13467
13468 public:
13469 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13470
13471 bool VisitCXXThisExpr(CXXThisExpr *E) {
13472 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13473 << E->isImplicit();
13474 return false;
13475 }
13476 };
13477}
13478
13479bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13480 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13481 if (!TSInfo)
13482 return false;
13483
13484 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013485 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000013486 if (!ProtoTL)
13487 return false;
13488
13489 // C++11 [expr.prim.general]p3:
13490 // [The expression this] shall not appear before the optional
13491 // cv-qualifier-seq and it shall not appear within the declaration of a
13492 // static member function (although its type and value category are defined
13493 // within a static member function as they are within a non-static member
13494 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000013495 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000013496 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000013497 FindCXXThisExpr Finder(*this);
13498
13499 // If the return type came after the cv-qualifier-seq, check it now.
13500 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000013501 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000013502 return true;
13503
13504 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000013505 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13506 return true;
13507
13508 return checkThisInStaticMemberFunctionAttributes(Method);
13509}
13510
13511bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13512 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13513 if (!TSInfo)
13514 return false;
13515
13516 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013517 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000013518 if (!ProtoTL)
13519 return false;
13520
David Blaikie6adc78e2013-02-18 22:06:02 +000013521 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000013522 FindCXXThisExpr Finder(*this);
13523
Douglas Gregor3024f072012-04-16 07:05:22 +000013524 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000013525 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000013526 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000013527 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000013528 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000013529 case EST_DynamicNone:
13530 case EST_MSAny:
13531 case EST_None:
13532 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000013533
Douglas Gregor3024f072012-04-16 07:05:22 +000013534 case EST_ComputedNoexcept:
13535 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13536 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000013537
Douglas Gregor3024f072012-04-16 07:05:22 +000013538 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000013539 for (const auto &E : Proto->exceptions()) {
13540 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000013541 return true;
13542 }
13543 break;
13544 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013545
13546 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013547}
13548
13549bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13550 FindCXXThisExpr Finder(*this);
13551
13552 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013553 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013554 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013555 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013556 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013557 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013558 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013559 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013560 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013561 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013562 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013563 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013564 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013565 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013566 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013567 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013568 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013569 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013570 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013571 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013572 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013573 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013574 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013575 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013576 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013577 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013578 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013579 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013580 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013581 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013582 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013583
13584 if (Arg && !Finder.TraverseStmt(Arg))
13585 return true;
13586
13587 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13588 if (!Finder.TraverseStmt(Args[I]))
13589 return true;
13590 }
13591 }
13592
13593 return false;
13594}
13595
Richard Smith2e321552014-11-12 02:00:47 +000013596void Sema::checkExceptionSpecification(
13597 bool IsTopLevel, ExceptionSpecificationType EST,
13598 ArrayRef<ParsedType> DynamicExceptions,
13599 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13600 SmallVectorImpl<QualType> &Exceptions,
13601 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013602 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013603 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013604 if (EST == EST_Dynamic) {
13605 Exceptions.reserve(DynamicExceptions.size());
13606 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13607 // FIXME: Preserve type source info.
13608 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13609
Richard Smith2e321552014-11-12 02:00:47 +000013610 if (IsTopLevel) {
13611 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13612 collectUnexpandedParameterPacks(ET, Unexpanded);
13613 if (!Unexpanded.empty()) {
13614 DiagnoseUnexpandedParameterPacks(
13615 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13616 Unexpanded);
13617 continue;
13618 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013619 }
13620
13621 // Check that the type is valid for an exception spec, and
13622 // drop it if not.
13623 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13624 Exceptions.push_back(ET);
13625 }
Richard Smith8acb4282014-07-31 21:57:55 +000013626 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013627 return;
13628 }
Richard Smith8acb4282014-07-31 21:57:55 +000013629
Douglas Gregor433e0532012-04-16 18:27:27 +000013630 if (EST == EST_ComputedNoexcept) {
13631 // If an error occurred, there's no expression here.
13632 if (NoexceptExpr) {
13633 assert((NoexceptExpr->isTypeDependent() ||
13634 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13635 Context.BoolTy) &&
13636 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000013637 if (IsTopLevel && NoexceptExpr &&
13638 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013639 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013640 return;
13641 }
Richard Smith8acb4282014-07-31 21:57:55 +000013642
Douglas Gregor433e0532012-04-16 18:27:27 +000013643 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013644 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013645 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013646 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013647 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013648 }
13649 return;
13650 }
13651}
13652
Richard Smith0b3a4622014-11-13 20:01:57 +000013653void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13654 ExceptionSpecificationType EST,
13655 SourceRange SpecificationRange,
13656 ArrayRef<ParsedType> DynamicExceptions,
13657 ArrayRef<SourceRange> DynamicExceptionRanges,
13658 Expr *NoexceptExpr) {
13659 if (!MethodD)
13660 return;
13661
13662 // Dig out the method we're referring to.
13663 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13664 MethodD = FunTmpl->getTemplatedDecl();
13665
13666 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13667 if (!Method)
13668 return;
13669
13670 // Check the exception specification.
13671 llvm::SmallVector<QualType, 4> Exceptions;
13672 FunctionProtoType::ExceptionSpecInfo ESI;
13673 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13674 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13675 ESI);
13676
13677 // Update the exception specification on the function type.
13678 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13679
13680 if (Method->isStatic())
13681 checkThisInStaticMemberFunctionExceptionSpec(Method);
13682
13683 if (Method->isVirtual()) {
13684 // Check overrides, which we previously had to delay.
13685 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13686 OEnd = Method->end_overridden_methods();
13687 O != OEnd; ++O)
13688 CheckOverridingFunctionExceptionSpec(Method, *O);
13689 }
13690}
13691
John McCall5e77d762013-04-16 07:28:30 +000013692/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13693///
13694MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13695 SourceLocation DeclStart,
13696 Declarator &D, Expr *BitWidth,
13697 InClassInitStyle InitStyle,
13698 AccessSpecifier AS,
13699 AttributeList *MSPropertyAttr) {
13700 IdentifierInfo *II = D.getIdentifier();
13701 if (!II) {
13702 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013703 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013704 }
13705 SourceLocation Loc = D.getIdentifierLoc();
13706
13707 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13708 QualType T = TInfo->getType();
13709 if (getLangOpts().CPlusPlus) {
13710 CheckExtraCXXDefaultArguments(D);
13711
13712 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13713 UPPC_DataMemberType)) {
13714 D.setInvalidType();
13715 T = Context.IntTy;
13716 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13717 }
13718 }
13719
13720 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13721
13722 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13723 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13724 diag::err_invalid_thread)
13725 << DeclSpec::getSpecifierName(TSCS);
13726
13727 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013728 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013729 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13730 LookupName(Previous, S);
13731 switch (Previous.getResultKind()) {
13732 case LookupResult::Found:
13733 case LookupResult::FoundUnresolvedValue:
13734 PrevDecl = Previous.getAsSingle<NamedDecl>();
13735 break;
13736
13737 case LookupResult::FoundOverloaded:
13738 PrevDecl = Previous.getRepresentativeDecl();
13739 break;
13740
13741 case LookupResult::NotFound:
13742 case LookupResult::NotFoundInCurrentInstantiation:
13743 case LookupResult::Ambiguous:
13744 break;
13745 }
13746
13747 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13748 // Maybe we will complain about the shadowed template parameter.
13749 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13750 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013751 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013752 }
13753
13754 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013755 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013756
13757 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013758 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013759 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13760 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013761 ProcessDeclAttributes(TUScope, NewPD, D);
13762 NewPD->setAccess(AS);
13763
13764 if (NewPD->isInvalidDecl())
13765 Record->setInvalidDecl();
13766
13767 if (D.getDeclSpec().isModulePrivateSpecified())
13768 NewPD->setModulePrivate();
13769
13770 if (NewPD->isInvalidDecl() && PrevDecl) {
13771 // Don't introduce NewFD into scope; there's already something
13772 // with the same name in the same scope.
13773 } else if (II) {
13774 PushOnScopeChains(NewPD, S);
13775 } else
13776 Record->addDecl(NewPD);
13777
13778 return NewPD;
13779}